Move function dependent resetting of a subtarget variable out of the
[oota-llvm.git] / lib / Target / ARM / ARMISelLowering.cpp
1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "ARMISelLowering.h"
16 #include "ARMCallingConv.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMPerfectShuffle.h"
20 #include "ARMSubtarget.h"
21 #include "ARMTargetMachine.h"
22 #include "ARMTargetObjectFile.h"
23 #include "MCTargetDesc/ARMAddressingModes.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/CodeGen/CallingConvLower.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineBasicBlock.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/SelectionDAG.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/GlobalValue.h"
39 #include "llvm/IR/IRBuilder.h"
40 #include "llvm/IR/Instruction.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/IR/Type.h"
44 #include "llvm/MC/MCSectionMachO.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include <utility>
51 using namespace llvm;
52
53 #define DEBUG_TYPE "arm-isel"
54
55 STATISTIC(NumTailCalls, "Number of tail calls");
56 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
57 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
58
59 cl::opt<bool>
60 EnableARMLongCalls("arm-long-calls", cl::Hidden,
61   cl::desc("Generate calls via indirect call instructions"),
62   cl::init(false));
63
64 static cl::opt<bool>
65 ARMInterworking("arm-interworking", cl::Hidden,
66   cl::desc("Enable / disable ARM interworking (for debugging only)"),
67   cl::init(true));
68
69 namespace {
70   class ARMCCState : public CCState {
71   public:
72     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
73                const TargetMachine &TM, SmallVectorImpl<CCValAssign> &locs,
74                LLVMContext &C, ParmContext PC)
75         : CCState(CC, isVarArg, MF, TM, locs, C) {
76       assert(((PC == Call) || (PC == Prologue)) &&
77              "ARMCCState users must specify whether their context is call"
78              "or prologue generation.");
79       CallOrPrologue = PC;
80     }
81   };
82 }
83
84 // The APCS parameter registers.
85 static const MCPhysReg GPRArgRegs[] = {
86   ARM::R0, ARM::R1, ARM::R2, ARM::R3
87 };
88
89 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
90                                        MVT PromotedBitwiseVT) {
91   if (VT != PromotedLdStVT) {
92     setOperationAction(ISD::LOAD, VT, Promote);
93     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
94
95     setOperationAction(ISD::STORE, VT, Promote);
96     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
97   }
98
99   MVT ElemTy = VT.getVectorElementType();
100   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
101     setOperationAction(ISD::SETCC, VT, Custom);
102   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
103   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
104   if (ElemTy == MVT::i32) {
105     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
106     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
107     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
108     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
109   } else {
110     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
111     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
112     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
113     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
114   }
115   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
116   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
117   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
118   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
119   setOperationAction(ISD::SELECT,            VT, Expand);
120   setOperationAction(ISD::SELECT_CC,         VT, Expand);
121   setOperationAction(ISD::VSELECT,           VT, Expand);
122   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
123   if (VT.isInteger()) {
124     setOperationAction(ISD::SHL, VT, Custom);
125     setOperationAction(ISD::SRA, VT, Custom);
126     setOperationAction(ISD::SRL, VT, Custom);
127   }
128
129   // Promote all bit-wise operations.
130   if (VT.isInteger() && VT != PromotedBitwiseVT) {
131     setOperationAction(ISD::AND, VT, Promote);
132     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
133     setOperationAction(ISD::OR,  VT, Promote);
134     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
135     setOperationAction(ISD::XOR, VT, Promote);
136     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
137   }
138
139   // Neon does not support vector divide/remainder operations.
140   setOperationAction(ISD::SDIV, VT, Expand);
141   setOperationAction(ISD::UDIV, VT, Expand);
142   setOperationAction(ISD::FDIV, VT, Expand);
143   setOperationAction(ISD::SREM, VT, Expand);
144   setOperationAction(ISD::UREM, VT, Expand);
145   setOperationAction(ISD::FREM, VT, Expand);
146 }
147
148 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
149   addRegisterClass(VT, &ARM::DPRRegClass);
150   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
151 }
152
153 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
154   addRegisterClass(VT, &ARM::DPairRegClass);
155   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
156 }
157
158 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
159   if (TT.isOSBinFormatMachO())
160     return new TargetLoweringObjectFileMachO();
161   if (TT.isOSWindows())
162     return new TargetLoweringObjectFileCOFF();
163   return new ARMElfTargetObjectFile();
164 }
165
166 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
167     : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
168   Subtarget = &TM.getSubtarget<ARMSubtarget>();
169   RegInfo = TM.getRegisterInfo();
170   Itins = TM.getInstrItineraryData();
171
172   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
173
174   if (Subtarget->isTargetMachO()) {
175     // Uses VFP for Thumb libfuncs if available.
176     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
177         Subtarget->hasARMOps() && !TM.Options.UseSoftFloat) {
178       // Single-precision floating-point arithmetic.
179       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
180       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
181       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
182       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
183
184       // Double-precision floating-point arithmetic.
185       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
186       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
187       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
188       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
189
190       // Single-precision comparisons.
191       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
192       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
193       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
194       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
195       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
196       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
197       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
198       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
199
200       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
201       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
202       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
203       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
204       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
205       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
206       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
207       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
208
209       // Double-precision comparisons.
210       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
211       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
212       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
213       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
214       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
215       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
216       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
217       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
218
219       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
220       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
221       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
222       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
223       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
224       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
225       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
226       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
227
228       // Floating-point to integer conversions.
229       // i64 conversions are done via library routines even when generating VFP
230       // instructions, so use the same ones.
231       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
232       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
233       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
234       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
235
236       // Conversions between floating types.
237       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
238       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
239
240       // Integer to floating-point conversions.
241       // i64 conversions are done via library routines even when generating VFP
242       // instructions, so use the same ones.
243       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
244       // e.g., __floatunsidf vs. __floatunssidfvfp.
245       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
246       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
247       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
248       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
249     }
250   }
251
252   // These libcalls are not available in 32-bit.
253   setLibcallName(RTLIB::SHL_I128, nullptr);
254   setLibcallName(RTLIB::SRL_I128, nullptr);
255   setLibcallName(RTLIB::SRA_I128, nullptr);
256
257   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
258       !Subtarget->isTargetWindows()) {
259     static const struct {
260       const RTLIB::Libcall Op;
261       const char * const Name;
262       const CallingConv::ID CC;
263       const ISD::CondCode Cond;
264     } LibraryCalls[] = {
265       // Double-precision floating-point arithmetic helper functions
266       // RTABI chapter 4.1.2, Table 2
267       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
268       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
269       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
270       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
271
272       // Double-precision floating-point comparison helper functions
273       // RTABI chapter 4.1.2, Table 3
274       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
275       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
276       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
277       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
278       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
279       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
280       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
281       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
282
283       // Single-precision floating-point arithmetic helper functions
284       // RTABI chapter 4.1.2, Table 4
285       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
286       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
287       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
288       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
289
290       // Single-precision floating-point comparison helper functions
291       // RTABI chapter 4.1.2, Table 5
292       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
293       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
294       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
295       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
296       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
297       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
298       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
299       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
300
301       // Floating-point to integer conversions.
302       // RTABI chapter 4.1.2, Table 6
303       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
304       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
307       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
308       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
309       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311
312       // Conversions between floating types.
313       // RTABI chapter 4.1.2, Table 7
314       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
315       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316
317       // Integer to floating-point conversions.
318       // RTABI chapter 4.1.2, Table 8
319       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
320       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327
328       // Long long helper functions
329       // RTABI chapter 4.2, Table 9
330       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
331       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
332       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334
335       // Integer division functions
336       // RTABI chapter 4.3.1
337       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345
346       // Memory operations
347       // RTABI chapter 4.3.4
348       { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
349       { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
350       { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
351     };
352
353     for (const auto &LC : LibraryCalls) {
354       setLibcallName(LC.Op, LC.Name);
355       setLibcallCallingConv(LC.Op, LC.CC);
356       if (LC.Cond != ISD::SETCC_INVALID)
357         setCmpLibcallCC(LC.Op, LC.Cond);
358     }
359   }
360
361   if (Subtarget->isTargetWindows()) {
362     static const struct {
363       const RTLIB::Libcall Op;
364       const char * const Name;
365       const CallingConv::ID CC;
366     } LibraryCalls[] = {
367       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
368       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
369       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
370       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
371       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
372       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
373       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
374       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
375     };
376
377     for (const auto &LC : LibraryCalls) {
378       setLibcallName(LC.Op, LC.Name);
379       setLibcallCallingConv(LC.Op, LC.CC);
380     }
381   }
382
383   // Use divmod compiler-rt calls for iOS 5.0 and later.
384   if (Subtarget->getTargetTriple().isiOS() &&
385       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
386     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
387     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
388   }
389
390   if (Subtarget->isThumb1Only())
391     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
392   else
393     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
394   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
395       !Subtarget->isThumb1Only()) {
396     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
397     if (!Subtarget->isFPOnlySP())
398       addRegisterClass(MVT::f64, &ARM::DPRRegClass);
399
400     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
401   }
402
403   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
404        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
405     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
406          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
407       setTruncStoreAction((MVT::SimpleValueType)VT,
408                           (MVT::SimpleValueType)InnerVT, Expand);
409     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
410     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
411     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
412
413     setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
414     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
415     setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
416     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
417
418     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
419   }
420
421   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
422   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
423
424   if (Subtarget->hasNEON()) {
425     addDRTypeForNEON(MVT::v2f32);
426     addDRTypeForNEON(MVT::v8i8);
427     addDRTypeForNEON(MVT::v4i16);
428     addDRTypeForNEON(MVT::v2i32);
429     addDRTypeForNEON(MVT::v1i64);
430
431     addQRTypeForNEON(MVT::v4f32);
432     addQRTypeForNEON(MVT::v2f64);
433     addQRTypeForNEON(MVT::v16i8);
434     addQRTypeForNEON(MVT::v8i16);
435     addQRTypeForNEON(MVT::v4i32);
436     addQRTypeForNEON(MVT::v2i64);
437
438     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
439     // neither Neon nor VFP support any arithmetic operations on it.
440     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
441     // supported for v4f32.
442     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
443     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
444     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
445     // FIXME: Code duplication: FDIV and FREM are expanded always, see
446     // ARMTargetLowering::addTypeForNEON method for details.
447     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
448     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
449     // FIXME: Create unittest.
450     // In another words, find a way when "copysign" appears in DAG with vector
451     // operands.
452     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
453     // FIXME: Code duplication: SETCC has custom operation action, see
454     // ARMTargetLowering::addTypeForNEON method for details.
455     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
456     // FIXME: Create unittest for FNEG and for FABS.
457     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
458     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
459     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
460     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
461     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
462     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
463     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
464     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
465     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
466     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
467     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
468     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
469     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
470     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
471     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
472     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
473     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
474     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
475     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
476
477     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
478     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
479     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
480     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
481     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
482     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
483     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
484     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
485     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
486     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
487     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
488     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
489     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
490     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
491     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
492
493     // Mark v2f32 intrinsics.
494     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
495     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
496     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
497     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
498     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
499     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
500     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
501     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
502     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
503     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
504     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
505     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
506     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
507     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
508     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
509
510     // Neon does not support some operations on v1i64 and v2i64 types.
511     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
512     // Custom handling for some quad-vector types to detect VMULL.
513     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
514     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
515     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
516     // Custom handling for some vector types to avoid expensive expansions
517     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
518     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
519     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
520     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
521     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
522     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
523     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
524     // a destination type that is wider than the source, and nor does
525     // it have a FP_TO_[SU]INT instruction with a narrower destination than
526     // source.
527     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
528     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
529     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
530     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
531
532     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
533     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
534
535     // NEON does not have single instruction CTPOP for vectors with element
536     // types wider than 8-bits.  However, custom lowering can leverage the
537     // v8i8/v16i8 vcnt instruction.
538     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
539     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
540     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
541     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
542
543     // NEON only has FMA instructions as of VFP4.
544     if (!Subtarget->hasVFP4()) {
545       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
546       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
547     }
548
549     setTargetDAGCombine(ISD::INTRINSIC_VOID);
550     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
551     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
552     setTargetDAGCombine(ISD::SHL);
553     setTargetDAGCombine(ISD::SRL);
554     setTargetDAGCombine(ISD::SRA);
555     setTargetDAGCombine(ISD::SIGN_EXTEND);
556     setTargetDAGCombine(ISD::ZERO_EXTEND);
557     setTargetDAGCombine(ISD::ANY_EXTEND);
558     setTargetDAGCombine(ISD::SELECT_CC);
559     setTargetDAGCombine(ISD::BUILD_VECTOR);
560     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
561     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
562     setTargetDAGCombine(ISD::STORE);
563     setTargetDAGCombine(ISD::FP_TO_SINT);
564     setTargetDAGCombine(ISD::FP_TO_UINT);
565     setTargetDAGCombine(ISD::FDIV);
566
567     // It is legal to extload from v4i8 to v4i16 or v4i32.
568     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
569                   MVT::v4i16, MVT::v2i16,
570                   MVT::v2i32};
571     for (unsigned i = 0; i < 6; ++i) {
572       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
573       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
574       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
575     }
576   }
577
578   // ARM and Thumb2 support UMLAL/SMLAL.
579   if (!Subtarget->isThumb1Only())
580     setTargetDAGCombine(ISD::ADDC);
581
582
583   computeRegisterProperties();
584
585   // ARM does not have f32 extending load.
586   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
587
588   // ARM does not have i1 sign extending load.
589   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
590
591   // ARM supports all 4 flavors of integer indexed load / store.
592   if (!Subtarget->isThumb1Only()) {
593     for (unsigned im = (unsigned)ISD::PRE_INC;
594          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
595       setIndexedLoadAction(im,  MVT::i1,  Legal);
596       setIndexedLoadAction(im,  MVT::i8,  Legal);
597       setIndexedLoadAction(im,  MVT::i16, Legal);
598       setIndexedLoadAction(im,  MVT::i32, Legal);
599       setIndexedStoreAction(im, MVT::i1,  Legal);
600       setIndexedStoreAction(im, MVT::i8,  Legal);
601       setIndexedStoreAction(im, MVT::i16, Legal);
602       setIndexedStoreAction(im, MVT::i32, Legal);
603     }
604   }
605
606   setOperationAction(ISD::SADDO, MVT::i32, Custom);
607   setOperationAction(ISD::UADDO, MVT::i32, Custom);
608   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
609   setOperationAction(ISD::USUBO, MVT::i32, Custom);
610
611   // i64 operation support.
612   setOperationAction(ISD::MUL,     MVT::i64, Expand);
613   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
614   if (Subtarget->isThumb1Only()) {
615     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
616     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
617   }
618   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
619       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
620     setOperationAction(ISD::MULHS, MVT::i32, Expand);
621
622   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
623   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
624   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
625   setOperationAction(ISD::SRL,       MVT::i64, Custom);
626   setOperationAction(ISD::SRA,       MVT::i64, Custom);
627
628   if (!Subtarget->isThumb1Only()) {
629     // FIXME: We should do this for Thumb1 as well.
630     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
631     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
632     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
633     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
634   }
635
636   // ARM does not have ROTL.
637   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
638   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
639   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
640   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
641     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
642
643   // These just redirect to CTTZ and CTLZ on ARM.
644   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
645   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
646
647   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
648
649   // Only ARMv6 has BSWAP.
650   if (!Subtarget->hasV6Ops())
651     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
652
653   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
654       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
655     // These are expanded into libcalls if the cpu doesn't have HW divider.
656     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
657     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
658   }
659
660   // FIXME: Also set divmod for SREM on EABI
661   setOperationAction(ISD::SREM,  MVT::i32, Expand);
662   setOperationAction(ISD::UREM,  MVT::i32, Expand);
663   // Register based DivRem for AEABI (RTABI 4.2)
664   if (Subtarget->isTargetAEABI()) {
665     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
666     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
667     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
668     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
669     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
670     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
671     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
672     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
673
674     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
675     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
676     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
677     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
678     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
679     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
680     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
681     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
682
683     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
684     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
685   } else {
686     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
687     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
688   }
689
690   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
691   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
692   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
693   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
694   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
695
696   setOperationAction(ISD::TRAP, MVT::Other, Legal);
697
698   // Use the default implementation.
699   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
700   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
701   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
702   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
703   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
704   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
705
706   if (!Subtarget->isTargetMachO()) {
707     // Non-MachO platforms may return values in these registers via the
708     // personality function.
709     setExceptionPointerRegister(ARM::R0);
710     setExceptionSelectorRegister(ARM::R1);
711   }
712
713   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
714     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
715   else
716     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
717
718   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
719   // the default expansion.
720   if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
721     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
722     // to ldrex/strex loops already.
723     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
724
725     // On v8, we have particularly efficient implementations of atomic fences
726     // if they can be combined with nearby atomic loads and stores.
727     if (!Subtarget->hasV8Ops()) {
728       // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
729       setInsertFencesForAtomic(true);
730     }
731   } else {
732     // If there's anything we can use as a barrier, go through custom lowering
733     // for ATOMIC_FENCE.
734     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
735                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
736
737     // Set them all for expansion, which will force libcalls.
738     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
739     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
740     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
741     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
742     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
743     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
744     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
745     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
746     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
747     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
748     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
749     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
750     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
751     // Unordered/Monotonic case.
752     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
753     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
754   }
755
756   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
757
758   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
759   if (!Subtarget->hasV6Ops()) {
760     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
761     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
762   }
763   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
764
765   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
766       !Subtarget->isThumb1Only()) {
767     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
768     // iff target supports vfp2.
769     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
770     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
771   }
772
773   // We want to custom lower some of our intrinsics.
774   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
775   if (Subtarget->isTargetDarwin()) {
776     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
777     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
778     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
779   }
780
781   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
782   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
783   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
784   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
785   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
786   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
787   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
788   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
789   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
790
791   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
792   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
793   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
794   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
795   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
796
797   // We don't support sin/cos/fmod/copysign/pow
798   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
799   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
800   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
801   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
802   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
803   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
804   setOperationAction(ISD::FREM,      MVT::f64, Expand);
805   setOperationAction(ISD::FREM,      MVT::f32, Expand);
806   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
807       !Subtarget->isThumb1Only()) {
808     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
809     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
810   }
811   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
812   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
813
814   if (!Subtarget->hasVFP4()) {
815     setOperationAction(ISD::FMA, MVT::f64, Expand);
816     setOperationAction(ISD::FMA, MVT::f32, Expand);
817   }
818
819   // Various VFP goodness
820   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
821     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
822     if (Subtarget->hasVFP2()) {
823       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
824       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
825       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
826       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
827     }
828     // Special handling for half-precision FP.
829     if (!Subtarget->hasFP16()) {
830       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
831       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
832     }
833   }
834
835   // Combine sin / cos into one node or libcall if possible.
836   if (Subtarget->hasSinCos()) {
837     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
838     setLibcallName(RTLIB::SINCOS_F64, "sincos");
839     if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
840       // For iOS, we don't want to the normal expansion of a libcall to
841       // sincos. We want to issue a libcall to __sincos_stret.
842       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
843       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
844     }
845   }
846
847   // We have target-specific dag combine patterns for the following nodes:
848   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
849   setTargetDAGCombine(ISD::ADD);
850   setTargetDAGCombine(ISD::SUB);
851   setTargetDAGCombine(ISD::MUL);
852   setTargetDAGCombine(ISD::AND);
853   setTargetDAGCombine(ISD::OR);
854   setTargetDAGCombine(ISD::XOR);
855
856   if (Subtarget->hasV6Ops())
857     setTargetDAGCombine(ISD::SRL);
858
859   setStackPointerRegisterToSaveRestore(ARM::SP);
860
861   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
862       !Subtarget->hasVFP2())
863     setSchedulingPreference(Sched::RegPressure);
864   else
865     setSchedulingPreference(Sched::Hybrid);
866
867   //// temporary - rewrite interface to use type
868   MaxStoresPerMemset = 8;
869   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
870   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
871   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
872   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
873   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
874
875   // On ARM arguments smaller than 4 bytes are extended, so all arguments
876   // are at least 4 bytes aligned.
877   setMinStackArgumentAlignment(4);
878
879   // Prefer likely predicted branches to selects on out-of-order cores.
880   PredictableSelectIsExpensive = Subtarget->isLikeA9();
881
882   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
883 }
884
885 // FIXME: It might make sense to define the representative register class as the
886 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
887 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
888 // SPR's representative would be DPR_VFP2. This should work well if register
889 // pressure tracking were modified such that a register use would increment the
890 // pressure of the register class's representative and all of it's super
891 // classes' representatives transitively. We have not implemented this because
892 // of the difficulty prior to coalescing of modeling operand register classes
893 // due to the common occurrence of cross class copies and subregister insertions
894 // and extractions.
895 std::pair<const TargetRegisterClass*, uint8_t>
896 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
897   const TargetRegisterClass *RRC = nullptr;
898   uint8_t Cost = 1;
899   switch (VT.SimpleTy) {
900   default:
901     return TargetLowering::findRepresentativeClass(VT);
902   // Use DPR as representative register class for all floating point
903   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
904   // the cost is 1 for both f32 and f64.
905   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
906   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
907     RRC = &ARM::DPRRegClass;
908     // When NEON is used for SP, only half of the register file is available
909     // because operations that define both SP and DP results will be constrained
910     // to the VFP2 class (D0-D15). We currently model this constraint prior to
911     // coalescing by double-counting the SP regs. See the FIXME above.
912     if (Subtarget->useNEONForSinglePrecisionFP())
913       Cost = 2;
914     break;
915   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
916   case MVT::v4f32: case MVT::v2f64:
917     RRC = &ARM::DPRRegClass;
918     Cost = 2;
919     break;
920   case MVT::v4i64:
921     RRC = &ARM::DPRRegClass;
922     Cost = 4;
923     break;
924   case MVT::v8i64:
925     RRC = &ARM::DPRRegClass;
926     Cost = 8;
927     break;
928   }
929   return std::make_pair(RRC, Cost);
930 }
931
932 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
933   switch (Opcode) {
934   default: return nullptr;
935   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
936   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
937   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
938   case ARMISD::CALL:          return "ARMISD::CALL";
939   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
940   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
941   case ARMISD::tCALL:         return "ARMISD::tCALL";
942   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
943   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
944   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
945   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
946   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
947   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
948   case ARMISD::CMP:           return "ARMISD::CMP";
949   case ARMISD::CMN:           return "ARMISD::CMN";
950   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
951   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
952   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
953   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
954   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
955
956   case ARMISD::CMOV:          return "ARMISD::CMOV";
957
958   case ARMISD::RBIT:          return "ARMISD::RBIT";
959
960   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
961   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
962   case ARMISD::SITOF:         return "ARMISD::SITOF";
963   case ARMISD::UITOF:         return "ARMISD::UITOF";
964
965   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
966   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
967   case ARMISD::RRX:           return "ARMISD::RRX";
968
969   case ARMISD::ADDC:          return "ARMISD::ADDC";
970   case ARMISD::ADDE:          return "ARMISD::ADDE";
971   case ARMISD::SUBC:          return "ARMISD::SUBC";
972   case ARMISD::SUBE:          return "ARMISD::SUBE";
973
974   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
975   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
976
977   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
978   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
979
980   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
981
982   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
983
984   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
985
986   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
987
988   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
989
990   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
991
992   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
993   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
994   case ARMISD::VCGE:          return "ARMISD::VCGE";
995   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
996   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
997   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
998   case ARMISD::VCGT:          return "ARMISD::VCGT";
999   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1000   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1001   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1002   case ARMISD::VTST:          return "ARMISD::VTST";
1003
1004   case ARMISD::VSHL:          return "ARMISD::VSHL";
1005   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1006   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1007   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1008   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1009   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1010   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1011   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1012   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1013   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1014   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1015   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1016   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1017   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1018   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1019   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1020   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1021   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1022   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1023   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1024   case ARMISD::VDUP:          return "ARMISD::VDUP";
1025   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1026   case ARMISD::VEXT:          return "ARMISD::VEXT";
1027   case ARMISD::VREV64:        return "ARMISD::VREV64";
1028   case ARMISD::VREV32:        return "ARMISD::VREV32";
1029   case ARMISD::VREV16:        return "ARMISD::VREV16";
1030   case ARMISD::VZIP:          return "ARMISD::VZIP";
1031   case ARMISD::VUZP:          return "ARMISD::VUZP";
1032   case ARMISD::VTRN:          return "ARMISD::VTRN";
1033   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1034   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1035   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1036   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1037   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1038   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1039   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1040   case ARMISD::FMAX:          return "ARMISD::FMAX";
1041   case ARMISD::FMIN:          return "ARMISD::FMIN";
1042   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1043   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1044   case ARMISD::BFI:           return "ARMISD::BFI";
1045   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1046   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1047   case ARMISD::VBSL:          return "ARMISD::VBSL";
1048   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1049   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1050   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1051   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1052   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1053   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1054   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1055   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1056   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1057   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1058   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1059   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1060   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1061   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1062   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1063   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1064   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1065   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1066   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1067   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1068   }
1069 }
1070
1071 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1072   if (!VT.isVector()) return getPointerTy();
1073   return VT.changeVectorElementTypeToInteger();
1074 }
1075
1076 /// getRegClassFor - Return the register class that should be used for the
1077 /// specified value type.
1078 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1079   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1080   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1081   // load / store 4 to 8 consecutive D registers.
1082   if (Subtarget->hasNEON()) {
1083     if (VT == MVT::v4i64)
1084       return &ARM::QQPRRegClass;
1085     if (VT == MVT::v8i64)
1086       return &ARM::QQQQPRRegClass;
1087   }
1088   return TargetLowering::getRegClassFor(VT);
1089 }
1090
1091 // Create a fast isel object.
1092 FastISel *
1093 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1094                                   const TargetLibraryInfo *libInfo) const {
1095   return ARM::createFastISel(funcInfo, libInfo);
1096 }
1097
1098 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1099 /// be used for loads / stores from the global.
1100 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1101   return (Subtarget->isThumb1Only() ? 127 : 4095);
1102 }
1103
1104 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1105   unsigned NumVals = N->getNumValues();
1106   if (!NumVals)
1107     return Sched::RegPressure;
1108
1109   for (unsigned i = 0; i != NumVals; ++i) {
1110     EVT VT = N->getValueType(i);
1111     if (VT == MVT::Glue || VT == MVT::Other)
1112       continue;
1113     if (VT.isFloatingPoint() || VT.isVector())
1114       return Sched::ILP;
1115   }
1116
1117   if (!N->isMachineOpcode())
1118     return Sched::RegPressure;
1119
1120   // Load are scheduled for latency even if there instruction itinerary
1121   // is not available.
1122   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1123   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1124
1125   if (MCID.getNumDefs() == 0)
1126     return Sched::RegPressure;
1127   if (!Itins->isEmpty() &&
1128       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1129     return Sched::ILP;
1130
1131   return Sched::RegPressure;
1132 }
1133
1134 //===----------------------------------------------------------------------===//
1135 // Lowering Code
1136 //===----------------------------------------------------------------------===//
1137
1138 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1139 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1140   switch (CC) {
1141   default: llvm_unreachable("Unknown condition code!");
1142   case ISD::SETNE:  return ARMCC::NE;
1143   case ISD::SETEQ:  return ARMCC::EQ;
1144   case ISD::SETGT:  return ARMCC::GT;
1145   case ISD::SETGE:  return ARMCC::GE;
1146   case ISD::SETLT:  return ARMCC::LT;
1147   case ISD::SETLE:  return ARMCC::LE;
1148   case ISD::SETUGT: return ARMCC::HI;
1149   case ISD::SETUGE: return ARMCC::HS;
1150   case ISD::SETULT: return ARMCC::LO;
1151   case ISD::SETULE: return ARMCC::LS;
1152   }
1153 }
1154
1155 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1156 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1157                         ARMCC::CondCodes &CondCode2) {
1158   CondCode2 = ARMCC::AL;
1159   switch (CC) {
1160   default: llvm_unreachable("Unknown FP condition!");
1161   case ISD::SETEQ:
1162   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1163   case ISD::SETGT:
1164   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1165   case ISD::SETGE:
1166   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1167   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1168   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1169   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1170   case ISD::SETO:   CondCode = ARMCC::VC; break;
1171   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1172   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1173   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1174   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1175   case ISD::SETLT:
1176   case ISD::SETULT: CondCode = ARMCC::LT; break;
1177   case ISD::SETLE:
1178   case ISD::SETULE: CondCode = ARMCC::LE; break;
1179   case ISD::SETNE:
1180   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1181   }
1182 }
1183
1184 //===----------------------------------------------------------------------===//
1185 //                      Calling Convention Implementation
1186 //===----------------------------------------------------------------------===//
1187
1188 #include "ARMGenCallingConv.inc"
1189
1190 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1191 /// account presence of floating point hardware and calling convention
1192 /// limitations, such as support for variadic functions.
1193 CallingConv::ID
1194 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1195                                            bool isVarArg) const {
1196   switch (CC) {
1197   default:
1198     llvm_unreachable("Unsupported calling convention");
1199   case CallingConv::ARM_AAPCS:
1200   case CallingConv::ARM_APCS:
1201   case CallingConv::GHC:
1202     return CC;
1203   case CallingConv::ARM_AAPCS_VFP:
1204     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1205   case CallingConv::C:
1206     if (!Subtarget->isAAPCS_ABI())
1207       return CallingConv::ARM_APCS;
1208     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1209              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1210              !isVarArg)
1211       return CallingConv::ARM_AAPCS_VFP;
1212     else
1213       return CallingConv::ARM_AAPCS;
1214   case CallingConv::Fast:
1215     if (!Subtarget->isAAPCS_ABI()) {
1216       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1217         return CallingConv::Fast;
1218       return CallingConv::ARM_APCS;
1219     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1220       return CallingConv::ARM_AAPCS_VFP;
1221     else
1222       return CallingConv::ARM_AAPCS;
1223   }
1224 }
1225
1226 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1227 /// CallingConvention.
1228 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1229                                                  bool Return,
1230                                                  bool isVarArg) const {
1231   switch (getEffectiveCallingConv(CC, isVarArg)) {
1232   default:
1233     llvm_unreachable("Unsupported calling convention");
1234   case CallingConv::ARM_APCS:
1235     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1236   case CallingConv::ARM_AAPCS:
1237     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1238   case CallingConv::ARM_AAPCS_VFP:
1239     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1240   case CallingConv::Fast:
1241     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1242   case CallingConv::GHC:
1243     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1244   }
1245 }
1246
1247 /// LowerCallResult - Lower the result values of a call into the
1248 /// appropriate copies out of appropriate physical registers.
1249 SDValue
1250 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1251                                    CallingConv::ID CallConv, bool isVarArg,
1252                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1253                                    SDLoc dl, SelectionDAG &DAG,
1254                                    SmallVectorImpl<SDValue> &InVals,
1255                                    bool isThisReturn, SDValue ThisVal) const {
1256
1257   // Assign locations to each value returned by this call.
1258   SmallVector<CCValAssign, 16> RVLocs;
1259   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1260                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1261   CCInfo.AnalyzeCallResult(Ins,
1262                            CCAssignFnForNode(CallConv, /* Return*/ true,
1263                                              isVarArg));
1264
1265   // Copy all of the result registers out of their specified physreg.
1266   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1267     CCValAssign VA = RVLocs[i];
1268
1269     // Pass 'this' value directly from the argument to return value, to avoid
1270     // reg unit interference
1271     if (i == 0 && isThisReturn) {
1272       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1273              "unexpected return calling convention register assignment");
1274       InVals.push_back(ThisVal);
1275       continue;
1276     }
1277
1278     SDValue Val;
1279     if (VA.needsCustom()) {
1280       // Handle f64 or half of a v2f64.
1281       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1282                                       InFlag);
1283       Chain = Lo.getValue(1);
1284       InFlag = Lo.getValue(2);
1285       VA = RVLocs[++i]; // skip ahead to next loc
1286       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1287                                       InFlag);
1288       Chain = Hi.getValue(1);
1289       InFlag = Hi.getValue(2);
1290       if (!Subtarget->isLittle())
1291         std::swap (Lo, Hi);
1292       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1293
1294       if (VA.getLocVT() == MVT::v2f64) {
1295         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1296         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1297                           DAG.getConstant(0, MVT::i32));
1298
1299         VA = RVLocs[++i]; // skip ahead to next loc
1300         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1301         Chain = Lo.getValue(1);
1302         InFlag = Lo.getValue(2);
1303         VA = RVLocs[++i]; // skip ahead to next loc
1304         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1305         Chain = Hi.getValue(1);
1306         InFlag = Hi.getValue(2);
1307         if (!Subtarget->isLittle())
1308           std::swap (Lo, Hi);
1309         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1310         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1311                           DAG.getConstant(1, MVT::i32));
1312       }
1313     } else {
1314       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1315                                InFlag);
1316       Chain = Val.getValue(1);
1317       InFlag = Val.getValue(2);
1318     }
1319
1320     switch (VA.getLocInfo()) {
1321     default: llvm_unreachable("Unknown loc info!");
1322     case CCValAssign::Full: break;
1323     case CCValAssign::BCvt:
1324       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1325       break;
1326     }
1327
1328     InVals.push_back(Val);
1329   }
1330
1331   return Chain;
1332 }
1333
1334 /// LowerMemOpCallTo - Store the argument to the stack.
1335 SDValue
1336 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1337                                     SDValue StackPtr, SDValue Arg,
1338                                     SDLoc dl, SelectionDAG &DAG,
1339                                     const CCValAssign &VA,
1340                                     ISD::ArgFlagsTy Flags) const {
1341   unsigned LocMemOffset = VA.getLocMemOffset();
1342   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1343   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1344   return DAG.getStore(Chain, dl, Arg, PtrOff,
1345                       MachinePointerInfo::getStack(LocMemOffset),
1346                       false, false, 0);
1347 }
1348
1349 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1350                                          SDValue Chain, SDValue &Arg,
1351                                          RegsToPassVector &RegsToPass,
1352                                          CCValAssign &VA, CCValAssign &NextVA,
1353                                          SDValue &StackPtr,
1354                                          SmallVectorImpl<SDValue> &MemOpChains,
1355                                          ISD::ArgFlagsTy Flags) const {
1356
1357   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1358                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1359   unsigned id = Subtarget->isLittle() ? 0 : 1;
1360   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1361
1362   if (NextVA.isRegLoc())
1363     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1364   else {
1365     assert(NextVA.isMemLoc());
1366     if (!StackPtr.getNode())
1367       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1368
1369     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1370                                            dl, DAG, NextVA,
1371                                            Flags));
1372   }
1373 }
1374
1375 /// LowerCall - Lowering a call into a callseq_start <-
1376 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1377 /// nodes.
1378 SDValue
1379 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1380                              SmallVectorImpl<SDValue> &InVals) const {
1381   SelectionDAG &DAG                     = CLI.DAG;
1382   SDLoc &dl                          = CLI.DL;
1383   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1384   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1385   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1386   SDValue Chain                         = CLI.Chain;
1387   SDValue Callee                        = CLI.Callee;
1388   bool &isTailCall                      = CLI.IsTailCall;
1389   CallingConv::ID CallConv              = CLI.CallConv;
1390   bool doesNotRet                       = CLI.DoesNotReturn;
1391   bool isVarArg                         = CLI.IsVarArg;
1392
1393   MachineFunction &MF = DAG.getMachineFunction();
1394   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1395   bool isThisReturn   = false;
1396   bool isSibCall      = false;
1397
1398   // Disable tail calls if they're not supported.
1399   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1400     isTailCall = false;
1401
1402   if (isTailCall) {
1403     // Check if it's really possible to do a tail call.
1404     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1405                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1406                                                    Outs, OutVals, Ins, DAG);
1407     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1408       report_fatal_error("failed to perform tail call elimination on a call "
1409                          "site marked musttail");
1410     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1411     // detected sibcalls.
1412     if (isTailCall) {
1413       ++NumTailCalls;
1414       isSibCall = true;
1415     }
1416   }
1417
1418   // Analyze operands of the call, assigning locations to each operand.
1419   SmallVector<CCValAssign, 16> ArgLocs;
1420   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1421                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1422   CCInfo.AnalyzeCallOperands(Outs,
1423                              CCAssignFnForNode(CallConv, /* Return*/ false,
1424                                                isVarArg));
1425
1426   // Get a count of how many bytes are to be pushed on the stack.
1427   unsigned NumBytes = CCInfo.getNextStackOffset();
1428
1429   // For tail calls, memory operands are available in our caller's stack.
1430   if (isSibCall)
1431     NumBytes = 0;
1432
1433   // Adjust the stack pointer for the new arguments...
1434   // These operations are automatically eliminated by the prolog/epilog pass
1435   if (!isSibCall)
1436     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1437                                  dl);
1438
1439   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1440
1441   RegsToPassVector RegsToPass;
1442   SmallVector<SDValue, 8> MemOpChains;
1443
1444   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1445   // of tail call optimization, arguments are handled later.
1446   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1447        i != e;
1448        ++i, ++realArgIdx) {
1449     CCValAssign &VA = ArgLocs[i];
1450     SDValue Arg = OutVals[realArgIdx];
1451     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1452     bool isByVal = Flags.isByVal();
1453
1454     // Promote the value if needed.
1455     switch (VA.getLocInfo()) {
1456     default: llvm_unreachable("Unknown loc info!");
1457     case CCValAssign::Full: break;
1458     case CCValAssign::SExt:
1459       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1460       break;
1461     case CCValAssign::ZExt:
1462       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1463       break;
1464     case CCValAssign::AExt:
1465       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1466       break;
1467     case CCValAssign::BCvt:
1468       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1469       break;
1470     }
1471
1472     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1473     if (VA.needsCustom()) {
1474       if (VA.getLocVT() == MVT::v2f64) {
1475         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1476                                   DAG.getConstant(0, MVT::i32));
1477         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1478                                   DAG.getConstant(1, MVT::i32));
1479
1480         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1481                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1482
1483         VA = ArgLocs[++i]; // skip ahead to next loc
1484         if (VA.isRegLoc()) {
1485           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1486                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1487         } else {
1488           assert(VA.isMemLoc());
1489
1490           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1491                                                  dl, DAG, VA, Flags));
1492         }
1493       } else {
1494         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1495                          StackPtr, MemOpChains, Flags);
1496       }
1497     } else if (VA.isRegLoc()) {
1498       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1499         assert(VA.getLocVT() == MVT::i32 &&
1500                "unexpected calling convention register assignment");
1501         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1502                "unexpected use of 'returned'");
1503         isThisReturn = true;
1504       }
1505       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1506     } else if (isByVal) {
1507       assert(VA.isMemLoc());
1508       unsigned offset = 0;
1509
1510       // True if this byval aggregate will be split between registers
1511       // and memory.
1512       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1513       unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1514
1515       if (CurByValIdx < ByValArgsCount) {
1516
1517         unsigned RegBegin, RegEnd;
1518         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1519
1520         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1521         unsigned int i, j;
1522         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1523           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1524           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1525           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1526                                      MachinePointerInfo(),
1527                                      false, false, false,
1528                                      DAG.InferPtrAlignment(AddArg));
1529           MemOpChains.push_back(Load.getValue(1));
1530           RegsToPass.push_back(std::make_pair(j, Load));
1531         }
1532
1533         // If parameter size outsides register area, "offset" value
1534         // helps us to calculate stack slot for remained part properly.
1535         offset = RegEnd - RegBegin;
1536
1537         CCInfo.nextInRegsParam();
1538       }
1539
1540       if (Flags.getByValSize() > 4*offset) {
1541         unsigned LocMemOffset = VA.getLocMemOffset();
1542         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1543         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1544                                   StkPtrOff);
1545         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1546         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1547         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1548                                            MVT::i32);
1549         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1550
1551         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1552         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1553         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1554                                           Ops));
1555       }
1556     } else if (!isSibCall) {
1557       assert(VA.isMemLoc());
1558
1559       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1560                                              dl, DAG, VA, Flags));
1561     }
1562   }
1563
1564   if (!MemOpChains.empty())
1565     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1566
1567   // Build a sequence of copy-to-reg nodes chained together with token chain
1568   // and flag operands which copy the outgoing args into the appropriate regs.
1569   SDValue InFlag;
1570   // Tail call byval lowering might overwrite argument registers so in case of
1571   // tail call optimization the copies to registers are lowered later.
1572   if (!isTailCall)
1573     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1574       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1575                                RegsToPass[i].second, InFlag);
1576       InFlag = Chain.getValue(1);
1577     }
1578
1579   // For tail calls lower the arguments to the 'real' stack slot.
1580   if (isTailCall) {
1581     // Force all the incoming stack arguments to be loaded from the stack
1582     // before any new outgoing arguments are stored to the stack, because the
1583     // outgoing stack slots may alias the incoming argument stack slots, and
1584     // the alias isn't otherwise explicit. This is slightly more conservative
1585     // than necessary, because it means that each store effectively depends
1586     // on every argument instead of just those arguments it would clobber.
1587
1588     // Do not flag preceding copytoreg stuff together with the following stuff.
1589     InFlag = SDValue();
1590     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1591       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1592                                RegsToPass[i].second, InFlag);
1593       InFlag = Chain.getValue(1);
1594     }
1595     InFlag = SDValue();
1596   }
1597
1598   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1599   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1600   // node so that legalize doesn't hack it.
1601   bool isDirect = false;
1602   bool isARMFunc = false;
1603   bool isLocalARMFunc = false;
1604   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1605
1606   if (EnableARMLongCalls) {
1607     assert((Subtarget->isTargetWindows() ||
1608             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1609            "long-calls with non-static relocation model!");
1610     // Handle a global address or an external symbol. If it's not one of
1611     // those, the target's already in a register, so we don't need to do
1612     // anything extra.
1613     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1614       const GlobalValue *GV = G->getGlobal();
1615       // Create a constant pool entry for the callee address
1616       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1617       ARMConstantPoolValue *CPV =
1618         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1619
1620       // Get the address of the callee into a register
1621       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1622       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1623       Callee = DAG.getLoad(getPointerTy(), dl,
1624                            DAG.getEntryNode(), CPAddr,
1625                            MachinePointerInfo::getConstantPool(),
1626                            false, false, false, 0);
1627     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1628       const char *Sym = S->getSymbol();
1629
1630       // Create a constant pool entry for the callee address
1631       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1632       ARMConstantPoolValue *CPV =
1633         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1634                                       ARMPCLabelIndex, 0);
1635       // Get the address of the callee into a register
1636       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1637       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1638       Callee = DAG.getLoad(getPointerTy(), dl,
1639                            DAG.getEntryNode(), CPAddr,
1640                            MachinePointerInfo::getConstantPool(),
1641                            false, false, false, 0);
1642     }
1643   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1644     const GlobalValue *GV = G->getGlobal();
1645     isDirect = true;
1646     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1647     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1648                    getTargetMachine().getRelocationModel() != Reloc::Static;
1649     isARMFunc = !Subtarget->isThumb() || isStub;
1650     // ARM call to a local ARM function is predicable.
1651     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1652     // tBX takes a register source operand.
1653     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1654       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1655       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1656                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy()));
1657     } else {
1658       // On ELF targets for PIC code, direct calls should go through the PLT
1659       unsigned OpFlags = 0;
1660       if (Subtarget->isTargetELF() &&
1661           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1662         OpFlags = ARMII::MO_PLT;
1663       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1664     }
1665   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1666     isDirect = true;
1667     bool isStub = Subtarget->isTargetMachO() &&
1668                   getTargetMachine().getRelocationModel() != Reloc::Static;
1669     isARMFunc = !Subtarget->isThumb() || isStub;
1670     // tBX takes a register source operand.
1671     const char *Sym = S->getSymbol();
1672     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1673       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1674       ARMConstantPoolValue *CPV =
1675         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1676                                       ARMPCLabelIndex, 4);
1677       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1678       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1679       Callee = DAG.getLoad(getPointerTy(), dl,
1680                            DAG.getEntryNode(), CPAddr,
1681                            MachinePointerInfo::getConstantPool(),
1682                            false, false, false, 0);
1683       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1684       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1685                            getPointerTy(), Callee, PICLabel);
1686     } else {
1687       unsigned OpFlags = 0;
1688       // On ELF targets for PIC code, direct calls should go through the PLT
1689       if (Subtarget->isTargetELF() &&
1690                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1691         OpFlags = ARMII::MO_PLT;
1692       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1693     }
1694   }
1695
1696   // FIXME: handle tail calls differently.
1697   unsigned CallOpc;
1698   bool HasMinSizeAttr = MF.getFunction()->getAttributes().hasAttribute(
1699       AttributeSet::FunctionIndex, Attribute::MinSize);
1700   if (Subtarget->isThumb()) {
1701     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1702       CallOpc = ARMISD::CALL_NOLINK;
1703     else
1704       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1705   } else {
1706     if (!isDirect && !Subtarget->hasV5TOps())
1707       CallOpc = ARMISD::CALL_NOLINK;
1708     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1709                // Emit regular call when code size is the priority
1710                !HasMinSizeAttr)
1711       // "mov lr, pc; b _foo" to avoid confusing the RSP
1712       CallOpc = ARMISD::CALL_NOLINK;
1713     else
1714       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1715   }
1716
1717   std::vector<SDValue> Ops;
1718   Ops.push_back(Chain);
1719   Ops.push_back(Callee);
1720
1721   // Add argument registers to the end of the list so that they are known live
1722   // into the call.
1723   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1724     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1725                                   RegsToPass[i].second.getValueType()));
1726
1727   // Add a register mask operand representing the call-preserved registers.
1728   if (!isTailCall) {
1729     const uint32_t *Mask;
1730     const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1731     const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1732     if (isThisReturn) {
1733       // For 'this' returns, use the R0-preserving mask if applicable
1734       Mask = ARI->getThisReturnPreservedMask(CallConv);
1735       if (!Mask) {
1736         // Set isThisReturn to false if the calling convention is not one that
1737         // allows 'returned' to be modeled in this way, so LowerCallResult does
1738         // not try to pass 'this' straight through
1739         isThisReturn = false;
1740         Mask = ARI->getCallPreservedMask(CallConv);
1741       }
1742     } else
1743       Mask = ARI->getCallPreservedMask(CallConv);
1744
1745     assert(Mask && "Missing call preserved mask for calling convention");
1746     Ops.push_back(DAG.getRegisterMask(Mask));
1747   }
1748
1749   if (InFlag.getNode())
1750     Ops.push_back(InFlag);
1751
1752   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1753   if (isTailCall)
1754     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1755
1756   // Returns a chain and a flag for retval copy to use.
1757   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1758   InFlag = Chain.getValue(1);
1759
1760   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1761                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1762   if (!Ins.empty())
1763     InFlag = Chain.getValue(1);
1764
1765   // Handle result values, copying them out of physregs into vregs that we
1766   // return.
1767   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1768                          InVals, isThisReturn,
1769                          isThisReturn ? OutVals[0] : SDValue());
1770 }
1771
1772 /// HandleByVal - Every parameter *after* a byval parameter is passed
1773 /// on the stack.  Remember the next parameter register to allocate,
1774 /// and then confiscate the rest of the parameter registers to insure
1775 /// this.
1776 void
1777 ARMTargetLowering::HandleByVal(
1778     CCState *State, unsigned &size, unsigned Align) const {
1779   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1780   assert((State->getCallOrPrologue() == Prologue ||
1781           State->getCallOrPrologue() == Call) &&
1782          "unhandled ParmContext");
1783
1784   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1785     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1786       unsigned AlignInRegs = Align / 4;
1787       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1788       for (unsigned i = 0; i < Waste; ++i)
1789         reg = State->AllocateReg(GPRArgRegs, 4);
1790     }
1791     if (reg != 0) {
1792       unsigned excess = 4 * (ARM::R4 - reg);
1793
1794       // Special case when NSAA != SP and parameter size greater than size of
1795       // all remained GPR regs. In that case we can't split parameter, we must
1796       // send it to stack. We also must set NCRN to R4, so waste all
1797       // remained registers.
1798       const unsigned NSAAOffset = State->getNextStackOffset();
1799       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1800         while (State->AllocateReg(GPRArgRegs, 4))
1801           ;
1802         return;
1803       }
1804
1805       // First register for byval parameter is the first register that wasn't
1806       // allocated before this method call, so it would be "reg".
1807       // If parameter is small enough to be saved in range [reg, r4), then
1808       // the end (first after last) register would be reg + param-size-in-regs,
1809       // else parameter would be splitted between registers and stack,
1810       // end register would be r4 in this case.
1811       unsigned ByValRegBegin = reg;
1812       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1813       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1814       // Note, first register is allocated in the beginning of function already,
1815       // allocate remained amount of registers we need.
1816       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1817         State->AllocateReg(GPRArgRegs, 4);
1818       // A byval parameter that is split between registers and memory needs its
1819       // size truncated here.
1820       // In the case where the entire structure fits in registers, we set the
1821       // size in memory to zero.
1822       if (size < excess)
1823         size = 0;
1824       else
1825         size -= excess;
1826     }
1827   }
1828 }
1829
1830 /// MatchingStackOffset - Return true if the given stack call argument is
1831 /// already available in the same position (relatively) of the caller's
1832 /// incoming argument stack.
1833 static
1834 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1835                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1836                          const TargetInstrInfo *TII) {
1837   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1838   int FI = INT_MAX;
1839   if (Arg.getOpcode() == ISD::CopyFromReg) {
1840     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1841     if (!TargetRegisterInfo::isVirtualRegister(VR))
1842       return false;
1843     MachineInstr *Def = MRI->getVRegDef(VR);
1844     if (!Def)
1845       return false;
1846     if (!Flags.isByVal()) {
1847       if (!TII->isLoadFromStackSlot(Def, FI))
1848         return false;
1849     } else {
1850       return false;
1851     }
1852   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1853     if (Flags.isByVal())
1854       // ByVal argument is passed in as a pointer but it's now being
1855       // dereferenced. e.g.
1856       // define @foo(%struct.X* %A) {
1857       //   tail call @bar(%struct.X* byval %A)
1858       // }
1859       return false;
1860     SDValue Ptr = Ld->getBasePtr();
1861     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1862     if (!FINode)
1863       return false;
1864     FI = FINode->getIndex();
1865   } else
1866     return false;
1867
1868   assert(FI != INT_MAX);
1869   if (!MFI->isFixedObjectIndex(FI))
1870     return false;
1871   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1872 }
1873
1874 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1875 /// for tail call optimization. Targets which want to do tail call
1876 /// optimization should implement this function.
1877 bool
1878 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1879                                                      CallingConv::ID CalleeCC,
1880                                                      bool isVarArg,
1881                                                      bool isCalleeStructRet,
1882                                                      bool isCallerStructRet,
1883                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1884                                     const SmallVectorImpl<SDValue> &OutVals,
1885                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1886                                                      SelectionDAG& DAG) const {
1887   const Function *CallerF = DAG.getMachineFunction().getFunction();
1888   CallingConv::ID CallerCC = CallerF->getCallingConv();
1889   bool CCMatch = CallerCC == CalleeCC;
1890
1891   // Look for obvious safe cases to perform tail call optimization that do not
1892   // require ABI changes. This is what gcc calls sibcall.
1893
1894   // Do not sibcall optimize vararg calls unless the call site is not passing
1895   // any arguments.
1896   if (isVarArg && !Outs.empty())
1897     return false;
1898
1899   // Exception-handling functions need a special set of instructions to indicate
1900   // a return to the hardware. Tail-calling another function would probably
1901   // break this.
1902   if (CallerF->hasFnAttribute("interrupt"))
1903     return false;
1904
1905   // Also avoid sibcall optimization if either caller or callee uses struct
1906   // return semantics.
1907   if (isCalleeStructRet || isCallerStructRet)
1908     return false;
1909
1910   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1911   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1912   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1913   // support in the assembler and linker to be used. This would need to be
1914   // fixed to fully support tail calls in Thumb1.
1915   //
1916   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1917   // LR.  This means if we need to reload LR, it takes an extra instructions,
1918   // which outweighs the value of the tail call; but here we don't know yet
1919   // whether LR is going to be used.  Probably the right approach is to
1920   // generate the tail call here and turn it back into CALL/RET in
1921   // emitEpilogue if LR is used.
1922
1923   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1924   // but we need to make sure there are enough registers; the only valid
1925   // registers are the 4 used for parameters.  We don't currently do this
1926   // case.
1927   if (Subtarget->isThumb1Only())
1928     return false;
1929
1930   // If the calling conventions do not match, then we'd better make sure the
1931   // results are returned in the same way as what the caller expects.
1932   if (!CCMatch) {
1933     SmallVector<CCValAssign, 16> RVLocs1;
1934     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1935                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1936     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1937
1938     SmallVector<CCValAssign, 16> RVLocs2;
1939     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1940                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1941     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1942
1943     if (RVLocs1.size() != RVLocs2.size())
1944       return false;
1945     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1946       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1947         return false;
1948       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1949         return false;
1950       if (RVLocs1[i].isRegLoc()) {
1951         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1952           return false;
1953       } else {
1954         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1955           return false;
1956       }
1957     }
1958   }
1959
1960   // If Caller's vararg or byval argument has been split between registers and
1961   // stack, do not perform tail call, since part of the argument is in caller's
1962   // local frame.
1963   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1964                                       getInfo<ARMFunctionInfo>();
1965   if (AFI_Caller->getArgRegsSaveSize())
1966     return false;
1967
1968   // If the callee takes no arguments then go on to check the results of the
1969   // call.
1970   if (!Outs.empty()) {
1971     // Check if stack adjustment is needed. For now, do not do this if any
1972     // argument is passed on the stack.
1973     SmallVector<CCValAssign, 16> ArgLocs;
1974     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1975                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1976     CCInfo.AnalyzeCallOperands(Outs,
1977                                CCAssignFnForNode(CalleeCC, false, isVarArg));
1978     if (CCInfo.getNextStackOffset()) {
1979       MachineFunction &MF = DAG.getMachineFunction();
1980
1981       // Check if the arguments are already laid out in the right way as
1982       // the caller's fixed stack objects.
1983       MachineFrameInfo *MFI = MF.getFrameInfo();
1984       const MachineRegisterInfo *MRI = &MF.getRegInfo();
1985       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1986       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1987            i != e;
1988            ++i, ++realArgIdx) {
1989         CCValAssign &VA = ArgLocs[i];
1990         EVT RegVT = VA.getLocVT();
1991         SDValue Arg = OutVals[realArgIdx];
1992         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1993         if (VA.getLocInfo() == CCValAssign::Indirect)
1994           return false;
1995         if (VA.needsCustom()) {
1996           // f64 and vector types are split into multiple registers or
1997           // register/stack-slot combinations.  The types will not match
1998           // the registers; give up on memory f64 refs until we figure
1999           // out what to do about this.
2000           if (!VA.isRegLoc())
2001             return false;
2002           if (!ArgLocs[++i].isRegLoc())
2003             return false;
2004           if (RegVT == MVT::v2f64) {
2005             if (!ArgLocs[++i].isRegLoc())
2006               return false;
2007             if (!ArgLocs[++i].isRegLoc())
2008               return false;
2009           }
2010         } else if (!VA.isRegLoc()) {
2011           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2012                                    MFI, MRI, TII))
2013             return false;
2014         }
2015       }
2016     }
2017   }
2018
2019   return true;
2020 }
2021
2022 bool
2023 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2024                                   MachineFunction &MF, bool isVarArg,
2025                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2026                                   LLVMContext &Context) const {
2027   SmallVector<CCValAssign, 16> RVLocs;
2028   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2029   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2030                                                     isVarArg));
2031 }
2032
2033 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2034                                     SDLoc DL, SelectionDAG &DAG) {
2035   const MachineFunction &MF = DAG.getMachineFunction();
2036   const Function *F = MF.getFunction();
2037
2038   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2039
2040   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2041   // version of the "preferred return address". These offsets affect the return
2042   // instruction if this is a return from PL1 without hypervisor extensions.
2043   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2044   //    SWI:     0      "subs pc, lr, #0"
2045   //    ABORT:   +4     "subs pc, lr, #4"
2046   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2047   // UNDEF varies depending on where the exception came from ARM or Thumb
2048   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2049
2050   int64_t LROffset;
2051   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2052       IntKind == "ABORT")
2053     LROffset = 4;
2054   else if (IntKind == "SWI" || IntKind == "UNDEF")
2055     LROffset = 0;
2056   else
2057     report_fatal_error("Unsupported interrupt attribute. If present, value "
2058                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2059
2060   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2061
2062   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2063 }
2064
2065 SDValue
2066 ARMTargetLowering::LowerReturn(SDValue Chain,
2067                                CallingConv::ID CallConv, bool isVarArg,
2068                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2069                                const SmallVectorImpl<SDValue> &OutVals,
2070                                SDLoc dl, SelectionDAG &DAG) const {
2071
2072   // CCValAssign - represent the assignment of the return value to a location.
2073   SmallVector<CCValAssign, 16> RVLocs;
2074
2075   // CCState - Info about the registers and stack slots.
2076   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2077                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2078
2079   // Analyze outgoing return values.
2080   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2081                                                isVarArg));
2082
2083   SDValue Flag;
2084   SmallVector<SDValue, 4> RetOps;
2085   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2086   bool isLittleEndian = Subtarget->isLittle();
2087
2088   // Copy the result values into the output registers.
2089   for (unsigned i = 0, realRVLocIdx = 0;
2090        i != RVLocs.size();
2091        ++i, ++realRVLocIdx) {
2092     CCValAssign &VA = RVLocs[i];
2093     assert(VA.isRegLoc() && "Can only return in registers!");
2094
2095     SDValue Arg = OutVals[realRVLocIdx];
2096
2097     switch (VA.getLocInfo()) {
2098     default: llvm_unreachable("Unknown loc info!");
2099     case CCValAssign::Full: break;
2100     case CCValAssign::BCvt:
2101       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2102       break;
2103     }
2104
2105     if (VA.needsCustom()) {
2106       if (VA.getLocVT() == MVT::v2f64) {
2107         // Extract the first half and return it in two registers.
2108         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2109                                    DAG.getConstant(0, MVT::i32));
2110         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2111                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2112
2113         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2114                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2115                                  Flag);
2116         Flag = Chain.getValue(1);
2117         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2118         VA = RVLocs[++i]; // skip ahead to next loc
2119         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2120                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2121                                  Flag);
2122         Flag = Chain.getValue(1);
2123         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2124         VA = RVLocs[++i]; // skip ahead to next loc
2125
2126         // Extract the 2nd half and fall through to handle it as an f64 value.
2127         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2128                           DAG.getConstant(1, MVT::i32));
2129       }
2130       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2131       // available.
2132       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2133                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2134       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2135                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2136                                Flag);
2137       Flag = Chain.getValue(1);
2138       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2139       VA = RVLocs[++i]; // skip ahead to next loc
2140       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2141                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2142                                Flag);
2143     } else
2144       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2145
2146     // Guarantee that all emitted copies are
2147     // stuck together, avoiding something bad.
2148     Flag = Chain.getValue(1);
2149     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2150   }
2151
2152   // Update chain and glue.
2153   RetOps[0] = Chain;
2154   if (Flag.getNode())
2155     RetOps.push_back(Flag);
2156
2157   // CPUs which aren't M-class use a special sequence to return from
2158   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2159   // though we use "subs pc, lr, #N").
2160   //
2161   // M-class CPUs actually use a normal return sequence with a special
2162   // (hardware-provided) value in LR, so the normal code path works.
2163   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2164       !Subtarget->isMClass()) {
2165     if (Subtarget->isThumb1Only())
2166       report_fatal_error("interrupt attribute is not supported in Thumb1");
2167     return LowerInterruptReturn(RetOps, dl, DAG);
2168   }
2169
2170   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2171 }
2172
2173 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2174   if (N->getNumValues() != 1)
2175     return false;
2176   if (!N->hasNUsesOfValue(1, 0))
2177     return false;
2178
2179   SDValue TCChain = Chain;
2180   SDNode *Copy = *N->use_begin();
2181   if (Copy->getOpcode() == ISD::CopyToReg) {
2182     // If the copy has a glue operand, we conservatively assume it isn't safe to
2183     // perform a tail call.
2184     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2185       return false;
2186     TCChain = Copy->getOperand(0);
2187   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2188     SDNode *VMov = Copy;
2189     // f64 returned in a pair of GPRs.
2190     SmallPtrSet<SDNode*, 2> Copies;
2191     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2192          UI != UE; ++UI) {
2193       if (UI->getOpcode() != ISD::CopyToReg)
2194         return false;
2195       Copies.insert(*UI);
2196     }
2197     if (Copies.size() > 2)
2198       return false;
2199
2200     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2201          UI != UE; ++UI) {
2202       SDValue UseChain = UI->getOperand(0);
2203       if (Copies.count(UseChain.getNode()))
2204         // Second CopyToReg
2205         Copy = *UI;
2206       else
2207         // First CopyToReg
2208         TCChain = UseChain;
2209     }
2210   } else if (Copy->getOpcode() == ISD::BITCAST) {
2211     // f32 returned in a single GPR.
2212     if (!Copy->hasOneUse())
2213       return false;
2214     Copy = *Copy->use_begin();
2215     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2216       return false;
2217     TCChain = Copy->getOperand(0);
2218   } else {
2219     return false;
2220   }
2221
2222   bool HasRet = false;
2223   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2224        UI != UE; ++UI) {
2225     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2226         UI->getOpcode() != ARMISD::INTRET_FLAG)
2227       return false;
2228     HasRet = true;
2229   }
2230
2231   if (!HasRet)
2232     return false;
2233
2234   Chain = TCChain;
2235   return true;
2236 }
2237
2238 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2239   if (!Subtarget->supportsTailCall())
2240     return false;
2241
2242   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2243     return false;
2244
2245   return !Subtarget->isThumb1Only();
2246 }
2247
2248 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2249 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2250 // one of the above mentioned nodes. It has to be wrapped because otherwise
2251 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2252 // be used to form addressing mode. These wrapped nodes will be selected
2253 // into MOVi.
2254 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2255   EVT PtrVT = Op.getValueType();
2256   // FIXME there is no actual debug info here
2257   SDLoc dl(Op);
2258   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2259   SDValue Res;
2260   if (CP->isMachineConstantPoolEntry())
2261     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2262                                     CP->getAlignment());
2263   else
2264     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2265                                     CP->getAlignment());
2266   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2267 }
2268
2269 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2270   return MachineJumpTableInfo::EK_Inline;
2271 }
2272
2273 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2274                                              SelectionDAG &DAG) const {
2275   MachineFunction &MF = DAG.getMachineFunction();
2276   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2277   unsigned ARMPCLabelIndex = 0;
2278   SDLoc DL(Op);
2279   EVT PtrVT = getPointerTy();
2280   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2281   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2282   SDValue CPAddr;
2283   if (RelocM == Reloc::Static) {
2284     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2285   } else {
2286     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2287     ARMPCLabelIndex = AFI->createPICLabelUId();
2288     ARMConstantPoolValue *CPV =
2289       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2290                                       ARMCP::CPBlockAddress, PCAdj);
2291     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2292   }
2293   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2294   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2295                                MachinePointerInfo::getConstantPool(),
2296                                false, false, false, 0);
2297   if (RelocM == Reloc::Static)
2298     return Result;
2299   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2300   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2301 }
2302
2303 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2304 SDValue
2305 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2306                                                  SelectionDAG &DAG) const {
2307   SDLoc dl(GA);
2308   EVT PtrVT = getPointerTy();
2309   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2310   MachineFunction &MF = DAG.getMachineFunction();
2311   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2312   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2313   ARMConstantPoolValue *CPV =
2314     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2315                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2316   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2317   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2318   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2319                          MachinePointerInfo::getConstantPool(),
2320                          false, false, false, 0);
2321   SDValue Chain = Argument.getValue(1);
2322
2323   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2324   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2325
2326   // call __tls_get_addr.
2327   ArgListTy Args;
2328   ArgListEntry Entry;
2329   Entry.Node = Argument;
2330   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2331   Args.push_back(Entry);
2332
2333   // FIXME: is there useful debug info available here?
2334   TargetLowering::CallLoweringInfo CLI(DAG);
2335   CLI.setDebugLoc(dl).setChain(Chain)
2336     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2337                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2338                0);
2339
2340   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2341   return CallResult.first;
2342 }
2343
2344 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2345 // "local exec" model.
2346 SDValue
2347 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2348                                         SelectionDAG &DAG,
2349                                         TLSModel::Model model) const {
2350   const GlobalValue *GV = GA->getGlobal();
2351   SDLoc dl(GA);
2352   SDValue Offset;
2353   SDValue Chain = DAG.getEntryNode();
2354   EVT PtrVT = getPointerTy();
2355   // Get the Thread Pointer
2356   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2357
2358   if (model == TLSModel::InitialExec) {
2359     MachineFunction &MF = DAG.getMachineFunction();
2360     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2361     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2362     // Initial exec model.
2363     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2364     ARMConstantPoolValue *CPV =
2365       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2366                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2367                                       true);
2368     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2369     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2370     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2371                          MachinePointerInfo::getConstantPool(),
2372                          false, false, false, 0);
2373     Chain = Offset.getValue(1);
2374
2375     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2376     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2377
2378     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2379                          MachinePointerInfo::getConstantPool(),
2380                          false, false, false, 0);
2381   } else {
2382     // local exec model
2383     assert(model == TLSModel::LocalExec);
2384     ARMConstantPoolValue *CPV =
2385       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2386     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2387     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2388     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2389                          MachinePointerInfo::getConstantPool(),
2390                          false, false, false, 0);
2391   }
2392
2393   // The address of the thread local variable is the add of the thread
2394   // pointer with the offset of the variable.
2395   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2396 }
2397
2398 SDValue
2399 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2400   // TODO: implement the "local dynamic" model
2401   assert(Subtarget->isTargetELF() &&
2402          "TLS not implemented for non-ELF targets");
2403   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2404
2405   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2406
2407   switch (model) {
2408     case TLSModel::GeneralDynamic:
2409     case TLSModel::LocalDynamic:
2410       return LowerToTLSGeneralDynamicModel(GA, DAG);
2411     case TLSModel::InitialExec:
2412     case TLSModel::LocalExec:
2413       return LowerToTLSExecModels(GA, DAG, model);
2414   }
2415   llvm_unreachable("bogus TLS model");
2416 }
2417
2418 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2419                                                  SelectionDAG &DAG) const {
2420   EVT PtrVT = getPointerTy();
2421   SDLoc dl(Op);
2422   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2423   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2424     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2425     ARMConstantPoolValue *CPV =
2426       ARMConstantPoolConstant::Create(GV,
2427                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2428     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2429     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2430     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2431                                  CPAddr,
2432                                  MachinePointerInfo::getConstantPool(),
2433                                  false, false, false, 0);
2434     SDValue Chain = Result.getValue(1);
2435     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2436     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2437     if (!UseGOTOFF)
2438       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2439                            MachinePointerInfo::getGOT(),
2440                            false, false, false, 0);
2441     return Result;
2442   }
2443
2444   // If we have T2 ops, we can materialize the address directly via movt/movw
2445   // pair. This is always cheaper.
2446   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2447     ++NumMovwMovt;
2448     // FIXME: Once remat is capable of dealing with instructions with register
2449     // operands, expand this into two nodes.
2450     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2451                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2452   } else {
2453     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2454     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2455     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2456                        MachinePointerInfo::getConstantPool(),
2457                        false, false, false, 0);
2458   }
2459 }
2460
2461 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2462                                                     SelectionDAG &DAG) const {
2463   EVT PtrVT = getPointerTy();
2464   SDLoc dl(Op);
2465   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2466   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2467
2468   if (Subtarget->useMovt(DAG.getMachineFunction()))
2469     ++NumMovwMovt;
2470
2471   // FIXME: Once remat is capable of dealing with instructions with register
2472   // operands, expand this into multiple nodes
2473   unsigned Wrapper =
2474       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2475
2476   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2477   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2478
2479   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2480     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2481                          MachinePointerInfo::getGOT(), false, false, false, 0);
2482   return Result;
2483 }
2484
2485 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2486                                                      SelectionDAG &DAG) const {
2487   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2488   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2489          "Windows on ARM expects to use movw/movt");
2490
2491   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2492   EVT PtrVT = getPointerTy();
2493   SDLoc DL(Op);
2494
2495   ++NumMovwMovt;
2496
2497   // FIXME: Once remat is capable of dealing with instructions with register
2498   // operands, expand this into two nodes.
2499   return DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2500                      DAG.getTargetGlobalAddress(GV, DL, PtrVT));
2501 }
2502
2503 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2504                                                     SelectionDAG &DAG) const {
2505   assert(Subtarget->isTargetELF() &&
2506          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2507   MachineFunction &MF = DAG.getMachineFunction();
2508   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2509   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2510   EVT PtrVT = getPointerTy();
2511   SDLoc dl(Op);
2512   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2513   ARMConstantPoolValue *CPV =
2514     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2515                                   ARMPCLabelIndex, PCAdj);
2516   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2517   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2518   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2519                                MachinePointerInfo::getConstantPool(),
2520                                false, false, false, 0);
2521   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2522   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2523 }
2524
2525 SDValue
2526 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2527   SDLoc dl(Op);
2528   SDValue Val = DAG.getConstant(0, MVT::i32);
2529   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2530                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2531                      Op.getOperand(1), Val);
2532 }
2533
2534 SDValue
2535 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2536   SDLoc dl(Op);
2537   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2538                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2539 }
2540
2541 SDValue
2542 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2543                                           const ARMSubtarget *Subtarget) const {
2544   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2545   SDLoc dl(Op);
2546   switch (IntNo) {
2547   default: return SDValue();    // Don't custom lower most intrinsics.
2548   case Intrinsic::arm_rbit: {
2549     assert(Op.getOperand(0).getValueType() == MVT::i32 &&
2550            "RBIT intrinsic must have i32 type!");
2551     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(0));
2552   }
2553   case Intrinsic::arm_thread_pointer: {
2554     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2555     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2556   }
2557   case Intrinsic::eh_sjlj_lsda: {
2558     MachineFunction &MF = DAG.getMachineFunction();
2559     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2560     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2561     EVT PtrVT = getPointerTy();
2562     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2563     SDValue CPAddr;
2564     unsigned PCAdj = (RelocM != Reloc::PIC_)
2565       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2566     ARMConstantPoolValue *CPV =
2567       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2568                                       ARMCP::CPLSDA, PCAdj);
2569     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2570     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2571     SDValue Result =
2572       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2573                   MachinePointerInfo::getConstantPool(),
2574                   false, false, false, 0);
2575
2576     if (RelocM == Reloc::PIC_) {
2577       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2578       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2579     }
2580     return Result;
2581   }
2582   case Intrinsic::arm_neon_vmulls:
2583   case Intrinsic::arm_neon_vmullu: {
2584     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2585       ? ARMISD::VMULLs : ARMISD::VMULLu;
2586     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2587                        Op.getOperand(1), Op.getOperand(2));
2588   }
2589   }
2590 }
2591
2592 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2593                                  const ARMSubtarget *Subtarget) {
2594   // FIXME: handle "fence singlethread" more efficiently.
2595   SDLoc dl(Op);
2596   if (!Subtarget->hasDataBarrier()) {
2597     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2598     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2599     // here.
2600     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2601            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2602     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2603                        DAG.getConstant(0, MVT::i32));
2604   }
2605
2606   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2607   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2608   unsigned Domain = ARM_MB::ISH;
2609   if (Subtarget->isMClass()) {
2610     // Only a full system barrier exists in the M-class architectures.
2611     Domain = ARM_MB::SY;
2612   } else if (Subtarget->isSwift() && Ord == Release) {
2613     // Swift happens to implement ISHST barriers in a way that's compatible with
2614     // Release semantics but weaker than ISH so we'd be fools not to use
2615     // it. Beware: other processors probably don't!
2616     Domain = ARM_MB::ISHST;
2617   }
2618
2619   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2620                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2621                      DAG.getConstant(Domain, MVT::i32));
2622 }
2623
2624 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2625                              const ARMSubtarget *Subtarget) {
2626   // ARM pre v5TE and Thumb1 does not have preload instructions.
2627   if (!(Subtarget->isThumb2() ||
2628         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2629     // Just preserve the chain.
2630     return Op.getOperand(0);
2631
2632   SDLoc dl(Op);
2633   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2634   if (!isRead &&
2635       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2636     // ARMv7 with MP extension has PLDW.
2637     return Op.getOperand(0);
2638
2639   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2640   if (Subtarget->isThumb()) {
2641     // Invert the bits.
2642     isRead = ~isRead & 1;
2643     isData = ~isData & 1;
2644   }
2645
2646   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2647                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2648                      DAG.getConstant(isData, MVT::i32));
2649 }
2650
2651 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2652   MachineFunction &MF = DAG.getMachineFunction();
2653   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2654
2655   // vastart just stores the address of the VarArgsFrameIndex slot into the
2656   // memory location argument.
2657   SDLoc dl(Op);
2658   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2659   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2660   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2661   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2662                       MachinePointerInfo(SV), false, false, 0);
2663 }
2664
2665 SDValue
2666 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2667                                         SDValue &Root, SelectionDAG &DAG,
2668                                         SDLoc dl) const {
2669   MachineFunction &MF = DAG.getMachineFunction();
2670   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2671
2672   const TargetRegisterClass *RC;
2673   if (AFI->isThumb1OnlyFunction())
2674     RC = &ARM::tGPRRegClass;
2675   else
2676     RC = &ARM::GPRRegClass;
2677
2678   // Transform the arguments stored in physical registers into virtual ones.
2679   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2680   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2681
2682   SDValue ArgValue2;
2683   if (NextVA.isMemLoc()) {
2684     MachineFrameInfo *MFI = MF.getFrameInfo();
2685     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2686
2687     // Create load node to retrieve arguments from the stack.
2688     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2689     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2690                             MachinePointerInfo::getFixedStack(FI),
2691                             false, false, false, 0);
2692   } else {
2693     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2694     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2695   }
2696   if (!Subtarget->isLittle())
2697     std::swap (ArgValue, ArgValue2);
2698   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2699 }
2700
2701 void
2702 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2703                                   unsigned InRegsParamRecordIdx,
2704                                   unsigned ArgSize,
2705                                   unsigned &ArgRegsSize,
2706                                   unsigned &ArgRegsSaveSize)
2707   const {
2708   unsigned NumGPRs;
2709   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2710     unsigned RBegin, REnd;
2711     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2712     NumGPRs = REnd - RBegin;
2713   } else {
2714     unsigned int firstUnalloced;
2715     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2716                                                 sizeof(GPRArgRegs) /
2717                                                 sizeof(GPRArgRegs[0]));
2718     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2719   }
2720
2721   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2722   ArgRegsSize = NumGPRs * 4;
2723
2724   // If parameter is split between stack and GPRs...
2725   if (NumGPRs && Align > 4 &&
2726       (ArgRegsSize < ArgSize ||
2727         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2728     // Add padding for part of param recovered from GPRs.  For example,
2729     // if Align == 8, its last byte must be at address K*8 - 1.
2730     // We need to do it, since remained (stack) part of parameter has
2731     // stack alignment, and we need to "attach" "GPRs head" without gaps
2732     // to it:
2733     // Stack:
2734     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2735     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2736     //
2737     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2738     unsigned Padding =
2739         OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2740     ArgRegsSaveSize = ArgRegsSize + Padding;
2741   } else
2742     // We don't need to extend regs save size for byval parameters if they
2743     // are passed via GPRs only.
2744     ArgRegsSaveSize = ArgRegsSize;
2745 }
2746
2747 // The remaining GPRs hold either the beginning of variable-argument
2748 // data, or the beginning of an aggregate passed by value (usually
2749 // byval).  Either way, we allocate stack slots adjacent to the data
2750 // provided by our caller, and store the unallocated registers there.
2751 // If this is a variadic function, the va_list pointer will begin with
2752 // these values; otherwise, this reassembles a (byval) structure that
2753 // was split between registers and memory.
2754 // Return: The frame index registers were stored into.
2755 int
2756 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2757                                   SDLoc dl, SDValue &Chain,
2758                                   const Value *OrigArg,
2759                                   unsigned InRegsParamRecordIdx,
2760                                   unsigned OffsetFromOrigArg,
2761                                   unsigned ArgOffset,
2762                                   unsigned ArgSize,
2763                                   bool ForceMutable,
2764                                   unsigned ByValStoreOffset,
2765                                   unsigned TotalArgRegsSaveSize) const {
2766
2767   // Currently, two use-cases possible:
2768   // Case #1. Non-var-args function, and we meet first byval parameter.
2769   //          Setup first unallocated register as first byval register;
2770   //          eat all remained registers
2771   //          (these two actions are performed by HandleByVal method).
2772   //          Then, here, we initialize stack frame with
2773   //          "store-reg" instructions.
2774   // Case #2. Var-args function, that doesn't contain byval parameters.
2775   //          The same: eat all remained unallocated registers,
2776   //          initialize stack frame.
2777
2778   MachineFunction &MF = DAG.getMachineFunction();
2779   MachineFrameInfo *MFI = MF.getFrameInfo();
2780   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2781   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2782   unsigned RBegin, REnd;
2783   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2784     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2785     firstRegToSaveIndex = RBegin - ARM::R0;
2786     lastRegToSaveIndex = REnd - ARM::R0;
2787   } else {
2788     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2789       (GPRArgRegs, array_lengthof(GPRArgRegs));
2790     lastRegToSaveIndex = 4;
2791   }
2792
2793   unsigned ArgRegsSize, ArgRegsSaveSize;
2794   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2795                  ArgRegsSize, ArgRegsSaveSize);
2796
2797   // Store any by-val regs to their spots on the stack so that they may be
2798   // loaded by deferencing the result of formal parameter pointer or va_next.
2799   // Note: once stack area for byval/varargs registers
2800   // was initialized, it can't be initialized again.
2801   if (ArgRegsSaveSize) {
2802     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2803
2804     if (Padding) {
2805       assert(AFI->getStoredByValParamsPadding() == 0 &&
2806              "The only parameter may be padded.");
2807       AFI->setStoredByValParamsPadding(Padding);
2808     }
2809
2810     int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2811                                             Padding +
2812                                               ByValStoreOffset -
2813                                               (int64_t)TotalArgRegsSaveSize,
2814                                             false);
2815     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2816     if (Padding) {
2817        MFI->CreateFixedObject(Padding,
2818                               ArgOffset + ByValStoreOffset -
2819                                 (int64_t)ArgRegsSaveSize,
2820                               false);
2821     }
2822
2823     SmallVector<SDValue, 4> MemOps;
2824     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2825          ++firstRegToSaveIndex, ++i) {
2826       const TargetRegisterClass *RC;
2827       if (AFI->isThumb1OnlyFunction())
2828         RC = &ARM::tGPRRegClass;
2829       else
2830         RC = &ARM::GPRRegClass;
2831
2832       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2833       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2834       SDValue Store =
2835         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2836                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2837                      false, false, 0);
2838       MemOps.push_back(Store);
2839       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2840                         DAG.getConstant(4, getPointerTy()));
2841     }
2842
2843     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2844
2845     if (!MemOps.empty())
2846       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2847     return FrameIndex;
2848   } else {
2849     if (ArgSize == 0) {
2850       // We cannot allocate a zero-byte object for the first variadic argument,
2851       // so just make up a size.
2852       ArgSize = 4;
2853     }
2854     // This will point to the next argument passed via stack.
2855     return MFI->CreateFixedObject(
2856       ArgSize, ArgOffset, !ForceMutable);
2857   }
2858 }
2859
2860 // Setup stack frame, the va_list pointer will start from.
2861 void
2862 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2863                                         SDLoc dl, SDValue &Chain,
2864                                         unsigned ArgOffset,
2865                                         unsigned TotalArgRegsSaveSize,
2866                                         bool ForceMutable) const {
2867   MachineFunction &MF = DAG.getMachineFunction();
2868   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2869
2870   // Try to store any remaining integer argument regs
2871   // to their spots on the stack so that they may be loaded by deferencing
2872   // the result of va_next.
2873   // If there is no regs to be stored, just point address after last
2874   // argument passed via stack.
2875   int FrameIndex =
2876     StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2877                    CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
2878                    0, TotalArgRegsSaveSize);
2879
2880   AFI->setVarArgsFrameIndex(FrameIndex);
2881 }
2882
2883 SDValue
2884 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2885                                         CallingConv::ID CallConv, bool isVarArg,
2886                                         const SmallVectorImpl<ISD::InputArg>
2887                                           &Ins,
2888                                         SDLoc dl, SelectionDAG &DAG,
2889                                         SmallVectorImpl<SDValue> &InVals)
2890                                           const {
2891   MachineFunction &MF = DAG.getMachineFunction();
2892   MachineFrameInfo *MFI = MF.getFrameInfo();
2893
2894   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2895
2896   // Assign locations to all of the incoming arguments.
2897   SmallVector<CCValAssign, 16> ArgLocs;
2898   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2899                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2900   CCInfo.AnalyzeFormalArguments(Ins,
2901                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2902                                                   isVarArg));
2903
2904   SmallVector<SDValue, 16> ArgValues;
2905   int lastInsIndex = -1;
2906   SDValue ArgValue;
2907   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2908   unsigned CurArgIdx = 0;
2909
2910   // Initially ArgRegsSaveSize is zero.
2911   // Then we increase this value each time we meet byval parameter.
2912   // We also increase this value in case of varargs function.
2913   AFI->setArgRegsSaveSize(0);
2914
2915   unsigned ByValStoreOffset = 0;
2916   unsigned TotalArgRegsSaveSize = 0;
2917   unsigned ArgRegsSaveSizeMaxAlign = 4;
2918
2919   // Calculate the amount of stack space that we need to allocate to store
2920   // byval and variadic arguments that are passed in registers.
2921   // We need to know this before we allocate the first byval or variadic
2922   // argument, as they will be allocated a stack slot below the CFA (Canonical
2923   // Frame Address, the stack pointer at entry to the function).
2924   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2925     CCValAssign &VA = ArgLocs[i];
2926     if (VA.isMemLoc()) {
2927       int index = VA.getValNo();
2928       if (index != lastInsIndex) {
2929         ISD::ArgFlagsTy Flags = Ins[index].Flags;
2930         if (Flags.isByVal()) {
2931           unsigned ExtraArgRegsSize;
2932           unsigned ExtraArgRegsSaveSize;
2933           computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
2934                          Flags.getByValSize(),
2935                          ExtraArgRegsSize, ExtraArgRegsSaveSize);
2936
2937           TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2938           if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
2939               ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
2940           CCInfo.nextInRegsParam();
2941         }
2942         lastInsIndex = index;
2943       }
2944     }
2945   }
2946   CCInfo.rewindByValRegsInfo();
2947   lastInsIndex = -1;
2948   if (isVarArg) {
2949     unsigned ExtraArgRegsSize;
2950     unsigned ExtraArgRegsSaveSize;
2951     computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
2952                    ExtraArgRegsSize, ExtraArgRegsSaveSize);
2953     TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2954   }
2955   // If the arg regs save area contains N-byte aligned values, the
2956   // bottom of it must be at least N-byte aligned.
2957   TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
2958   TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
2959
2960   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2961     CCValAssign &VA = ArgLocs[i];
2962     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2963     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2964     // Arguments stored in registers.
2965     if (VA.isRegLoc()) {
2966       EVT RegVT = VA.getLocVT();
2967
2968       if (VA.needsCustom()) {
2969         // f64 and vector types are split up into multiple registers or
2970         // combinations of registers and stack slots.
2971         if (VA.getLocVT() == MVT::v2f64) {
2972           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2973                                                    Chain, DAG, dl);
2974           VA = ArgLocs[++i]; // skip ahead to next loc
2975           SDValue ArgValue2;
2976           if (VA.isMemLoc()) {
2977             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2978             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2979             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2980                                     MachinePointerInfo::getFixedStack(FI),
2981                                     false, false, false, 0);
2982           } else {
2983             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2984                                              Chain, DAG, dl);
2985           }
2986           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2987           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2988                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2989           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2990                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2991         } else
2992           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2993
2994       } else {
2995         const TargetRegisterClass *RC;
2996
2997         if (RegVT == MVT::f32)
2998           RC = &ARM::SPRRegClass;
2999         else if (RegVT == MVT::f64)
3000           RC = &ARM::DPRRegClass;
3001         else if (RegVT == MVT::v2f64)
3002           RC = &ARM::QPRRegClass;
3003         else if (RegVT == MVT::i32)
3004           RC = AFI->isThumb1OnlyFunction() ?
3005             (const TargetRegisterClass*)&ARM::tGPRRegClass :
3006             (const TargetRegisterClass*)&ARM::GPRRegClass;
3007         else
3008           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3009
3010         // Transform the arguments in physical registers into virtual ones.
3011         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3012         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3013       }
3014
3015       // If this is an 8 or 16-bit value, it is really passed promoted
3016       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3017       // truncate to the right size.
3018       switch (VA.getLocInfo()) {
3019       default: llvm_unreachable("Unknown loc info!");
3020       case CCValAssign::Full: break;
3021       case CCValAssign::BCvt:
3022         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3023         break;
3024       case CCValAssign::SExt:
3025         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3026                                DAG.getValueType(VA.getValVT()));
3027         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3028         break;
3029       case CCValAssign::ZExt:
3030         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3031                                DAG.getValueType(VA.getValVT()));
3032         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3033         break;
3034       }
3035
3036       InVals.push_back(ArgValue);
3037
3038     } else { // VA.isRegLoc()
3039
3040       // sanity check
3041       assert(VA.isMemLoc());
3042       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3043
3044       int index = ArgLocs[i].getValNo();
3045
3046       // Some Ins[] entries become multiple ArgLoc[] entries.
3047       // Process them only once.
3048       if (index != lastInsIndex)
3049         {
3050           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3051           // FIXME: For now, all byval parameter objects are marked mutable.
3052           // This can be changed with more analysis.
3053           // In case of tail call optimization mark all arguments mutable.
3054           // Since they could be overwritten by lowering of arguments in case of
3055           // a tail call.
3056           if (Flags.isByVal()) {
3057             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3058
3059             ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3060             int FrameIndex = StoreByValRegs(
3061                 CCInfo, DAG, dl, Chain, CurOrigArg,
3062                 CurByValIndex,
3063                 Ins[VA.getValNo()].PartOffset,
3064                 VA.getLocMemOffset(),
3065                 Flags.getByValSize(),
3066                 true /*force mutable frames*/,
3067                 ByValStoreOffset,
3068                 TotalArgRegsSaveSize);
3069             ByValStoreOffset += Flags.getByValSize();
3070             ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3071             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3072             CCInfo.nextInRegsParam();
3073           } else {
3074             unsigned FIOffset = VA.getLocMemOffset();
3075             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3076                                             FIOffset, true);
3077
3078             // Create load nodes to retrieve arguments from the stack.
3079             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3080             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3081                                          MachinePointerInfo::getFixedStack(FI),
3082                                          false, false, false, 0));
3083           }
3084           lastInsIndex = index;
3085         }
3086     }
3087   }
3088
3089   // varargs
3090   if (isVarArg)
3091     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3092                          CCInfo.getNextStackOffset(),
3093                          TotalArgRegsSaveSize);
3094
3095   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3096
3097   return Chain;
3098 }
3099
3100 /// isFloatingPointZero - Return true if this is +0.0.
3101 static bool isFloatingPointZero(SDValue Op) {
3102   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3103     return CFP->getValueAPF().isPosZero();
3104   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3105     // Maybe this has already been legalized into the constant pool?
3106     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3107       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3108       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3109         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3110           return CFP->getValueAPF().isPosZero();
3111     }
3112   }
3113   return false;
3114 }
3115
3116 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3117 /// the given operands.
3118 SDValue
3119 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3120                              SDValue &ARMcc, SelectionDAG &DAG,
3121                              SDLoc dl) const {
3122   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3123     unsigned C = RHSC->getZExtValue();
3124     if (!isLegalICmpImmediate(C)) {
3125       // Constant does not fit, try adjusting it by one?
3126       switch (CC) {
3127       default: break;
3128       case ISD::SETLT:
3129       case ISD::SETGE:
3130         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3131           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3132           RHS = DAG.getConstant(C-1, MVT::i32);
3133         }
3134         break;
3135       case ISD::SETULT:
3136       case ISD::SETUGE:
3137         if (C != 0 && isLegalICmpImmediate(C-1)) {
3138           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3139           RHS = DAG.getConstant(C-1, MVT::i32);
3140         }
3141         break;
3142       case ISD::SETLE:
3143       case ISD::SETGT:
3144         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3145           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3146           RHS = DAG.getConstant(C+1, MVT::i32);
3147         }
3148         break;
3149       case ISD::SETULE:
3150       case ISD::SETUGT:
3151         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3152           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3153           RHS = DAG.getConstant(C+1, MVT::i32);
3154         }
3155         break;
3156       }
3157     }
3158   }
3159
3160   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3161   ARMISD::NodeType CompareType;
3162   switch (CondCode) {
3163   default:
3164     CompareType = ARMISD::CMP;
3165     break;
3166   case ARMCC::EQ:
3167   case ARMCC::NE:
3168     // Uses only Z Flag
3169     CompareType = ARMISD::CMPZ;
3170     break;
3171   }
3172   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3173   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3174 }
3175
3176 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3177 SDValue
3178 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3179                              SDLoc dl) const {
3180   SDValue Cmp;
3181   if (!isFloatingPointZero(RHS))
3182     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3183   else
3184     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3185   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3186 }
3187
3188 /// duplicateCmp - Glue values can have only one use, so this function
3189 /// duplicates a comparison node.
3190 SDValue
3191 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3192   unsigned Opc = Cmp.getOpcode();
3193   SDLoc DL(Cmp);
3194   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3195     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3196
3197   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3198   Cmp = Cmp.getOperand(0);
3199   Opc = Cmp.getOpcode();
3200   if (Opc == ARMISD::CMPFP)
3201     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3202   else {
3203     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3204     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3205   }
3206   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3207 }
3208
3209 std::pair<SDValue, SDValue>
3210 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3211                                  SDValue &ARMcc) const {
3212   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3213
3214   SDValue Value, OverflowCmp;
3215   SDValue LHS = Op.getOperand(0);
3216   SDValue RHS = Op.getOperand(1);
3217
3218
3219   // FIXME: We are currently always generating CMPs because we don't support
3220   // generating CMN through the backend. This is not as good as the natural
3221   // CMP case because it causes a register dependency and cannot be folded
3222   // later.
3223
3224   switch (Op.getOpcode()) {
3225   default:
3226     llvm_unreachable("Unknown overflow instruction!");
3227   case ISD::SADDO:
3228     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3229     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3230     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3231     break;
3232   case ISD::UADDO:
3233     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3234     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3235     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3236     break;
3237   case ISD::SSUBO:
3238     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3239     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3240     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3241     break;
3242   case ISD::USUBO:
3243     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3244     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3245     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3246     break;
3247   } // switch (...)
3248
3249   return std::make_pair(Value, OverflowCmp);
3250 }
3251
3252
3253 SDValue
3254 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3255   // Let legalize expand this if it isn't a legal type yet.
3256   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3257     return SDValue();
3258
3259   SDValue Value, OverflowCmp;
3260   SDValue ARMcc;
3261   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3262   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3263   // We use 0 and 1 as false and true values.
3264   SDValue TVal = DAG.getConstant(1, MVT::i32);
3265   SDValue FVal = DAG.getConstant(0, MVT::i32);
3266   EVT VT = Op.getValueType();
3267
3268   SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3269                                  ARMcc, CCR, OverflowCmp);
3270
3271   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3272   return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3273 }
3274
3275
3276 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3277   SDValue Cond = Op.getOperand(0);
3278   SDValue SelectTrue = Op.getOperand(1);
3279   SDValue SelectFalse = Op.getOperand(2);
3280   SDLoc dl(Op);
3281   unsigned Opc = Cond.getOpcode();
3282
3283   if (Cond.getResNo() == 1 &&
3284       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3285        Opc == ISD::USUBO)) {
3286     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3287       return SDValue();
3288
3289     SDValue Value, OverflowCmp;
3290     SDValue ARMcc;
3291     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3292     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3293     EVT VT = Op.getValueType();
3294
3295     return DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, SelectTrue, SelectFalse,
3296                        ARMcc, CCR, OverflowCmp);
3297
3298   }
3299
3300   // Convert:
3301   //
3302   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3303   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3304   //
3305   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3306     const ConstantSDNode *CMOVTrue =
3307       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3308     const ConstantSDNode *CMOVFalse =
3309       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3310
3311     if (CMOVTrue && CMOVFalse) {
3312       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3313       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3314
3315       SDValue True;
3316       SDValue False;
3317       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3318         True = SelectTrue;
3319         False = SelectFalse;
3320       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3321         True = SelectFalse;
3322         False = SelectTrue;
3323       }
3324
3325       if (True.getNode() && False.getNode()) {
3326         EVT VT = Op.getValueType();
3327         SDValue ARMcc = Cond.getOperand(2);
3328         SDValue CCR = Cond.getOperand(3);
3329         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3330         assert(True.getValueType() == VT);
3331         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3332       }
3333     }
3334   }
3335
3336   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3337   // undefined bits before doing a full-word comparison with zero.
3338   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3339                      DAG.getConstant(1, Cond.getValueType()));
3340
3341   return DAG.getSelectCC(dl, Cond,
3342                          DAG.getConstant(0, Cond.getValueType()),
3343                          SelectTrue, SelectFalse, ISD::SETNE);
3344 }
3345
3346 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3347   if (CC == ISD::SETNE)
3348     return ISD::SETEQ;
3349   return ISD::getSetCCInverse(CC, true);
3350 }
3351
3352 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3353                                  bool &swpCmpOps, bool &swpVselOps) {
3354   // Start by selecting the GE condition code for opcodes that return true for
3355   // 'equality'
3356   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3357       CC == ISD::SETULE)
3358     CondCode = ARMCC::GE;
3359
3360   // and GT for opcodes that return false for 'equality'.
3361   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3362            CC == ISD::SETULT)
3363     CondCode = ARMCC::GT;
3364
3365   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3366   // to swap the compare operands.
3367   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3368       CC == ISD::SETULT)
3369     swpCmpOps = true;
3370
3371   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3372   // If we have an unordered opcode, we need to swap the operands to the VSEL
3373   // instruction (effectively negating the condition).
3374   //
3375   // This also has the effect of swapping which one of 'less' or 'greater'
3376   // returns true, so we also swap the compare operands. It also switches
3377   // whether we return true for 'equality', so we compensate by picking the
3378   // opposite condition code to our original choice.
3379   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3380       CC == ISD::SETUGT) {
3381     swpCmpOps = !swpCmpOps;
3382     swpVselOps = !swpVselOps;
3383     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3384   }
3385
3386   // 'ordered' is 'anything but unordered', so use the VS condition code and
3387   // swap the VSEL operands.
3388   if (CC == ISD::SETO) {
3389     CondCode = ARMCC::VS;
3390     swpVselOps = true;
3391   }
3392
3393   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3394   // code and swap the VSEL operands.
3395   if (CC == ISD::SETUNE) {
3396     CondCode = ARMCC::EQ;
3397     swpVselOps = true;
3398   }
3399 }
3400
3401 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3402   EVT VT = Op.getValueType();
3403   SDValue LHS = Op.getOperand(0);
3404   SDValue RHS = Op.getOperand(1);
3405   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3406   SDValue TrueVal = Op.getOperand(2);
3407   SDValue FalseVal = Op.getOperand(3);
3408   SDLoc dl(Op);
3409
3410   if (LHS.getValueType() == MVT::i32) {
3411     // Try to generate VSEL on ARMv8.
3412     // The VSEL instruction can't use all the usual ARM condition
3413     // codes: it only has two bits to select the condition code, so it's
3414     // constrained to use only GE, GT, VS and EQ.
3415     //
3416     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3417     // swap the operands of the previous compare instruction (effectively
3418     // inverting the compare condition, swapping 'less' and 'greater') and
3419     // sometimes need to swap the operands to the VSEL (which inverts the
3420     // condition in the sense of firing whenever the previous condition didn't)
3421     if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3422                                       TrueVal.getValueType() == MVT::f64)) {
3423       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3424       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3425           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3426         CC = getInverseCCForVSEL(CC);
3427         std::swap(TrueVal, FalseVal);
3428       }
3429     }
3430
3431     SDValue ARMcc;
3432     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3433     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3434     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3435                        Cmp);
3436   }
3437
3438   ARMCC::CondCodes CondCode, CondCode2;
3439   FPCCToARMCC(CC, CondCode, CondCode2);
3440
3441   // Try to generate VSEL on ARMv8.
3442   if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3443                                     TrueVal.getValueType() == MVT::f64)) {
3444     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3445     // same operands, as follows:
3446     //   c = fcmp [ogt, olt, ugt, ult] a, b
3447     //   select c, a, b
3448     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3449     // handled differently than the original code sequence.
3450     if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3451         RHS == FalseVal) {
3452       if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3453         return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3454       if (CC == ISD::SETOLT || CC == ISD::SETULT)
3455         return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3456     }
3457
3458     bool swpCmpOps = false;
3459     bool swpVselOps = false;
3460     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3461
3462     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3463         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3464       if (swpCmpOps)
3465         std::swap(LHS, RHS);
3466       if (swpVselOps)
3467         std::swap(TrueVal, FalseVal);
3468     }
3469   }
3470
3471   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3472   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3473   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3474   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3475                                ARMcc, CCR, Cmp);
3476   if (CondCode2 != ARMCC::AL) {
3477     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3478     // FIXME: Needs another CMP because flag can have but one use.
3479     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3480     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3481                          Result, TrueVal, ARMcc2, CCR, Cmp2);
3482   }
3483   return Result;
3484 }
3485
3486 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3487 /// to morph to an integer compare sequence.
3488 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3489                            const ARMSubtarget *Subtarget) {
3490   SDNode *N = Op.getNode();
3491   if (!N->hasOneUse())
3492     // Otherwise it requires moving the value from fp to integer registers.
3493     return false;
3494   if (!N->getNumValues())
3495     return false;
3496   EVT VT = Op.getValueType();
3497   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3498     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3499     // vmrs are very slow, e.g. cortex-a8.
3500     return false;
3501
3502   if (isFloatingPointZero(Op)) {
3503     SeenZero = true;
3504     return true;
3505   }
3506   return ISD::isNormalLoad(N);
3507 }
3508
3509 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3510   if (isFloatingPointZero(Op))
3511     return DAG.getConstant(0, MVT::i32);
3512
3513   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3514     return DAG.getLoad(MVT::i32, SDLoc(Op),
3515                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3516                        Ld->isVolatile(), Ld->isNonTemporal(),
3517                        Ld->isInvariant(), Ld->getAlignment());
3518
3519   llvm_unreachable("Unknown VFP cmp argument!");
3520 }
3521
3522 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3523                            SDValue &RetVal1, SDValue &RetVal2) {
3524   if (isFloatingPointZero(Op)) {
3525     RetVal1 = DAG.getConstant(0, MVT::i32);
3526     RetVal2 = DAG.getConstant(0, MVT::i32);
3527     return;
3528   }
3529
3530   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3531     SDValue Ptr = Ld->getBasePtr();
3532     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3533                           Ld->getChain(), Ptr,
3534                           Ld->getPointerInfo(),
3535                           Ld->isVolatile(), Ld->isNonTemporal(),
3536                           Ld->isInvariant(), Ld->getAlignment());
3537
3538     EVT PtrType = Ptr.getValueType();
3539     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3540     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3541                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3542     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3543                           Ld->getChain(), NewPtr,
3544                           Ld->getPointerInfo().getWithOffset(4),
3545                           Ld->isVolatile(), Ld->isNonTemporal(),
3546                           Ld->isInvariant(), NewAlign);
3547     return;
3548   }
3549
3550   llvm_unreachable("Unknown VFP cmp argument!");
3551 }
3552
3553 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3554 /// f32 and even f64 comparisons to integer ones.
3555 SDValue
3556 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3557   SDValue Chain = Op.getOperand(0);
3558   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3559   SDValue LHS = Op.getOperand(2);
3560   SDValue RHS = Op.getOperand(3);
3561   SDValue Dest = Op.getOperand(4);
3562   SDLoc dl(Op);
3563
3564   bool LHSSeenZero = false;
3565   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3566   bool RHSSeenZero = false;
3567   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3568   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3569     // If unsafe fp math optimization is enabled and there are no other uses of
3570     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3571     // to an integer comparison.
3572     if (CC == ISD::SETOEQ)
3573       CC = ISD::SETEQ;
3574     else if (CC == ISD::SETUNE)
3575       CC = ISD::SETNE;
3576
3577     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3578     SDValue ARMcc;
3579     if (LHS.getValueType() == MVT::f32) {
3580       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3581                         bitcastf32Toi32(LHS, DAG), Mask);
3582       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3583                         bitcastf32Toi32(RHS, DAG), Mask);
3584       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3585       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3586       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3587                          Chain, Dest, ARMcc, CCR, Cmp);
3588     }
3589
3590     SDValue LHS1, LHS2;
3591     SDValue RHS1, RHS2;
3592     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3593     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3594     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3595     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3596     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3597     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3598     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3599     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3600     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3601   }
3602
3603   return SDValue();
3604 }
3605
3606 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3607   SDValue Chain = Op.getOperand(0);
3608   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3609   SDValue LHS = Op.getOperand(2);
3610   SDValue RHS = Op.getOperand(3);
3611   SDValue Dest = Op.getOperand(4);
3612   SDLoc dl(Op);
3613
3614   if (LHS.getValueType() == MVT::i32) {
3615     SDValue ARMcc;
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   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3623
3624   if (getTargetMachine().Options.UnsafeFPMath &&
3625       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3626        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3627     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3628     if (Result.getNode())
3629       return Result;
3630   }
3631
3632   ARMCC::CondCodes CondCode, CondCode2;
3633   FPCCToARMCC(CC, CondCode, CondCode2);
3634
3635   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3636   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3637   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3638   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3639   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3640   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3641   if (CondCode2 != ARMCC::AL) {
3642     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3643     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3644     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3645   }
3646   return Res;
3647 }
3648
3649 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3650   SDValue Chain = Op.getOperand(0);
3651   SDValue Table = Op.getOperand(1);
3652   SDValue Index = Op.getOperand(2);
3653   SDLoc dl(Op);
3654
3655   EVT PTy = getPointerTy();
3656   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3657   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3658   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3659   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3660   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3661   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3662   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3663   if (Subtarget->isThumb2()) {
3664     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3665     // which does another jump to the destination. This also makes it easier
3666     // to translate it to TBB / TBH later.
3667     // FIXME: This might not work if the function is extremely large.
3668     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3669                        Addr, Op.getOperand(2), JTI, UId);
3670   }
3671   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3672     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3673                        MachinePointerInfo::getJumpTable(),
3674                        false, false, false, 0);
3675     Chain = Addr.getValue(1);
3676     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3677     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3678   } else {
3679     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3680                        MachinePointerInfo::getJumpTable(),
3681                        false, false, false, 0);
3682     Chain = Addr.getValue(1);
3683     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3684   }
3685 }
3686
3687 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3688   EVT VT = Op.getValueType();
3689   SDLoc dl(Op);
3690
3691   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3692     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3693       return Op;
3694     return DAG.UnrollVectorOp(Op.getNode());
3695   }
3696
3697   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3698          "Invalid type for custom lowering!");
3699   if (VT != MVT::v4i16)
3700     return DAG.UnrollVectorOp(Op.getNode());
3701
3702   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3703   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3704 }
3705
3706 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3707   EVT VT = Op.getValueType();
3708   if (VT.isVector())
3709     return LowerVectorFP_TO_INT(Op, DAG);
3710
3711   SDLoc dl(Op);
3712   unsigned Opc;
3713
3714   switch (Op.getOpcode()) {
3715   default: llvm_unreachable("Invalid opcode!");
3716   case ISD::FP_TO_SINT:
3717     Opc = ARMISD::FTOSI;
3718     break;
3719   case ISD::FP_TO_UINT:
3720     Opc = ARMISD::FTOUI;
3721     break;
3722   }
3723   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3724   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3725 }
3726
3727 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3728   EVT VT = Op.getValueType();
3729   SDLoc dl(Op);
3730
3731   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3732     if (VT.getVectorElementType() == MVT::f32)
3733       return Op;
3734     return DAG.UnrollVectorOp(Op.getNode());
3735   }
3736
3737   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3738          "Invalid type for custom lowering!");
3739   if (VT != MVT::v4f32)
3740     return DAG.UnrollVectorOp(Op.getNode());
3741
3742   unsigned CastOpc;
3743   unsigned Opc;
3744   switch (Op.getOpcode()) {
3745   default: llvm_unreachable("Invalid opcode!");
3746   case ISD::SINT_TO_FP:
3747     CastOpc = ISD::SIGN_EXTEND;
3748     Opc = ISD::SINT_TO_FP;
3749     break;
3750   case ISD::UINT_TO_FP:
3751     CastOpc = ISD::ZERO_EXTEND;
3752     Opc = ISD::UINT_TO_FP;
3753     break;
3754   }
3755
3756   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3757   return DAG.getNode(Opc, dl, VT, Op);
3758 }
3759
3760 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3761   EVT VT = Op.getValueType();
3762   if (VT.isVector())
3763     return LowerVectorINT_TO_FP(Op, DAG);
3764
3765   SDLoc dl(Op);
3766   unsigned Opc;
3767
3768   switch (Op.getOpcode()) {
3769   default: llvm_unreachable("Invalid opcode!");
3770   case ISD::SINT_TO_FP:
3771     Opc = ARMISD::SITOF;
3772     break;
3773   case ISD::UINT_TO_FP:
3774     Opc = ARMISD::UITOF;
3775     break;
3776   }
3777
3778   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3779   return DAG.getNode(Opc, dl, VT, Op);
3780 }
3781
3782 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3783   // Implement fcopysign with a fabs and a conditional fneg.
3784   SDValue Tmp0 = Op.getOperand(0);
3785   SDValue Tmp1 = Op.getOperand(1);
3786   SDLoc dl(Op);
3787   EVT VT = Op.getValueType();
3788   EVT SrcVT = Tmp1.getValueType();
3789   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3790     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3791   bool UseNEON = !InGPR && Subtarget->hasNEON();
3792
3793   if (UseNEON) {
3794     // Use VBSL to copy the sign bit.
3795     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3796     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3797                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3798     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3799     if (VT == MVT::f64)
3800       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3801                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3802                          DAG.getConstant(32, MVT::i32));
3803     else /*if (VT == MVT::f32)*/
3804       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3805     if (SrcVT == MVT::f32) {
3806       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3807       if (VT == MVT::f64)
3808         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3809                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3810                            DAG.getConstant(32, MVT::i32));
3811     } else if (VT == MVT::f32)
3812       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3813                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3814                          DAG.getConstant(32, MVT::i32));
3815     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3816     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3817
3818     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3819                                             MVT::i32);
3820     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3821     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3822                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3823
3824     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3825                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3826                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3827     if (VT == MVT::f32) {
3828       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3829       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3830                         DAG.getConstant(0, MVT::i32));
3831     } else {
3832       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3833     }
3834
3835     return Res;
3836   }
3837
3838   // Bitcast operand 1 to i32.
3839   if (SrcVT == MVT::f64)
3840     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3841                        Tmp1).getValue(1);
3842   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3843
3844   // Or in the signbit with integer operations.
3845   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3846   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3847   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3848   if (VT == MVT::f32) {
3849     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3850                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3851     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3852                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3853   }
3854
3855   // f64: Or the high part with signbit and then combine two parts.
3856   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3857                      Tmp0);
3858   SDValue Lo = Tmp0.getValue(0);
3859   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3860   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3861   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3862 }
3863
3864 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3865   MachineFunction &MF = DAG.getMachineFunction();
3866   MachineFrameInfo *MFI = MF.getFrameInfo();
3867   MFI->setReturnAddressIsTaken(true);
3868
3869   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3870     return SDValue();
3871
3872   EVT VT = Op.getValueType();
3873   SDLoc dl(Op);
3874   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3875   if (Depth) {
3876     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3877     SDValue Offset = DAG.getConstant(4, MVT::i32);
3878     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3879                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3880                        MachinePointerInfo(), false, false, false, 0);
3881   }
3882
3883   // Return LR, which contains the return address. Mark it an implicit live-in.
3884   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3885   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3886 }
3887
3888 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3889   const ARMBaseRegisterInfo &ARI =
3890     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
3891   MachineFunction &MF = DAG.getMachineFunction();
3892   MachineFrameInfo *MFI = MF.getFrameInfo();
3893   MFI->setFrameAddressIsTaken(true);
3894
3895   EVT VT = Op.getValueType();
3896   SDLoc dl(Op);  // FIXME probably not meaningful
3897   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3898   unsigned FrameReg = ARI.getFrameRegister(MF);
3899   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3900   while (Depth--)
3901     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3902                             MachinePointerInfo(),
3903                             false, false, false, 0);
3904   return FrameAddr;
3905 }
3906
3907 // FIXME? Maybe this could be a TableGen attribute on some registers and
3908 // this table could be generated automatically from RegInfo.
3909 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
3910                                               EVT VT) const {
3911   unsigned Reg = StringSwitch<unsigned>(RegName)
3912                        .Case("sp", ARM::SP)
3913                        .Default(0);
3914   if (Reg)
3915     return Reg;
3916   report_fatal_error("Invalid register name global variable");
3917 }
3918
3919 /// ExpandBITCAST - If the target supports VFP, this function is called to
3920 /// expand a bit convert where either the source or destination type is i64 to
3921 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3922 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3923 /// vectors), since the legalizer won't know what to do with that.
3924 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3925   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3926   SDLoc dl(N);
3927   SDValue Op = N->getOperand(0);
3928
3929   // This function is only supposed to be called for i64 types, either as the
3930   // source or destination of the bit convert.
3931   EVT SrcVT = Op.getValueType();
3932   EVT DstVT = N->getValueType(0);
3933   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3934          "ExpandBITCAST called for non-i64 type");
3935
3936   // Turn i64->f64 into VMOVDRR.
3937   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3938     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3939                              DAG.getConstant(0, MVT::i32));
3940     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3941                              DAG.getConstant(1, MVT::i32));
3942     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3943                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3944   }
3945
3946   // Turn f64->i64 into VMOVRRD.
3947   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3948     SDValue Cvt;
3949     if (TLI.isBigEndian() && SrcVT.isVector() &&
3950         SrcVT.getVectorNumElements() > 1)
3951       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3952                         DAG.getVTList(MVT::i32, MVT::i32),
3953                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
3954     else
3955       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3956                         DAG.getVTList(MVT::i32, MVT::i32), Op);
3957     // Merge the pieces into a single i64 value.
3958     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3959   }
3960
3961   return SDValue();
3962 }
3963
3964 /// getZeroVector - Returns a vector of specified type with all zero elements.
3965 /// Zero vectors are used to represent vector negation and in those cases
3966 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3967 /// not support i64 elements, so sometimes the zero vectors will need to be
3968 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3969 /// zero vector.
3970 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3971   assert(VT.isVector() && "Expected a vector type");
3972   // The canonical modified immediate encoding of a zero vector is....0!
3973   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3974   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3975   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3976   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3977 }
3978
3979 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3980 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3981 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3982                                                 SelectionDAG &DAG) const {
3983   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3984   EVT VT = Op.getValueType();
3985   unsigned VTBits = VT.getSizeInBits();
3986   SDLoc dl(Op);
3987   SDValue ShOpLo = Op.getOperand(0);
3988   SDValue ShOpHi = Op.getOperand(1);
3989   SDValue ShAmt  = Op.getOperand(2);
3990   SDValue ARMcc;
3991   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3992
3993   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3994
3995   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3996                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3997   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3998   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3999                                    DAG.getConstant(VTBits, MVT::i32));
4000   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4001   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4002   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4003
4004   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4005   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4006                           ARMcc, DAG, dl);
4007   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4008   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4009                            CCR, Cmp);
4010
4011   SDValue Ops[2] = { Lo, Hi };
4012   return DAG.getMergeValues(Ops, dl);
4013 }
4014
4015 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4016 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4017 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4018                                                SelectionDAG &DAG) const {
4019   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4020   EVT VT = Op.getValueType();
4021   unsigned VTBits = VT.getSizeInBits();
4022   SDLoc dl(Op);
4023   SDValue ShOpLo = Op.getOperand(0);
4024   SDValue ShOpHi = Op.getOperand(1);
4025   SDValue ShAmt  = Op.getOperand(2);
4026   SDValue ARMcc;
4027
4028   assert(Op.getOpcode() == ISD::SHL_PARTS);
4029   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4030                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4031   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4032   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4033                                    DAG.getConstant(VTBits, MVT::i32));
4034   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4035   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4036
4037   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4038   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4039   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4040                           ARMcc, DAG, dl);
4041   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4042   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4043                            CCR, Cmp);
4044
4045   SDValue Ops[2] = { Lo, Hi };
4046   return DAG.getMergeValues(Ops, dl);
4047 }
4048
4049 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4050                                             SelectionDAG &DAG) const {
4051   // The rounding mode is in bits 23:22 of the FPSCR.
4052   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4053   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4054   // so that the shift + and get folded into a bitfield extract.
4055   SDLoc dl(Op);
4056   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4057                               DAG.getConstant(Intrinsic::arm_get_fpscr,
4058                                               MVT::i32));
4059   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4060                                   DAG.getConstant(1U << 22, MVT::i32));
4061   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4062                               DAG.getConstant(22, MVT::i32));
4063   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4064                      DAG.getConstant(3, MVT::i32));
4065 }
4066
4067 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4068                          const ARMSubtarget *ST) {
4069   EVT VT = N->getValueType(0);
4070   SDLoc dl(N);
4071
4072   if (!ST->hasV6T2Ops())
4073     return SDValue();
4074
4075   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4076   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4077 }
4078
4079 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4080 /// for each 16-bit element from operand, repeated.  The basic idea is to
4081 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4082 ///
4083 /// Trace for v4i16:
4084 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4085 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4086 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4087 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4088 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4089 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4090 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4091 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4092 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4093   EVT VT = N->getValueType(0);
4094   SDLoc DL(N);
4095
4096   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4097   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4098   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4099   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4100   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4101   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4102 }
4103
4104 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4105 /// bit-count for each 16-bit element from the operand.  We need slightly
4106 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4107 /// 64/128-bit registers.
4108 ///
4109 /// Trace for v4i16:
4110 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4111 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4112 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4113 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4114 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4115   EVT VT = N->getValueType(0);
4116   SDLoc DL(N);
4117
4118   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4119   if (VT.is64BitVector()) {
4120     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4121     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4122                        DAG.getIntPtrConstant(0));
4123   } else {
4124     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4125                                     BitCounts, DAG.getIntPtrConstant(0));
4126     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4127   }
4128 }
4129
4130 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4131 /// bit-count for each 32-bit element from the operand.  The idea here is
4132 /// to split the vector into 16-bit elements, leverage the 16-bit count
4133 /// routine, and then combine the results.
4134 ///
4135 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4136 /// input    = [v0    v1    ] (vi: 32-bit elements)
4137 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4138 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4139 /// vrev: N0 = [k1 k0 k3 k2 ]
4140 ///            [k0 k1 k2 k3 ]
4141 ///       N1 =+[k1 k0 k3 k2 ]
4142 ///            [k0 k2 k1 k3 ]
4143 ///       N2 =+[k1 k3 k0 k2 ]
4144 ///            [k0    k2    k1    k3    ]
4145 /// Extended =+[k1    k3    k0    k2    ]
4146 ///            [k0    k2    ]
4147 /// Extracted=+[k1    k3    ]
4148 ///
4149 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4150   EVT VT = N->getValueType(0);
4151   SDLoc DL(N);
4152
4153   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4154
4155   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4156   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4157   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4158   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4159   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4160
4161   if (VT.is64BitVector()) {
4162     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4163     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4164                        DAG.getIntPtrConstant(0));
4165   } else {
4166     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4167                                     DAG.getIntPtrConstant(0));
4168     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4169   }
4170 }
4171
4172 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4173                           const ARMSubtarget *ST) {
4174   EVT VT = N->getValueType(0);
4175
4176   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4177   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4178           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4179          "Unexpected type for custom ctpop lowering");
4180
4181   if (VT.getVectorElementType() == MVT::i32)
4182     return lowerCTPOP32BitElements(N, DAG);
4183   else
4184     return lowerCTPOP16BitElements(N, DAG);
4185 }
4186
4187 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4188                           const ARMSubtarget *ST) {
4189   EVT VT = N->getValueType(0);
4190   SDLoc dl(N);
4191
4192   if (!VT.isVector())
4193     return SDValue();
4194
4195   // Lower vector shifts on NEON to use VSHL.
4196   assert(ST->hasNEON() && "unexpected vector shift");
4197
4198   // Left shifts translate directly to the vshiftu intrinsic.
4199   if (N->getOpcode() == ISD::SHL)
4200     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4201                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4202                        N->getOperand(0), N->getOperand(1));
4203
4204   assert((N->getOpcode() == ISD::SRA ||
4205           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4206
4207   // NEON uses the same intrinsics for both left and right shifts.  For
4208   // right shifts, the shift amounts are negative, so negate the vector of
4209   // shift amounts.
4210   EVT ShiftVT = N->getOperand(1).getValueType();
4211   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4212                                      getZeroVector(ShiftVT, DAG, dl),
4213                                      N->getOperand(1));
4214   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4215                              Intrinsic::arm_neon_vshifts :
4216                              Intrinsic::arm_neon_vshiftu);
4217   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4218                      DAG.getConstant(vshiftInt, MVT::i32),
4219                      N->getOperand(0), NegatedCount);
4220 }
4221
4222 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4223                                 const ARMSubtarget *ST) {
4224   EVT VT = N->getValueType(0);
4225   SDLoc dl(N);
4226
4227   // We can get here for a node like i32 = ISD::SHL i32, i64
4228   if (VT != MVT::i64)
4229     return SDValue();
4230
4231   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4232          "Unknown shift to lower!");
4233
4234   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4235   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4236       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4237     return SDValue();
4238
4239   // If we are in thumb mode, we don't have RRX.
4240   if (ST->isThumb1Only()) return SDValue();
4241
4242   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4243   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4244                            DAG.getConstant(0, MVT::i32));
4245   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4246                            DAG.getConstant(1, MVT::i32));
4247
4248   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4249   // captures the result into a carry flag.
4250   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4251   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4252
4253   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4254   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4255
4256   // Merge the pieces into a single i64 value.
4257  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4258 }
4259
4260 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4261   SDValue TmpOp0, TmpOp1;
4262   bool Invert = false;
4263   bool Swap = false;
4264   unsigned Opc = 0;
4265
4266   SDValue Op0 = Op.getOperand(0);
4267   SDValue Op1 = Op.getOperand(1);
4268   SDValue CC = Op.getOperand(2);
4269   EVT VT = Op.getValueType();
4270   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4271   SDLoc dl(Op);
4272
4273   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4274     switch (SetCCOpcode) {
4275     default: llvm_unreachable("Illegal FP comparison");
4276     case ISD::SETUNE:
4277     case ISD::SETNE:  Invert = true; // Fallthrough
4278     case ISD::SETOEQ:
4279     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4280     case ISD::SETOLT:
4281     case ISD::SETLT: Swap = true; // Fallthrough
4282     case ISD::SETOGT:
4283     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4284     case ISD::SETOLE:
4285     case ISD::SETLE:  Swap = true; // Fallthrough
4286     case ISD::SETOGE:
4287     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4288     case ISD::SETUGE: Swap = true; // Fallthrough
4289     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4290     case ISD::SETUGT: Swap = true; // Fallthrough
4291     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4292     case ISD::SETUEQ: Invert = true; // Fallthrough
4293     case ISD::SETONE:
4294       // Expand this to (OLT | OGT).
4295       TmpOp0 = Op0;
4296       TmpOp1 = Op1;
4297       Opc = ISD::OR;
4298       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4299       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4300       break;
4301     case ISD::SETUO: Invert = true; // Fallthrough
4302     case ISD::SETO:
4303       // Expand this to (OLT | OGE).
4304       TmpOp0 = Op0;
4305       TmpOp1 = Op1;
4306       Opc = ISD::OR;
4307       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4308       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4309       break;
4310     }
4311   } else {
4312     // Integer comparisons.
4313     switch (SetCCOpcode) {
4314     default: llvm_unreachable("Illegal integer comparison");
4315     case ISD::SETNE:  Invert = true;
4316     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4317     case ISD::SETLT:  Swap = true;
4318     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4319     case ISD::SETLE:  Swap = true;
4320     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4321     case ISD::SETULT: Swap = true;
4322     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4323     case ISD::SETULE: Swap = true;
4324     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4325     }
4326
4327     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4328     if (Opc == ARMISD::VCEQ) {
4329
4330       SDValue AndOp;
4331       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4332         AndOp = Op0;
4333       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4334         AndOp = Op1;
4335
4336       // Ignore bitconvert.
4337       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4338         AndOp = AndOp.getOperand(0);
4339
4340       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4341         Opc = ARMISD::VTST;
4342         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4343         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4344         Invert = !Invert;
4345       }
4346     }
4347   }
4348
4349   if (Swap)
4350     std::swap(Op0, Op1);
4351
4352   // If one of the operands is a constant vector zero, attempt to fold the
4353   // comparison to a specialized compare-against-zero form.
4354   SDValue SingleOp;
4355   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4356     SingleOp = Op0;
4357   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4358     if (Opc == ARMISD::VCGE)
4359       Opc = ARMISD::VCLEZ;
4360     else if (Opc == ARMISD::VCGT)
4361       Opc = ARMISD::VCLTZ;
4362     SingleOp = Op1;
4363   }
4364
4365   SDValue Result;
4366   if (SingleOp.getNode()) {
4367     switch (Opc) {
4368     case ARMISD::VCEQ:
4369       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4370     case ARMISD::VCGE:
4371       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4372     case ARMISD::VCLEZ:
4373       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4374     case ARMISD::VCGT:
4375       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4376     case ARMISD::VCLTZ:
4377       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4378     default:
4379       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4380     }
4381   } else {
4382      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4383   }
4384
4385   if (Invert)
4386     Result = DAG.getNOT(dl, Result, VT);
4387
4388   return Result;
4389 }
4390
4391 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4392 /// valid vector constant for a NEON instruction with a "modified immediate"
4393 /// operand (e.g., VMOV).  If so, return the encoded value.
4394 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4395                                  unsigned SplatBitSize, SelectionDAG &DAG,
4396                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4397   unsigned OpCmode, Imm;
4398
4399   // SplatBitSize is set to the smallest size that splats the vector, so a
4400   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4401   // immediate instructions others than VMOV do not support the 8-bit encoding
4402   // of a zero vector, and the default encoding of zero is supposed to be the
4403   // 32-bit version.
4404   if (SplatBits == 0)
4405     SplatBitSize = 32;
4406
4407   switch (SplatBitSize) {
4408   case 8:
4409     if (type != VMOVModImm)
4410       return SDValue();
4411     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4412     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4413     OpCmode = 0xe;
4414     Imm = SplatBits;
4415     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4416     break;
4417
4418   case 16:
4419     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4420     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4421     if ((SplatBits & ~0xff) == 0) {
4422       // Value = 0x00nn: Op=x, Cmode=100x.
4423       OpCmode = 0x8;
4424       Imm = SplatBits;
4425       break;
4426     }
4427     if ((SplatBits & ~0xff00) == 0) {
4428       // Value = 0xnn00: Op=x, Cmode=101x.
4429       OpCmode = 0xa;
4430       Imm = SplatBits >> 8;
4431       break;
4432     }
4433     return SDValue();
4434
4435   case 32:
4436     // NEON's 32-bit VMOV supports splat values where:
4437     // * only one byte is nonzero, or
4438     // * the least significant byte is 0xff and the second byte is nonzero, or
4439     // * the least significant 2 bytes are 0xff and the third is nonzero.
4440     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4441     if ((SplatBits & ~0xff) == 0) {
4442       // Value = 0x000000nn: Op=x, Cmode=000x.
4443       OpCmode = 0;
4444       Imm = SplatBits;
4445       break;
4446     }
4447     if ((SplatBits & ~0xff00) == 0) {
4448       // Value = 0x0000nn00: Op=x, Cmode=001x.
4449       OpCmode = 0x2;
4450       Imm = SplatBits >> 8;
4451       break;
4452     }
4453     if ((SplatBits & ~0xff0000) == 0) {
4454       // Value = 0x00nn0000: Op=x, Cmode=010x.
4455       OpCmode = 0x4;
4456       Imm = SplatBits >> 16;
4457       break;
4458     }
4459     if ((SplatBits & ~0xff000000) == 0) {
4460       // Value = 0xnn000000: Op=x, Cmode=011x.
4461       OpCmode = 0x6;
4462       Imm = SplatBits >> 24;
4463       break;
4464     }
4465
4466     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4467     if (type == OtherModImm) return SDValue();
4468
4469     if ((SplatBits & ~0xffff) == 0 &&
4470         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4471       // Value = 0x0000nnff: Op=x, Cmode=1100.
4472       OpCmode = 0xc;
4473       Imm = SplatBits >> 8;
4474       break;
4475     }
4476
4477     if ((SplatBits & ~0xffffff) == 0 &&
4478         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4479       // Value = 0x00nnffff: Op=x, Cmode=1101.
4480       OpCmode = 0xd;
4481       Imm = SplatBits >> 16;
4482       break;
4483     }
4484
4485     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4486     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4487     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4488     // and fall through here to test for a valid 64-bit splat.  But, then the
4489     // caller would also need to check and handle the change in size.
4490     return SDValue();
4491
4492   case 64: {
4493     if (type != VMOVModImm)
4494       return SDValue();
4495     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4496     uint64_t BitMask = 0xff;
4497     uint64_t Val = 0;
4498     unsigned ImmMask = 1;
4499     Imm = 0;
4500     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4501       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4502         Val |= BitMask;
4503         Imm |= ImmMask;
4504       } else if ((SplatBits & BitMask) != 0) {
4505         return SDValue();
4506       }
4507       BitMask <<= 8;
4508       ImmMask <<= 1;
4509     }
4510
4511     if (DAG.getTargetLoweringInfo().isBigEndian())
4512       // swap higher and lower 32 bit word
4513       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4514
4515     // Op=1, Cmode=1110.
4516     OpCmode = 0x1e;
4517     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4518     break;
4519   }
4520
4521   default:
4522     llvm_unreachable("unexpected size for isNEONModifiedImm");
4523   }
4524
4525   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4526   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4527 }
4528
4529 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4530                                            const ARMSubtarget *ST) const {
4531   if (!ST->hasVFP3())
4532     return SDValue();
4533
4534   bool IsDouble = Op.getValueType() == MVT::f64;
4535   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4536
4537   // Try splatting with a VMOV.f32...
4538   APFloat FPVal = CFP->getValueAPF();
4539   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4540
4541   if (ImmVal != -1) {
4542     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4543       // We have code in place to select a valid ConstantFP already, no need to
4544       // do any mangling.
4545       return Op;
4546     }
4547
4548     // It's a float and we are trying to use NEON operations where
4549     // possible. Lower it to a splat followed by an extract.
4550     SDLoc DL(Op);
4551     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4552     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4553                                       NewVal);
4554     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4555                        DAG.getConstant(0, MVT::i32));
4556   }
4557
4558   // The rest of our options are NEON only, make sure that's allowed before
4559   // proceeding..
4560   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4561     return SDValue();
4562
4563   EVT VMovVT;
4564   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4565
4566   // It wouldn't really be worth bothering for doubles except for one very
4567   // important value, which does happen to match: 0.0. So make sure we don't do
4568   // anything stupid.
4569   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4570     return SDValue();
4571
4572   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4573   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4574                                      false, VMOVModImm);
4575   if (NewVal != SDValue()) {
4576     SDLoc DL(Op);
4577     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4578                                       NewVal);
4579     if (IsDouble)
4580       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4581
4582     // It's a float: cast and extract a vector element.
4583     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4584                                        VecConstant);
4585     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4586                        DAG.getConstant(0, MVT::i32));
4587   }
4588
4589   // Finally, try a VMVN.i32
4590   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4591                              false, VMVNModImm);
4592   if (NewVal != SDValue()) {
4593     SDLoc DL(Op);
4594     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4595
4596     if (IsDouble)
4597       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4598
4599     // It's a float: cast and extract a vector element.
4600     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4601                                        VecConstant);
4602     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4603                        DAG.getConstant(0, MVT::i32));
4604   }
4605
4606   return SDValue();
4607 }
4608
4609 // check if an VEXT instruction can handle the shuffle mask when the
4610 // vector sources of the shuffle are the same.
4611 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4612   unsigned NumElts = VT.getVectorNumElements();
4613
4614   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4615   if (M[0] < 0)
4616     return false;
4617
4618   Imm = M[0];
4619
4620   // If this is a VEXT shuffle, the immediate value is the index of the first
4621   // element.  The other shuffle indices must be the successive elements after
4622   // the first one.
4623   unsigned ExpectedElt = Imm;
4624   for (unsigned i = 1; i < NumElts; ++i) {
4625     // Increment the expected index.  If it wraps around, just follow it
4626     // back to index zero and keep going.
4627     ++ExpectedElt;
4628     if (ExpectedElt == NumElts)
4629       ExpectedElt = 0;
4630
4631     if (M[i] < 0) continue; // ignore UNDEF indices
4632     if (ExpectedElt != static_cast<unsigned>(M[i]))
4633       return false;
4634   }
4635
4636   return true;
4637 }
4638
4639
4640 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4641                        bool &ReverseVEXT, unsigned &Imm) {
4642   unsigned NumElts = VT.getVectorNumElements();
4643   ReverseVEXT = false;
4644
4645   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4646   if (M[0] < 0)
4647     return false;
4648
4649   Imm = M[0];
4650
4651   // If this is a VEXT shuffle, the immediate value is the index of the first
4652   // element.  The other shuffle indices must be the successive elements after
4653   // the first one.
4654   unsigned ExpectedElt = Imm;
4655   for (unsigned i = 1; i < NumElts; ++i) {
4656     // Increment the expected index.  If it wraps around, it may still be
4657     // a VEXT but the source vectors must be swapped.
4658     ExpectedElt += 1;
4659     if (ExpectedElt == NumElts * 2) {
4660       ExpectedElt = 0;
4661       ReverseVEXT = true;
4662     }
4663
4664     if (M[i] < 0) continue; // ignore UNDEF indices
4665     if (ExpectedElt != static_cast<unsigned>(M[i]))
4666       return false;
4667   }
4668
4669   // Adjust the index value if the source operands will be swapped.
4670   if (ReverseVEXT)
4671     Imm -= NumElts;
4672
4673   return true;
4674 }
4675
4676 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4677 /// instruction with the specified blocksize.  (The order of the elements
4678 /// within each block of the vector is reversed.)
4679 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4680   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4681          "Only possible block sizes for VREV are: 16, 32, 64");
4682
4683   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4684   if (EltSz == 64)
4685     return false;
4686
4687   unsigned NumElts = VT.getVectorNumElements();
4688   unsigned BlockElts = M[0] + 1;
4689   // If the first shuffle index is UNDEF, be optimistic.
4690   if (M[0] < 0)
4691     BlockElts = BlockSize / EltSz;
4692
4693   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4694     return false;
4695
4696   for (unsigned i = 0; i < NumElts; ++i) {
4697     if (M[i] < 0) continue; // ignore UNDEF indices
4698     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4699       return false;
4700   }
4701
4702   return true;
4703 }
4704
4705 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4706   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4707   // range, then 0 is placed into the resulting vector. So pretty much any mask
4708   // of 8 elements can work here.
4709   return VT == MVT::v8i8 && M.size() == 8;
4710 }
4711
4712 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4713   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4714   if (EltSz == 64)
4715     return false;
4716
4717   unsigned NumElts = VT.getVectorNumElements();
4718   WhichResult = (M[0] == 0 ? 0 : 1);
4719   for (unsigned i = 0; i < NumElts; i += 2) {
4720     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4721         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4722       return false;
4723   }
4724   return true;
4725 }
4726
4727 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4728 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4729 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4730 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4731   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4732   if (EltSz == 64)
4733     return false;
4734
4735   unsigned NumElts = VT.getVectorNumElements();
4736   WhichResult = (M[0] == 0 ? 0 : 1);
4737   for (unsigned i = 0; i < NumElts; i += 2) {
4738     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4739         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4740       return false;
4741   }
4742   return true;
4743 }
4744
4745 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4746   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4747   if (EltSz == 64)
4748     return false;
4749
4750   unsigned NumElts = VT.getVectorNumElements();
4751   WhichResult = (M[0] == 0 ? 0 : 1);
4752   for (unsigned i = 0; i != NumElts; ++i) {
4753     if (M[i] < 0) continue; // ignore UNDEF indices
4754     if ((unsigned) M[i] != 2 * i + WhichResult)
4755       return false;
4756   }
4757
4758   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4759   if (VT.is64BitVector() && EltSz == 32)
4760     return false;
4761
4762   return true;
4763 }
4764
4765 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4766 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4767 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4768 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4769   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4770   if (EltSz == 64)
4771     return false;
4772
4773   unsigned Half = VT.getVectorNumElements() / 2;
4774   WhichResult = (M[0] == 0 ? 0 : 1);
4775   for (unsigned j = 0; j != 2; ++j) {
4776     unsigned Idx = WhichResult;
4777     for (unsigned i = 0; i != Half; ++i) {
4778       int MIdx = M[i + j * Half];
4779       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4780         return false;
4781       Idx += 2;
4782     }
4783   }
4784
4785   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4786   if (VT.is64BitVector() && EltSz == 32)
4787     return false;
4788
4789   return true;
4790 }
4791
4792 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4793   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4794   if (EltSz == 64)
4795     return false;
4796
4797   unsigned NumElts = VT.getVectorNumElements();
4798   WhichResult = (M[0] == 0 ? 0 : 1);
4799   unsigned Idx = WhichResult * NumElts / 2;
4800   for (unsigned i = 0; i != NumElts; i += 2) {
4801     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4802         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4803       return false;
4804     Idx += 1;
4805   }
4806
4807   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4808   if (VT.is64BitVector() && EltSz == 32)
4809     return false;
4810
4811   return true;
4812 }
4813
4814 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4815 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4816 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4817 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4818   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4819   if (EltSz == 64)
4820     return false;
4821
4822   unsigned NumElts = VT.getVectorNumElements();
4823   WhichResult = (M[0] == 0 ? 0 : 1);
4824   unsigned Idx = WhichResult * NumElts / 2;
4825   for (unsigned i = 0; i != NumElts; i += 2) {
4826     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4827         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4828       return false;
4829     Idx += 1;
4830   }
4831
4832   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4833   if (VT.is64BitVector() && EltSz == 32)
4834     return false;
4835
4836   return true;
4837 }
4838
4839 /// \return true if this is a reverse operation on an vector.
4840 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4841   unsigned NumElts = VT.getVectorNumElements();
4842   // Make sure the mask has the right size.
4843   if (NumElts != M.size())
4844       return false;
4845
4846   // Look for <15, ..., 3, -1, 1, 0>.
4847   for (unsigned i = 0; i != NumElts; ++i)
4848     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4849       return false;
4850
4851   return true;
4852 }
4853
4854 // If N is an integer constant that can be moved into a register in one
4855 // instruction, return an SDValue of such a constant (will become a MOV
4856 // instruction).  Otherwise return null.
4857 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4858                                      const ARMSubtarget *ST, SDLoc dl) {
4859   uint64_t Val;
4860   if (!isa<ConstantSDNode>(N))
4861     return SDValue();
4862   Val = cast<ConstantSDNode>(N)->getZExtValue();
4863
4864   if (ST->isThumb1Only()) {
4865     if (Val <= 255 || ~Val <= 255)
4866       return DAG.getConstant(Val, MVT::i32);
4867   } else {
4868     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4869       return DAG.getConstant(Val, MVT::i32);
4870   }
4871   return SDValue();
4872 }
4873
4874 // If this is a case we can't handle, return null and let the default
4875 // expansion code take care of it.
4876 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4877                                              const ARMSubtarget *ST) const {
4878   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4879   SDLoc dl(Op);
4880   EVT VT = Op.getValueType();
4881
4882   APInt SplatBits, SplatUndef;
4883   unsigned SplatBitSize;
4884   bool HasAnyUndefs;
4885   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4886     if (SplatBitSize <= 64) {
4887       // Check if an immediate VMOV works.
4888       EVT VmovVT;
4889       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4890                                       SplatUndef.getZExtValue(), SplatBitSize,
4891                                       DAG, VmovVT, VT.is128BitVector(),
4892                                       VMOVModImm);
4893       if (Val.getNode()) {
4894         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4895         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4896       }
4897
4898       // Try an immediate VMVN.
4899       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4900       Val = isNEONModifiedImm(NegatedImm,
4901                                       SplatUndef.getZExtValue(), SplatBitSize,
4902                                       DAG, VmovVT, VT.is128BitVector(),
4903                                       VMVNModImm);
4904       if (Val.getNode()) {
4905         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4906         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4907       }
4908
4909       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4910       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4911         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4912         if (ImmVal != -1) {
4913           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4914           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4915         }
4916       }
4917     }
4918   }
4919
4920   // Scan through the operands to see if only one value is used.
4921   //
4922   // As an optimisation, even if more than one value is used it may be more
4923   // profitable to splat with one value then change some lanes.
4924   //
4925   // Heuristically we decide to do this if the vector has a "dominant" value,
4926   // defined as splatted to more than half of the lanes.
4927   unsigned NumElts = VT.getVectorNumElements();
4928   bool isOnlyLowElement = true;
4929   bool usesOnlyOneValue = true;
4930   bool hasDominantValue = false;
4931   bool isConstant = true;
4932
4933   // Map of the number of times a particular SDValue appears in the
4934   // element list.
4935   DenseMap<SDValue, unsigned> ValueCounts;
4936   SDValue Value;
4937   for (unsigned i = 0; i < NumElts; ++i) {
4938     SDValue V = Op.getOperand(i);
4939     if (V.getOpcode() == ISD::UNDEF)
4940       continue;
4941     if (i > 0)
4942       isOnlyLowElement = false;
4943     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4944       isConstant = false;
4945
4946     ValueCounts.insert(std::make_pair(V, 0));
4947     unsigned &Count = ValueCounts[V];
4948
4949     // Is this value dominant? (takes up more than half of the lanes)
4950     if (++Count > (NumElts / 2)) {
4951       hasDominantValue = true;
4952       Value = V;
4953     }
4954   }
4955   if (ValueCounts.size() != 1)
4956     usesOnlyOneValue = false;
4957   if (!Value.getNode() && ValueCounts.size() > 0)
4958     Value = ValueCounts.begin()->first;
4959
4960   if (ValueCounts.size() == 0)
4961     return DAG.getUNDEF(VT);
4962
4963   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
4964   // Keep going if we are hitting this case.
4965   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
4966     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4967
4968   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4969
4970   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4971   // i32 and try again.
4972   if (hasDominantValue && EltSize <= 32) {
4973     if (!isConstant) {
4974       SDValue N;
4975
4976       // If we are VDUPing a value that comes directly from a vector, that will
4977       // cause an unnecessary move to and from a GPR, where instead we could
4978       // just use VDUPLANE. We can only do this if the lane being extracted
4979       // is at a constant index, as the VDUP from lane instructions only have
4980       // constant-index forms.
4981       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4982           isa<ConstantSDNode>(Value->getOperand(1))) {
4983         // We need to create a new undef vector to use for the VDUPLANE if the
4984         // size of the vector from which we get the value is different than the
4985         // size of the vector that we need to create. We will insert the element
4986         // such that the register coalescer will remove unnecessary copies.
4987         if (VT != Value->getOperand(0).getValueType()) {
4988           ConstantSDNode *constIndex;
4989           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4990           assert(constIndex && "The index is not a constant!");
4991           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4992                              VT.getVectorNumElements();
4993           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4994                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4995                         Value, DAG.getConstant(index, MVT::i32)),
4996                            DAG.getConstant(index, MVT::i32));
4997         } else
4998           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4999                         Value->getOperand(0), Value->getOperand(1));
5000       } else
5001         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5002
5003       if (!usesOnlyOneValue) {
5004         // The dominant value was splatted as 'N', but we now have to insert
5005         // all differing elements.
5006         for (unsigned I = 0; I < NumElts; ++I) {
5007           if (Op.getOperand(I) == Value)
5008             continue;
5009           SmallVector<SDValue, 3> Ops;
5010           Ops.push_back(N);
5011           Ops.push_back(Op.getOperand(I));
5012           Ops.push_back(DAG.getConstant(I, MVT::i32));
5013           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5014         }
5015       }
5016       return N;
5017     }
5018     if (VT.getVectorElementType().isFloatingPoint()) {
5019       SmallVector<SDValue, 8> Ops;
5020       for (unsigned i = 0; i < NumElts; ++i)
5021         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5022                                   Op.getOperand(i)));
5023       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5024       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5025       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5026       if (Val.getNode())
5027         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5028     }
5029     if (usesOnlyOneValue) {
5030       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5031       if (isConstant && Val.getNode())
5032         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5033     }
5034   }
5035
5036   // If all elements are constants and the case above didn't get hit, fall back
5037   // to the default expansion, which will generate a load from the constant
5038   // pool.
5039   if (isConstant)
5040     return SDValue();
5041
5042   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5043   if (NumElts >= 4) {
5044     SDValue shuffle = ReconstructShuffle(Op, DAG);
5045     if (shuffle != SDValue())
5046       return shuffle;
5047   }
5048
5049   // Vectors with 32- or 64-bit elements can be built by directly assigning
5050   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5051   // will be legalized.
5052   if (EltSize >= 32) {
5053     // Do the expansion with floating-point types, since that is what the VFP
5054     // registers are defined to use, and since i64 is not legal.
5055     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5056     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5057     SmallVector<SDValue, 8> Ops;
5058     for (unsigned i = 0; i < NumElts; ++i)
5059       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5060     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5061     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5062   }
5063
5064   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5065   // know the default expansion would otherwise fall back on something even
5066   // worse. For a vector with one or two non-undef values, that's
5067   // scalar_to_vector for the elements followed by a shuffle (provided the
5068   // shuffle is valid for the target) and materialization element by element
5069   // on the stack followed by a load for everything else.
5070   if (!isConstant && !usesOnlyOneValue) {
5071     SDValue Vec = DAG.getUNDEF(VT);
5072     for (unsigned i = 0 ; i < NumElts; ++i) {
5073       SDValue V = Op.getOperand(i);
5074       if (V.getOpcode() == ISD::UNDEF)
5075         continue;
5076       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5077       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5078     }
5079     return Vec;
5080   }
5081
5082   return SDValue();
5083 }
5084
5085 // Gather data to see if the operation can be modelled as a
5086 // shuffle in combination with VEXTs.
5087 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5088                                               SelectionDAG &DAG) const {
5089   SDLoc dl(Op);
5090   EVT VT = Op.getValueType();
5091   unsigned NumElts = VT.getVectorNumElements();
5092
5093   SmallVector<SDValue, 2> SourceVecs;
5094   SmallVector<unsigned, 2> MinElts;
5095   SmallVector<unsigned, 2> MaxElts;
5096
5097   for (unsigned i = 0; i < NumElts; ++i) {
5098     SDValue V = Op.getOperand(i);
5099     if (V.getOpcode() == ISD::UNDEF)
5100       continue;
5101     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5102       // A shuffle can only come from building a vector from various
5103       // elements of other vectors.
5104       return SDValue();
5105     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5106                VT.getVectorElementType()) {
5107       // This code doesn't know how to handle shuffles where the vector
5108       // element types do not match (this happens because type legalization
5109       // promotes the return type of EXTRACT_VECTOR_ELT).
5110       // FIXME: It might be appropriate to extend this code to handle
5111       // mismatched types.
5112       return SDValue();
5113     }
5114
5115     // Record this extraction against the appropriate vector if possible...
5116     SDValue SourceVec = V.getOperand(0);
5117     // If the element number isn't a constant, we can't effectively
5118     // analyze what's going on.
5119     if (!isa<ConstantSDNode>(V.getOperand(1)))
5120       return SDValue();
5121     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5122     bool FoundSource = false;
5123     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5124       if (SourceVecs[j] == SourceVec) {
5125         if (MinElts[j] > EltNo)
5126           MinElts[j] = EltNo;
5127         if (MaxElts[j] < EltNo)
5128           MaxElts[j] = EltNo;
5129         FoundSource = true;
5130         break;
5131       }
5132     }
5133
5134     // Or record a new source if not...
5135     if (!FoundSource) {
5136       SourceVecs.push_back(SourceVec);
5137       MinElts.push_back(EltNo);
5138       MaxElts.push_back(EltNo);
5139     }
5140   }
5141
5142   // Currently only do something sane when at most two source vectors
5143   // involved.
5144   if (SourceVecs.size() > 2)
5145     return SDValue();
5146
5147   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5148   int VEXTOffsets[2] = {0, 0};
5149
5150   // This loop extracts the usage patterns of the source vectors
5151   // and prepares appropriate SDValues for a shuffle if possible.
5152   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5153     if (SourceVecs[i].getValueType() == VT) {
5154       // No VEXT necessary
5155       ShuffleSrcs[i] = SourceVecs[i];
5156       VEXTOffsets[i] = 0;
5157       continue;
5158     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5159       // It probably isn't worth padding out a smaller vector just to
5160       // break it down again in a shuffle.
5161       return SDValue();
5162     }
5163
5164     // Since only 64-bit and 128-bit vectors are legal on ARM and
5165     // we've eliminated the other cases...
5166     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5167            "unexpected vector sizes in ReconstructShuffle");
5168
5169     if (MaxElts[i] - MinElts[i] >= NumElts) {
5170       // Span too large for a VEXT to cope
5171       return SDValue();
5172     }
5173
5174     if (MinElts[i] >= NumElts) {
5175       // The extraction can just take the second half
5176       VEXTOffsets[i] = NumElts;
5177       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5178                                    SourceVecs[i],
5179                                    DAG.getIntPtrConstant(NumElts));
5180     } else if (MaxElts[i] < NumElts) {
5181       // The extraction can just take the first half
5182       VEXTOffsets[i] = 0;
5183       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5184                                    SourceVecs[i],
5185                                    DAG.getIntPtrConstant(0));
5186     } else {
5187       // An actual VEXT is needed
5188       VEXTOffsets[i] = MinElts[i];
5189       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5190                                      SourceVecs[i],
5191                                      DAG.getIntPtrConstant(0));
5192       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5193                                      SourceVecs[i],
5194                                      DAG.getIntPtrConstant(NumElts));
5195       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5196                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5197     }
5198   }
5199
5200   SmallVector<int, 8> Mask;
5201
5202   for (unsigned i = 0; i < NumElts; ++i) {
5203     SDValue Entry = Op.getOperand(i);
5204     if (Entry.getOpcode() == ISD::UNDEF) {
5205       Mask.push_back(-1);
5206       continue;
5207     }
5208
5209     SDValue ExtractVec = Entry.getOperand(0);
5210     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5211                                           .getOperand(1))->getSExtValue();
5212     if (ExtractVec == SourceVecs[0]) {
5213       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5214     } else {
5215       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5216     }
5217   }
5218
5219   // Final check before we try to produce nonsense...
5220   if (isShuffleMaskLegal(Mask, VT))
5221     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5222                                 &Mask[0]);
5223
5224   return SDValue();
5225 }
5226
5227 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5228 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5229 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5230 /// are assumed to be legal.
5231 bool
5232 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5233                                       EVT VT) const {
5234   if (VT.getVectorNumElements() == 4 &&
5235       (VT.is128BitVector() || VT.is64BitVector())) {
5236     unsigned PFIndexes[4];
5237     for (unsigned i = 0; i != 4; ++i) {
5238       if (M[i] < 0)
5239         PFIndexes[i] = 8;
5240       else
5241         PFIndexes[i] = M[i];
5242     }
5243
5244     // Compute the index in the perfect shuffle table.
5245     unsigned PFTableIndex =
5246       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5247     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5248     unsigned Cost = (PFEntry >> 30);
5249
5250     if (Cost <= 4)
5251       return true;
5252   }
5253
5254   bool ReverseVEXT;
5255   unsigned Imm, WhichResult;
5256
5257   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5258   return (EltSize >= 32 ||
5259           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5260           isVREVMask(M, VT, 64) ||
5261           isVREVMask(M, VT, 32) ||
5262           isVREVMask(M, VT, 16) ||
5263           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5264           isVTBLMask(M, VT) ||
5265           isVTRNMask(M, VT, WhichResult) ||
5266           isVUZPMask(M, VT, WhichResult) ||
5267           isVZIPMask(M, VT, WhichResult) ||
5268           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5269           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5270           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5271           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5272 }
5273
5274 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5275 /// the specified operations to build the shuffle.
5276 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5277                                       SDValue RHS, SelectionDAG &DAG,
5278                                       SDLoc dl) {
5279   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5280   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5281   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5282
5283   enum {
5284     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5285     OP_VREV,
5286     OP_VDUP0,
5287     OP_VDUP1,
5288     OP_VDUP2,
5289     OP_VDUP3,
5290     OP_VEXT1,
5291     OP_VEXT2,
5292     OP_VEXT3,
5293     OP_VUZPL, // VUZP, left result
5294     OP_VUZPR, // VUZP, right result
5295     OP_VZIPL, // VZIP, left result
5296     OP_VZIPR, // VZIP, right result
5297     OP_VTRNL, // VTRN, left result
5298     OP_VTRNR  // VTRN, right result
5299   };
5300
5301   if (OpNum == OP_COPY) {
5302     if (LHSID == (1*9+2)*9+3) return LHS;
5303     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5304     return RHS;
5305   }
5306
5307   SDValue OpLHS, OpRHS;
5308   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5309   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5310   EVT VT = OpLHS.getValueType();
5311
5312   switch (OpNum) {
5313   default: llvm_unreachable("Unknown shuffle opcode!");
5314   case OP_VREV:
5315     // VREV divides the vector in half and swaps within the half.
5316     if (VT.getVectorElementType() == MVT::i32 ||
5317         VT.getVectorElementType() == MVT::f32)
5318       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5319     // vrev <4 x i16> -> VREV32
5320     if (VT.getVectorElementType() == MVT::i16)
5321       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5322     // vrev <4 x i8> -> VREV16
5323     assert(VT.getVectorElementType() == MVT::i8);
5324     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5325   case OP_VDUP0:
5326   case OP_VDUP1:
5327   case OP_VDUP2:
5328   case OP_VDUP3:
5329     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5330                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5331   case OP_VEXT1:
5332   case OP_VEXT2:
5333   case OP_VEXT3:
5334     return DAG.getNode(ARMISD::VEXT, dl, VT,
5335                        OpLHS, OpRHS,
5336                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5337   case OP_VUZPL:
5338   case OP_VUZPR:
5339     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5340                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5341   case OP_VZIPL:
5342   case OP_VZIPR:
5343     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5344                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5345   case OP_VTRNL:
5346   case OP_VTRNR:
5347     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5348                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5349   }
5350 }
5351
5352 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5353                                        ArrayRef<int> ShuffleMask,
5354                                        SelectionDAG &DAG) {
5355   // Check to see if we can use the VTBL instruction.
5356   SDValue V1 = Op.getOperand(0);
5357   SDValue V2 = Op.getOperand(1);
5358   SDLoc DL(Op);
5359
5360   SmallVector<SDValue, 8> VTBLMask;
5361   for (ArrayRef<int>::iterator
5362          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5363     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5364
5365   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5366     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5367                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5368
5369   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5370                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5371 }
5372
5373 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5374                                                       SelectionDAG &DAG) {
5375   SDLoc DL(Op);
5376   SDValue OpLHS = Op.getOperand(0);
5377   EVT VT = OpLHS.getValueType();
5378
5379   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5380          "Expect an v8i16/v16i8 type");
5381   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5382   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5383   // extract the first 8 bytes into the top double word and the last 8 bytes
5384   // into the bottom double word. The v8i16 case is similar.
5385   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5386   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5387                      DAG.getConstant(ExtractNum, MVT::i32));
5388 }
5389
5390 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5391   SDValue V1 = Op.getOperand(0);
5392   SDValue V2 = Op.getOperand(1);
5393   SDLoc dl(Op);
5394   EVT VT = Op.getValueType();
5395   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5396
5397   // Convert shuffles that are directly supported on NEON to target-specific
5398   // DAG nodes, instead of keeping them as shuffles and matching them again
5399   // during code selection.  This is more efficient and avoids the possibility
5400   // of inconsistencies between legalization and selection.
5401   // FIXME: floating-point vectors should be canonicalized to integer vectors
5402   // of the same time so that they get CSEd properly.
5403   ArrayRef<int> ShuffleMask = SVN->getMask();
5404
5405   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5406   if (EltSize <= 32) {
5407     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5408       int Lane = SVN->getSplatIndex();
5409       // If this is undef splat, generate it via "just" vdup, if possible.
5410       if (Lane == -1) Lane = 0;
5411
5412       // Test if V1 is a SCALAR_TO_VECTOR.
5413       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5414         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5415       }
5416       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5417       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5418       // reaches it).
5419       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5420           !isa<ConstantSDNode>(V1.getOperand(0))) {
5421         bool IsScalarToVector = true;
5422         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5423           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5424             IsScalarToVector = false;
5425             break;
5426           }
5427         if (IsScalarToVector)
5428           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5429       }
5430       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5431                          DAG.getConstant(Lane, MVT::i32));
5432     }
5433
5434     bool ReverseVEXT;
5435     unsigned Imm;
5436     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5437       if (ReverseVEXT)
5438         std::swap(V1, V2);
5439       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5440                          DAG.getConstant(Imm, MVT::i32));
5441     }
5442
5443     if (isVREVMask(ShuffleMask, VT, 64))
5444       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5445     if (isVREVMask(ShuffleMask, VT, 32))
5446       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5447     if (isVREVMask(ShuffleMask, VT, 16))
5448       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5449
5450     if (V2->getOpcode() == ISD::UNDEF &&
5451         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5452       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5453                          DAG.getConstant(Imm, MVT::i32));
5454     }
5455
5456     // Check for Neon shuffles that modify both input vectors in place.
5457     // If both results are used, i.e., if there are two shuffles with the same
5458     // source operands and with masks corresponding to both results of one of
5459     // these operations, DAG memoization will ensure that a single node is
5460     // used for both shuffles.
5461     unsigned WhichResult;
5462     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5463       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5464                          V1, V2).getValue(WhichResult);
5465     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5466       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5467                          V1, V2).getValue(WhichResult);
5468     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5469       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5470                          V1, V2).getValue(WhichResult);
5471
5472     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5473       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5474                          V1, V1).getValue(WhichResult);
5475     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5476       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5477                          V1, V1).getValue(WhichResult);
5478     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5479       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5480                          V1, V1).getValue(WhichResult);
5481   }
5482
5483   // If the shuffle is not directly supported and it has 4 elements, use
5484   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5485   unsigned NumElts = VT.getVectorNumElements();
5486   if (NumElts == 4) {
5487     unsigned PFIndexes[4];
5488     for (unsigned i = 0; i != 4; ++i) {
5489       if (ShuffleMask[i] < 0)
5490         PFIndexes[i] = 8;
5491       else
5492         PFIndexes[i] = ShuffleMask[i];
5493     }
5494
5495     // Compute the index in the perfect shuffle table.
5496     unsigned PFTableIndex =
5497       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5498     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5499     unsigned Cost = (PFEntry >> 30);
5500
5501     if (Cost <= 4)
5502       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5503   }
5504
5505   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5506   if (EltSize >= 32) {
5507     // Do the expansion with floating-point types, since that is what the VFP
5508     // registers are defined to use, and since i64 is not legal.
5509     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5510     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5511     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5512     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5513     SmallVector<SDValue, 8> Ops;
5514     for (unsigned i = 0; i < NumElts; ++i) {
5515       if (ShuffleMask[i] < 0)
5516         Ops.push_back(DAG.getUNDEF(EltVT));
5517       else
5518         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5519                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5520                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5521                                                   MVT::i32)));
5522     }
5523     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5524     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5525   }
5526
5527   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5528     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5529
5530   if (VT == MVT::v8i8) {
5531     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5532     if (NewOp.getNode())
5533       return NewOp;
5534   }
5535
5536   return SDValue();
5537 }
5538
5539 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5540   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5541   SDValue Lane = Op.getOperand(2);
5542   if (!isa<ConstantSDNode>(Lane))
5543     return SDValue();
5544
5545   return Op;
5546 }
5547
5548 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5549   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5550   SDValue Lane = Op.getOperand(1);
5551   if (!isa<ConstantSDNode>(Lane))
5552     return SDValue();
5553
5554   SDValue Vec = Op.getOperand(0);
5555   if (Op.getValueType() == MVT::i32 &&
5556       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5557     SDLoc dl(Op);
5558     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5559   }
5560
5561   return Op;
5562 }
5563
5564 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5565   // The only time a CONCAT_VECTORS operation can have legal types is when
5566   // two 64-bit vectors are concatenated to a 128-bit vector.
5567   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5568          "unexpected CONCAT_VECTORS");
5569   SDLoc dl(Op);
5570   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5571   SDValue Op0 = Op.getOperand(0);
5572   SDValue Op1 = Op.getOperand(1);
5573   if (Op0.getOpcode() != ISD::UNDEF)
5574     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5575                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5576                       DAG.getIntPtrConstant(0));
5577   if (Op1.getOpcode() != ISD::UNDEF)
5578     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5579                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5580                       DAG.getIntPtrConstant(1));
5581   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5582 }
5583
5584 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5585 /// element has been zero/sign-extended, depending on the isSigned parameter,
5586 /// from an integer type half its size.
5587 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5588                                    bool isSigned) {
5589   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5590   EVT VT = N->getValueType(0);
5591   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5592     SDNode *BVN = N->getOperand(0).getNode();
5593     if (BVN->getValueType(0) != MVT::v4i32 ||
5594         BVN->getOpcode() != ISD::BUILD_VECTOR)
5595       return false;
5596     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5597     unsigned HiElt = 1 - LoElt;
5598     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5599     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5600     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5601     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5602     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5603       return false;
5604     if (isSigned) {
5605       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5606           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5607         return true;
5608     } else {
5609       if (Hi0->isNullValue() && Hi1->isNullValue())
5610         return true;
5611     }
5612     return false;
5613   }
5614
5615   if (N->getOpcode() != ISD::BUILD_VECTOR)
5616     return false;
5617
5618   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5619     SDNode *Elt = N->getOperand(i).getNode();
5620     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5621       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5622       unsigned HalfSize = EltSize / 2;
5623       if (isSigned) {
5624         if (!isIntN(HalfSize, C->getSExtValue()))
5625           return false;
5626       } else {
5627         if (!isUIntN(HalfSize, C->getZExtValue()))
5628           return false;
5629       }
5630       continue;
5631     }
5632     return false;
5633   }
5634
5635   return true;
5636 }
5637
5638 /// isSignExtended - Check if a node is a vector value that is sign-extended
5639 /// or a constant BUILD_VECTOR with sign-extended elements.
5640 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5641   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5642     return true;
5643   if (isExtendedBUILD_VECTOR(N, DAG, true))
5644     return true;
5645   return false;
5646 }
5647
5648 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5649 /// or a constant BUILD_VECTOR with zero-extended elements.
5650 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5651   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5652     return true;
5653   if (isExtendedBUILD_VECTOR(N, DAG, false))
5654     return true;
5655   return false;
5656 }
5657
5658 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5659   if (OrigVT.getSizeInBits() >= 64)
5660     return OrigVT;
5661
5662   assert(OrigVT.isSimple() && "Expecting a simple value type");
5663
5664   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5665   switch (OrigSimpleTy) {
5666   default: llvm_unreachable("Unexpected Vector Type");
5667   case MVT::v2i8:
5668   case MVT::v2i16:
5669      return MVT::v2i32;
5670   case MVT::v4i8:
5671     return  MVT::v4i16;
5672   }
5673 }
5674
5675 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5676 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5677 /// We insert the required extension here to get the vector to fill a D register.
5678 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5679                                             const EVT &OrigTy,
5680                                             const EVT &ExtTy,
5681                                             unsigned ExtOpcode) {
5682   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5683   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5684   // 64-bits we need to insert a new extension so that it will be 64-bits.
5685   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5686   if (OrigTy.getSizeInBits() >= 64)
5687     return N;
5688
5689   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5690   EVT NewVT = getExtensionTo64Bits(OrigTy);
5691
5692   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5693 }
5694
5695 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5696 /// does not do any sign/zero extension. If the original vector is less
5697 /// than 64 bits, an appropriate extension will be added after the load to
5698 /// reach a total size of 64 bits. We have to add the extension separately
5699 /// because ARM does not have a sign/zero extending load for vectors.
5700 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5701   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5702
5703   // The load already has the right type.
5704   if (ExtendedTy == LD->getMemoryVT())
5705     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5706                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5707                 LD->isNonTemporal(), LD->isInvariant(),
5708                 LD->getAlignment());
5709
5710   // We need to create a zextload/sextload. We cannot just create a load
5711   // followed by a zext/zext node because LowerMUL is also run during normal
5712   // operation legalization where we can't create illegal types.
5713   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5714                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5715                         LD->getMemoryVT(), LD->isVolatile(),
5716                         LD->isNonTemporal(), LD->getAlignment());
5717 }
5718
5719 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5720 /// extending load, or BUILD_VECTOR with extended elements, return the
5721 /// unextended value. The unextended vector should be 64 bits so that it can
5722 /// be used as an operand to a VMULL instruction. If the original vector size
5723 /// before extension is less than 64 bits we add a an extension to resize
5724 /// the vector to 64 bits.
5725 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5726   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5727     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5728                                         N->getOperand(0)->getValueType(0),
5729                                         N->getValueType(0),
5730                                         N->getOpcode());
5731
5732   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5733     return SkipLoadExtensionForVMULL(LD, DAG);
5734
5735   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5736   // have been legalized as a BITCAST from v4i32.
5737   if (N->getOpcode() == ISD::BITCAST) {
5738     SDNode *BVN = N->getOperand(0).getNode();
5739     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5740            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5741     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5742     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5743                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5744   }
5745   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5746   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5747   EVT VT = N->getValueType(0);
5748   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5749   unsigned NumElts = VT.getVectorNumElements();
5750   MVT TruncVT = MVT::getIntegerVT(EltSize);
5751   SmallVector<SDValue, 8> Ops;
5752   for (unsigned i = 0; i != NumElts; ++i) {
5753     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5754     const APInt &CInt = C->getAPIntValue();
5755     // Element types smaller than 32 bits are not legal, so use i32 elements.
5756     // The values are implicitly truncated so sext vs. zext doesn't matter.
5757     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5758   }
5759   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5760                      MVT::getVectorVT(TruncVT, NumElts), Ops);
5761 }
5762
5763 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5764   unsigned Opcode = N->getOpcode();
5765   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5766     SDNode *N0 = N->getOperand(0).getNode();
5767     SDNode *N1 = N->getOperand(1).getNode();
5768     return N0->hasOneUse() && N1->hasOneUse() &&
5769       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5770   }
5771   return false;
5772 }
5773
5774 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5775   unsigned Opcode = N->getOpcode();
5776   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5777     SDNode *N0 = N->getOperand(0).getNode();
5778     SDNode *N1 = N->getOperand(1).getNode();
5779     return N0->hasOneUse() && N1->hasOneUse() &&
5780       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5781   }
5782   return false;
5783 }
5784
5785 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5786   // Multiplications are only custom-lowered for 128-bit vectors so that
5787   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5788   EVT VT = Op.getValueType();
5789   assert(VT.is128BitVector() && VT.isInteger() &&
5790          "unexpected type for custom-lowering ISD::MUL");
5791   SDNode *N0 = Op.getOperand(0).getNode();
5792   SDNode *N1 = Op.getOperand(1).getNode();
5793   unsigned NewOpc = 0;
5794   bool isMLA = false;
5795   bool isN0SExt = isSignExtended(N0, DAG);
5796   bool isN1SExt = isSignExtended(N1, DAG);
5797   if (isN0SExt && isN1SExt)
5798     NewOpc = ARMISD::VMULLs;
5799   else {
5800     bool isN0ZExt = isZeroExtended(N0, DAG);
5801     bool isN1ZExt = isZeroExtended(N1, DAG);
5802     if (isN0ZExt && isN1ZExt)
5803       NewOpc = ARMISD::VMULLu;
5804     else if (isN1SExt || isN1ZExt) {
5805       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5806       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5807       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5808         NewOpc = ARMISD::VMULLs;
5809         isMLA = true;
5810       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5811         NewOpc = ARMISD::VMULLu;
5812         isMLA = true;
5813       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5814         std::swap(N0, N1);
5815         NewOpc = ARMISD::VMULLu;
5816         isMLA = true;
5817       }
5818     }
5819
5820     if (!NewOpc) {
5821       if (VT == MVT::v2i64)
5822         // Fall through to expand this.  It is not legal.
5823         return SDValue();
5824       else
5825         // Other vector multiplications are legal.
5826         return Op;
5827     }
5828   }
5829
5830   // Legalize to a VMULL instruction.
5831   SDLoc DL(Op);
5832   SDValue Op0;
5833   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5834   if (!isMLA) {
5835     Op0 = SkipExtensionForVMULL(N0, DAG);
5836     assert(Op0.getValueType().is64BitVector() &&
5837            Op1.getValueType().is64BitVector() &&
5838            "unexpected types for extended operands to VMULL");
5839     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5840   }
5841
5842   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5843   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5844   //   vmull q0, d4, d6
5845   //   vmlal q0, d5, d6
5846   // is faster than
5847   //   vaddl q0, d4, d5
5848   //   vmovl q1, d6
5849   //   vmul  q0, q0, q1
5850   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5851   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5852   EVT Op1VT = Op1.getValueType();
5853   return DAG.getNode(N0->getOpcode(), DL, VT,
5854                      DAG.getNode(NewOpc, DL, VT,
5855                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5856                      DAG.getNode(NewOpc, DL, VT,
5857                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5858 }
5859
5860 static SDValue
5861 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5862   // Convert to float
5863   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5864   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5865   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5866   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5867   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5868   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5869   // Get reciprocal estimate.
5870   // float4 recip = vrecpeq_f32(yf);
5871   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5872                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5873   // Because char has a smaller range than uchar, we can actually get away
5874   // without any newton steps.  This requires that we use a weird bias
5875   // of 0xb000, however (again, this has been exhaustively tested).
5876   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5877   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5878   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5879   Y = DAG.getConstant(0xb000, MVT::i32);
5880   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5881   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5882   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5883   // Convert back to short.
5884   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5885   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5886   return X;
5887 }
5888
5889 static SDValue
5890 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5891   SDValue N2;
5892   // Convert to float.
5893   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5894   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5895   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5896   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5897   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5898   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5899
5900   // Use reciprocal estimate and one refinement step.
5901   // float4 recip = vrecpeq_f32(yf);
5902   // recip *= vrecpsq_f32(yf, recip);
5903   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5904                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5905   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5906                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5907                    N1, N2);
5908   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5909   // Because short has a smaller range than ushort, we can actually get away
5910   // with only a single newton step.  This requires that we use a weird bias
5911   // of 89, however (again, this has been exhaustively tested).
5912   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5913   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5914   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5915   N1 = DAG.getConstant(0x89, MVT::i32);
5916   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5917   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5918   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5919   // Convert back to integer and return.
5920   // return vmovn_s32(vcvt_s32_f32(result));
5921   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5922   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5923   return N0;
5924 }
5925
5926 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5927   EVT VT = Op.getValueType();
5928   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5929          "unexpected type for custom-lowering ISD::SDIV");
5930
5931   SDLoc dl(Op);
5932   SDValue N0 = Op.getOperand(0);
5933   SDValue N1 = Op.getOperand(1);
5934   SDValue N2, N3;
5935
5936   if (VT == MVT::v8i8) {
5937     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5938     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5939
5940     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5941                      DAG.getIntPtrConstant(4));
5942     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5943                      DAG.getIntPtrConstant(4));
5944     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5945                      DAG.getIntPtrConstant(0));
5946     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5947                      DAG.getIntPtrConstant(0));
5948
5949     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5950     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5951
5952     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5953     N0 = LowerCONCAT_VECTORS(N0, DAG);
5954
5955     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5956     return N0;
5957   }
5958   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5959 }
5960
5961 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5962   EVT VT = Op.getValueType();
5963   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5964          "unexpected type for custom-lowering ISD::UDIV");
5965
5966   SDLoc dl(Op);
5967   SDValue N0 = Op.getOperand(0);
5968   SDValue N1 = Op.getOperand(1);
5969   SDValue N2, N3;
5970
5971   if (VT == MVT::v8i8) {
5972     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5973     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5974
5975     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5976                      DAG.getIntPtrConstant(4));
5977     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5978                      DAG.getIntPtrConstant(4));
5979     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5980                      DAG.getIntPtrConstant(0));
5981     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5982                      DAG.getIntPtrConstant(0));
5983
5984     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5985     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5986
5987     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5988     N0 = LowerCONCAT_VECTORS(N0, DAG);
5989
5990     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5991                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5992                      N0);
5993     return N0;
5994   }
5995
5996   // v4i16 sdiv ... Convert to float.
5997   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5998   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5999   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6000   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6001   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6002   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6003
6004   // Use reciprocal estimate and two refinement steps.
6005   // float4 recip = vrecpeq_f32(yf);
6006   // recip *= vrecpsq_f32(yf, recip);
6007   // recip *= vrecpsq_f32(yf, recip);
6008   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6009                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6010   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6011                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6012                    BN1, N2);
6013   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6014   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6015                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6016                    BN1, N2);
6017   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6018   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6019   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6020   // and that it will never cause us to return an answer too large).
6021   // float4 result = as_float4(as_int4(xf*recip) + 2);
6022   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6023   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6024   N1 = DAG.getConstant(2, MVT::i32);
6025   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6026   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6027   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6028   // Convert back to integer and return.
6029   // return vmovn_u32(vcvt_s32_f32(result));
6030   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6031   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6032   return N0;
6033 }
6034
6035 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6036   EVT VT = Op.getNode()->getValueType(0);
6037   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6038
6039   unsigned Opc;
6040   bool ExtraOp = false;
6041   switch (Op.getOpcode()) {
6042   default: llvm_unreachable("Invalid code");
6043   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6044   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6045   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6046   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6047   }
6048
6049   if (!ExtraOp)
6050     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6051                        Op.getOperand(1));
6052   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6053                      Op.getOperand(1), Op.getOperand(2));
6054 }
6055
6056 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6057   assert(Subtarget->isTargetDarwin());
6058
6059   // For iOS, we want to call an alternative entry point: __sincos_stret,
6060   // return values are passed via sret.
6061   SDLoc dl(Op);
6062   SDValue Arg = Op.getOperand(0);
6063   EVT ArgVT = Arg.getValueType();
6064   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6065
6066   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6067   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6068
6069   // Pair of floats / doubles used to pass the result.
6070   StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
6071
6072   // Create stack object for sret.
6073   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6074   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6075   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6076   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6077
6078   ArgListTy Args;
6079   ArgListEntry Entry;
6080
6081   Entry.Node = SRet;
6082   Entry.Ty = RetTy->getPointerTo();
6083   Entry.isSExt = false;
6084   Entry.isZExt = false;
6085   Entry.isSRet = true;
6086   Args.push_back(Entry);
6087
6088   Entry.Node = Arg;
6089   Entry.Ty = ArgTy;
6090   Entry.isSExt = false;
6091   Entry.isZExt = false;
6092   Args.push_back(Entry);
6093
6094   const char *LibcallName  = (ArgVT == MVT::f64)
6095   ? "__sincos_stret" : "__sincosf_stret";
6096   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6097
6098   TargetLowering::CallLoweringInfo CLI(DAG);
6099   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6100     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6101                std::move(Args), 0)
6102     .setDiscardResult();
6103
6104   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6105
6106   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6107                                 MachinePointerInfo(), false, false, false, 0);
6108
6109   // Address of cos field.
6110   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6111                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6112   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6113                                 MachinePointerInfo(), false, false, false, 0);
6114
6115   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6116   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6117                      LoadSin.getValue(0), LoadCos.getValue(0));
6118 }
6119
6120 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6121   // Monotonic load/store is legal for all targets
6122   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6123     return Op;
6124
6125   // Acquire/Release load/store is not legal for targets without a
6126   // dmb or equivalent available.
6127   return SDValue();
6128 }
6129
6130 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6131                                     SmallVectorImpl<SDValue> &Results,
6132                                     SelectionDAG &DAG,
6133                                     const ARMSubtarget *Subtarget) {
6134   SDLoc DL(N);
6135   SDValue Cycles32, OutChain;
6136
6137   if (Subtarget->hasPerfMon()) {
6138     // Under Power Management extensions, the cycle-count is:
6139     //    mrc p15, #0, <Rt>, c9, c13, #0
6140     SDValue Ops[] = { N->getOperand(0), // Chain
6141                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6142                       DAG.getConstant(15, MVT::i32),
6143                       DAG.getConstant(0, MVT::i32),
6144                       DAG.getConstant(9, MVT::i32),
6145                       DAG.getConstant(13, MVT::i32),
6146                       DAG.getConstant(0, MVT::i32)
6147     };
6148
6149     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6150                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6151     OutChain = Cycles32.getValue(1);
6152   } else {
6153     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6154     // there are older ARM CPUs that have implementation-specific ways of
6155     // obtaining this information (FIXME!).
6156     Cycles32 = DAG.getConstant(0, MVT::i32);
6157     OutChain = DAG.getEntryNode();
6158   }
6159
6160
6161   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6162                                  Cycles32, DAG.getConstant(0, MVT::i32));
6163   Results.push_back(Cycles64);
6164   Results.push_back(OutChain);
6165 }
6166
6167 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6168   switch (Op.getOpcode()) {
6169   default: llvm_unreachable("Don't know how to custom lower this!");
6170   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6171   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6172   case ISD::GlobalAddress:
6173     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6174     default: llvm_unreachable("unknown object format");
6175     case Triple::COFF:
6176       return LowerGlobalAddressWindows(Op, DAG);
6177     case Triple::ELF:
6178       return LowerGlobalAddressELF(Op, DAG);
6179     case Triple::MachO:
6180       return LowerGlobalAddressDarwin(Op, DAG);
6181     }
6182   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6183   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6184   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6185   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6186   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6187   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6188   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6189   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6190   case ISD::SINT_TO_FP:
6191   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6192   case ISD::FP_TO_SINT:
6193   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6194   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6195   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6196   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6197   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6198   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6199   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6200   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6201                                                                Subtarget);
6202   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6203   case ISD::SHL:
6204   case ISD::SRL:
6205   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6206   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6207   case ISD::SRL_PARTS:
6208   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6209   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6210   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6211   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6212   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6213   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6214   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6215   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6216   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6217   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6218   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6219   case ISD::MUL:           return LowerMUL(Op, DAG);
6220   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6221   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6222   case ISD::ADDC:
6223   case ISD::ADDE:
6224   case ISD::SUBC:
6225   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6226   case ISD::SADDO:
6227   case ISD::UADDO:
6228   case ISD::SSUBO:
6229   case ISD::USUBO:
6230     return LowerXALUO(Op, DAG);
6231   case ISD::ATOMIC_LOAD:
6232   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6233   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6234   case ISD::SDIVREM:
6235   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6236   case ISD::DYNAMIC_STACKALLOC:
6237     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6238       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6239     llvm_unreachable("Don't know how to custom lower this!");
6240   }
6241 }
6242
6243 /// ReplaceNodeResults - Replace the results of node with an illegal result
6244 /// type with new values built out of custom code.
6245 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6246                                            SmallVectorImpl<SDValue>&Results,
6247                                            SelectionDAG &DAG) const {
6248   SDValue Res;
6249   switch (N->getOpcode()) {
6250   default:
6251     llvm_unreachable("Don't know how to custom expand this!");
6252   case ISD::BITCAST:
6253     Res = ExpandBITCAST(N, DAG);
6254     break;
6255   case ISD::SRL:
6256   case ISD::SRA:
6257     Res = Expand64BitShift(N, DAG, Subtarget);
6258     break;
6259   case ISD::READCYCLECOUNTER:
6260     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6261     return;
6262   }
6263   if (Res.getNode())
6264     Results.push_back(Res);
6265 }
6266
6267 //===----------------------------------------------------------------------===//
6268 //                           ARM Scheduler Hooks
6269 //===----------------------------------------------------------------------===//
6270
6271 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6272 /// registers the function context.
6273 void ARMTargetLowering::
6274 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6275                        MachineBasicBlock *DispatchBB, int FI) const {
6276   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6277   DebugLoc dl = MI->getDebugLoc();
6278   MachineFunction *MF = MBB->getParent();
6279   MachineRegisterInfo *MRI = &MF->getRegInfo();
6280   MachineConstantPool *MCP = MF->getConstantPool();
6281   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6282   const Function *F = MF->getFunction();
6283
6284   bool isThumb = Subtarget->isThumb();
6285   bool isThumb2 = Subtarget->isThumb2();
6286
6287   unsigned PCLabelId = AFI->createPICLabelUId();
6288   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6289   ARMConstantPoolValue *CPV =
6290     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6291   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6292
6293   const TargetRegisterClass *TRC = isThumb ?
6294     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6295     (const TargetRegisterClass*)&ARM::GPRRegClass;
6296
6297   // Grab constant pool and fixed stack memory operands.
6298   MachineMemOperand *CPMMO =
6299     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6300                              MachineMemOperand::MOLoad, 4, 4);
6301
6302   MachineMemOperand *FIMMOSt =
6303     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6304                              MachineMemOperand::MOStore, 4, 4);
6305
6306   // Load the address of the dispatch MBB into the jump buffer.
6307   if (isThumb2) {
6308     // Incoming value: jbuf
6309     //   ldr.n  r5, LCPI1_1
6310     //   orr    r5, r5, #1
6311     //   add    r5, pc
6312     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6313     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6314     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6315                    .addConstantPoolIndex(CPI)
6316                    .addMemOperand(CPMMO));
6317     // Set the low bit because of thumb mode.
6318     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6319     AddDefaultCC(
6320       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6321                      .addReg(NewVReg1, RegState::Kill)
6322                      .addImm(0x01)));
6323     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6324     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6325       .addReg(NewVReg2, RegState::Kill)
6326       .addImm(PCLabelId);
6327     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6328                    .addReg(NewVReg3, RegState::Kill)
6329                    .addFrameIndex(FI)
6330                    .addImm(36)  // &jbuf[1] :: pc
6331                    .addMemOperand(FIMMOSt));
6332   } else if (isThumb) {
6333     // Incoming value: jbuf
6334     //   ldr.n  r1, LCPI1_4
6335     //   add    r1, pc
6336     //   mov    r2, #1
6337     //   orrs   r1, r2
6338     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6339     //   str    r1, [r2]
6340     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6341     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6342                    .addConstantPoolIndex(CPI)
6343                    .addMemOperand(CPMMO));
6344     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6345     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6346       .addReg(NewVReg1, RegState::Kill)
6347       .addImm(PCLabelId);
6348     // Set the low bit because of thumb mode.
6349     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6350     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6351                    .addReg(ARM::CPSR, RegState::Define)
6352                    .addImm(1));
6353     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6354     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6355                    .addReg(ARM::CPSR, RegState::Define)
6356                    .addReg(NewVReg2, RegState::Kill)
6357                    .addReg(NewVReg3, RegState::Kill));
6358     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6359     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6360                    .addFrameIndex(FI)
6361                    .addImm(36)); // &jbuf[1] :: pc
6362     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6363                    .addReg(NewVReg4, RegState::Kill)
6364                    .addReg(NewVReg5, RegState::Kill)
6365                    .addImm(0)
6366                    .addMemOperand(FIMMOSt));
6367   } else {
6368     // Incoming value: jbuf
6369     //   ldr  r1, LCPI1_1
6370     //   add  r1, pc, r1
6371     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6372     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6373     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6374                    .addConstantPoolIndex(CPI)
6375                    .addImm(0)
6376                    .addMemOperand(CPMMO));
6377     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6378     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6379                    .addReg(NewVReg1, RegState::Kill)
6380                    .addImm(PCLabelId));
6381     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6382                    .addReg(NewVReg2, RegState::Kill)
6383                    .addFrameIndex(FI)
6384                    .addImm(36)  // &jbuf[1] :: pc
6385                    .addMemOperand(FIMMOSt));
6386   }
6387 }
6388
6389 MachineBasicBlock *ARMTargetLowering::
6390 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6391   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6392   DebugLoc dl = MI->getDebugLoc();
6393   MachineFunction *MF = MBB->getParent();
6394   MachineRegisterInfo *MRI = &MF->getRegInfo();
6395   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6396   MachineFrameInfo *MFI = MF->getFrameInfo();
6397   int FI = MFI->getFunctionContextIndex();
6398
6399   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6400     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6401     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6402
6403   // Get a mapping of the call site numbers to all of the landing pads they're
6404   // associated with.
6405   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6406   unsigned MaxCSNum = 0;
6407   MachineModuleInfo &MMI = MF->getMMI();
6408   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6409        ++BB) {
6410     if (!BB->isLandingPad()) continue;
6411
6412     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6413     // pad.
6414     for (MachineBasicBlock::iterator
6415            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6416       if (!II->isEHLabel()) continue;
6417
6418       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6419       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6420
6421       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6422       for (SmallVectorImpl<unsigned>::iterator
6423              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6424            CSI != CSE; ++CSI) {
6425         CallSiteNumToLPad[*CSI].push_back(BB);
6426         MaxCSNum = std::max(MaxCSNum, *CSI);
6427       }
6428       break;
6429     }
6430   }
6431
6432   // Get an ordered list of the machine basic blocks for the jump table.
6433   std::vector<MachineBasicBlock*> LPadList;
6434   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6435   LPadList.reserve(CallSiteNumToLPad.size());
6436   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6437     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6438     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6439            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6440       LPadList.push_back(*II);
6441       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6442     }
6443   }
6444
6445   assert(!LPadList.empty() &&
6446          "No landing pad destinations for the dispatch jump table!");
6447
6448   // Create the jump table and associated information.
6449   MachineJumpTableInfo *JTI =
6450     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6451   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6452   unsigned UId = AFI->createJumpTableUId();
6453   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6454
6455   // Create the MBBs for the dispatch code.
6456
6457   // Shove the dispatch's address into the return slot in the function context.
6458   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6459   DispatchBB->setIsLandingPad();
6460
6461   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6462   unsigned trap_opcode;
6463   if (Subtarget->isThumb())
6464     trap_opcode = ARM::tTRAP;
6465   else
6466     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6467
6468   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6469   DispatchBB->addSuccessor(TrapBB);
6470
6471   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6472   DispatchBB->addSuccessor(DispContBB);
6473
6474   // Insert and MBBs.
6475   MF->insert(MF->end(), DispatchBB);
6476   MF->insert(MF->end(), DispContBB);
6477   MF->insert(MF->end(), TrapBB);
6478
6479   // Insert code into the entry block that creates and registers the function
6480   // context.
6481   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6482
6483   MachineMemOperand *FIMMOLd =
6484     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6485                              MachineMemOperand::MOLoad |
6486                              MachineMemOperand::MOVolatile, 4, 4);
6487
6488   MachineInstrBuilder MIB;
6489   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6490
6491   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6492   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6493
6494   // Add a register mask with no preserved registers.  This results in all
6495   // registers being marked as clobbered.
6496   MIB.addRegMask(RI.getNoPreservedMask());
6497
6498   unsigned NumLPads = LPadList.size();
6499   if (Subtarget->isThumb2()) {
6500     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6501     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6502                    .addFrameIndex(FI)
6503                    .addImm(4)
6504                    .addMemOperand(FIMMOLd));
6505
6506     if (NumLPads < 256) {
6507       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6508                      .addReg(NewVReg1)
6509                      .addImm(LPadList.size()));
6510     } else {
6511       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6512       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6513                      .addImm(NumLPads & 0xFFFF));
6514
6515       unsigned VReg2 = VReg1;
6516       if ((NumLPads & 0xFFFF0000) != 0) {
6517         VReg2 = MRI->createVirtualRegister(TRC);
6518         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6519                        .addReg(VReg1)
6520                        .addImm(NumLPads >> 16));
6521       }
6522
6523       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6524                      .addReg(NewVReg1)
6525                      .addReg(VReg2));
6526     }
6527
6528     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6529       .addMBB(TrapBB)
6530       .addImm(ARMCC::HI)
6531       .addReg(ARM::CPSR);
6532
6533     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6534     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6535                    .addJumpTableIndex(MJTI)
6536                    .addImm(UId));
6537
6538     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6539     AddDefaultCC(
6540       AddDefaultPred(
6541         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6542         .addReg(NewVReg3, RegState::Kill)
6543         .addReg(NewVReg1)
6544         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6545
6546     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6547       .addReg(NewVReg4, RegState::Kill)
6548       .addReg(NewVReg1)
6549       .addJumpTableIndex(MJTI)
6550       .addImm(UId);
6551   } else if (Subtarget->isThumb()) {
6552     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6553     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6554                    .addFrameIndex(FI)
6555                    .addImm(1)
6556                    .addMemOperand(FIMMOLd));
6557
6558     if (NumLPads < 256) {
6559       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6560                      .addReg(NewVReg1)
6561                      .addImm(NumLPads));
6562     } else {
6563       MachineConstantPool *ConstantPool = MF->getConstantPool();
6564       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6565       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6566
6567       // MachineConstantPool wants an explicit alignment.
6568       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6569       if (Align == 0)
6570         Align = getDataLayout()->getTypeAllocSize(C->getType());
6571       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6572
6573       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6574       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6575                      .addReg(VReg1, RegState::Define)
6576                      .addConstantPoolIndex(Idx));
6577       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6578                      .addReg(NewVReg1)
6579                      .addReg(VReg1));
6580     }
6581
6582     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6583       .addMBB(TrapBB)
6584       .addImm(ARMCC::HI)
6585       .addReg(ARM::CPSR);
6586
6587     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6588     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6589                    .addReg(ARM::CPSR, RegState::Define)
6590                    .addReg(NewVReg1)
6591                    .addImm(2));
6592
6593     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6594     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6595                    .addJumpTableIndex(MJTI)
6596                    .addImm(UId));
6597
6598     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6599     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6600                    .addReg(ARM::CPSR, RegState::Define)
6601                    .addReg(NewVReg2, RegState::Kill)
6602                    .addReg(NewVReg3));
6603
6604     MachineMemOperand *JTMMOLd =
6605       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6606                                MachineMemOperand::MOLoad, 4, 4);
6607
6608     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6609     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6610                    .addReg(NewVReg4, RegState::Kill)
6611                    .addImm(0)
6612                    .addMemOperand(JTMMOLd));
6613
6614     unsigned NewVReg6 = NewVReg5;
6615     if (RelocM == Reloc::PIC_) {
6616       NewVReg6 = MRI->createVirtualRegister(TRC);
6617       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6618                      .addReg(ARM::CPSR, RegState::Define)
6619                      .addReg(NewVReg5, RegState::Kill)
6620                      .addReg(NewVReg3));
6621     }
6622
6623     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6624       .addReg(NewVReg6, RegState::Kill)
6625       .addJumpTableIndex(MJTI)
6626       .addImm(UId);
6627   } else {
6628     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6629     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6630                    .addFrameIndex(FI)
6631                    .addImm(4)
6632                    .addMemOperand(FIMMOLd));
6633
6634     if (NumLPads < 256) {
6635       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6636                      .addReg(NewVReg1)
6637                      .addImm(NumLPads));
6638     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6639       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6640       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6641                      .addImm(NumLPads & 0xFFFF));
6642
6643       unsigned VReg2 = VReg1;
6644       if ((NumLPads & 0xFFFF0000) != 0) {
6645         VReg2 = MRI->createVirtualRegister(TRC);
6646         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6647                        .addReg(VReg1)
6648                        .addImm(NumLPads >> 16));
6649       }
6650
6651       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6652                      .addReg(NewVReg1)
6653                      .addReg(VReg2));
6654     } else {
6655       MachineConstantPool *ConstantPool = MF->getConstantPool();
6656       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6657       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6658
6659       // MachineConstantPool wants an explicit alignment.
6660       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6661       if (Align == 0)
6662         Align = getDataLayout()->getTypeAllocSize(C->getType());
6663       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6664
6665       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6666       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6667                      .addReg(VReg1, RegState::Define)
6668                      .addConstantPoolIndex(Idx)
6669                      .addImm(0));
6670       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6671                      .addReg(NewVReg1)
6672                      .addReg(VReg1, RegState::Kill));
6673     }
6674
6675     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6676       .addMBB(TrapBB)
6677       .addImm(ARMCC::HI)
6678       .addReg(ARM::CPSR);
6679
6680     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6681     AddDefaultCC(
6682       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6683                      .addReg(NewVReg1)
6684                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6685     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6686     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6687                    .addJumpTableIndex(MJTI)
6688                    .addImm(UId));
6689
6690     MachineMemOperand *JTMMOLd =
6691       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6692                                MachineMemOperand::MOLoad, 4, 4);
6693     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6694     AddDefaultPred(
6695       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6696       .addReg(NewVReg3, RegState::Kill)
6697       .addReg(NewVReg4)
6698       .addImm(0)
6699       .addMemOperand(JTMMOLd));
6700
6701     if (RelocM == Reloc::PIC_) {
6702       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6703         .addReg(NewVReg5, RegState::Kill)
6704         .addReg(NewVReg4)
6705         .addJumpTableIndex(MJTI)
6706         .addImm(UId);
6707     } else {
6708       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6709         .addReg(NewVReg5, RegState::Kill)
6710         .addJumpTableIndex(MJTI)
6711         .addImm(UId);
6712     }
6713   }
6714
6715   // Add the jump table entries as successors to the MBB.
6716   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6717   for (std::vector<MachineBasicBlock*>::iterator
6718          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6719     MachineBasicBlock *CurMBB = *I;
6720     if (SeenMBBs.insert(CurMBB))
6721       DispContBB->addSuccessor(CurMBB);
6722   }
6723
6724   // N.B. the order the invoke BBs are processed in doesn't matter here.
6725   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6726   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6727   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6728          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6729     MachineBasicBlock *BB = *I;
6730
6731     // Remove the landing pad successor from the invoke block and replace it
6732     // with the new dispatch block.
6733     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6734                                                   BB->succ_end());
6735     while (!Successors.empty()) {
6736       MachineBasicBlock *SMBB = Successors.pop_back_val();
6737       if (SMBB->isLandingPad()) {
6738         BB->removeSuccessor(SMBB);
6739         MBBLPads.push_back(SMBB);
6740       }
6741     }
6742
6743     BB->addSuccessor(DispatchBB);
6744
6745     // Find the invoke call and mark all of the callee-saved registers as
6746     // 'implicit defined' so that they're spilled. This prevents code from
6747     // moving instructions to before the EH block, where they will never be
6748     // executed.
6749     for (MachineBasicBlock::reverse_iterator
6750            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6751       if (!II->isCall()) continue;
6752
6753       DenseMap<unsigned, bool> DefRegs;
6754       for (MachineInstr::mop_iterator
6755              OI = II->operands_begin(), OE = II->operands_end();
6756            OI != OE; ++OI) {
6757         if (!OI->isReg()) continue;
6758         DefRegs[OI->getReg()] = true;
6759       }
6760
6761       MachineInstrBuilder MIB(*MF, &*II);
6762
6763       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6764         unsigned Reg = SavedRegs[i];
6765         if (Subtarget->isThumb2() &&
6766             !ARM::tGPRRegClass.contains(Reg) &&
6767             !ARM::hGPRRegClass.contains(Reg))
6768           continue;
6769         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6770           continue;
6771         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6772           continue;
6773         if (!DefRegs[Reg])
6774           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6775       }
6776
6777       break;
6778     }
6779   }
6780
6781   // Mark all former landing pads as non-landing pads. The dispatch is the only
6782   // landing pad now.
6783   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6784          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6785     (*I)->setIsLandingPad(false);
6786
6787   // The instruction is gone now.
6788   MI->eraseFromParent();
6789
6790   return MBB;
6791 }
6792
6793 static
6794 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6795   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6796        E = MBB->succ_end(); I != E; ++I)
6797     if (*I != Succ)
6798       return *I;
6799   llvm_unreachable("Expecting a BB with two successors!");
6800 }
6801
6802 /// Return the load opcode for a given load size. If load size >= 8,
6803 /// neon opcode will be returned.
6804 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6805   if (LdSize >= 8)
6806     return LdSize == 16 ? ARM::VLD1q32wb_fixed
6807                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6808   if (IsThumb1)
6809     return LdSize == 4 ? ARM::tLDRi
6810                        : LdSize == 2 ? ARM::tLDRHi
6811                                      : LdSize == 1 ? ARM::tLDRBi : 0;
6812   if (IsThumb2)
6813     return LdSize == 4 ? ARM::t2LDR_POST
6814                        : LdSize == 2 ? ARM::t2LDRH_POST
6815                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
6816   return LdSize == 4 ? ARM::LDR_POST_IMM
6817                      : LdSize == 2 ? ARM::LDRH_POST
6818                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
6819 }
6820
6821 /// Return the store opcode for a given store size. If store size >= 8,
6822 /// neon opcode will be returned.
6823 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
6824   if (StSize >= 8)
6825     return StSize == 16 ? ARM::VST1q32wb_fixed
6826                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
6827   if (IsThumb1)
6828     return StSize == 4 ? ARM::tSTRi
6829                        : StSize == 2 ? ARM::tSTRHi
6830                                      : StSize == 1 ? ARM::tSTRBi : 0;
6831   if (IsThumb2)
6832     return StSize == 4 ? ARM::t2STR_POST
6833                        : StSize == 2 ? ARM::t2STRH_POST
6834                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
6835   return StSize == 4 ? ARM::STR_POST_IMM
6836                      : StSize == 2 ? ARM::STRH_POST
6837                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
6838 }
6839
6840 /// Emit a post-increment load operation with given size. The instructions
6841 /// will be added to BB at Pos.
6842 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
6843                        const TargetInstrInfo *TII, DebugLoc dl,
6844                        unsigned LdSize, unsigned Data, unsigned AddrIn,
6845                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6846   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
6847   assert(LdOpc != 0 && "Should have a load opcode");
6848   if (LdSize >= 8) {
6849     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6850                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6851                        .addImm(0));
6852   } else if (IsThumb1) {
6853     // load + update AddrIn
6854     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6855                        .addReg(AddrIn).addImm(0));
6856     MachineInstrBuilder MIB =
6857         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6858     MIB = AddDefaultT1CC(MIB);
6859     MIB.addReg(AddrIn).addImm(LdSize);
6860     AddDefaultPred(MIB);
6861   } else if (IsThumb2) {
6862     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6863                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6864                        .addImm(LdSize));
6865   } else { // arm
6866     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6867                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6868                        .addReg(0).addImm(LdSize));
6869   }
6870 }
6871
6872 /// Emit a post-increment store operation with given size. The instructions
6873 /// will be added to BB at Pos.
6874 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
6875                        const TargetInstrInfo *TII, DebugLoc dl,
6876                        unsigned StSize, unsigned Data, unsigned AddrIn,
6877                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6878   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
6879   assert(StOpc != 0 && "Should have a store opcode");
6880   if (StSize >= 8) {
6881     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6882                        .addReg(AddrIn).addImm(0).addReg(Data));
6883   } else if (IsThumb1) {
6884     // store + update AddrIn
6885     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
6886                        .addReg(AddrIn).addImm(0));
6887     MachineInstrBuilder MIB =
6888         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6889     MIB = AddDefaultT1CC(MIB);
6890     MIB.addReg(AddrIn).addImm(StSize);
6891     AddDefaultPred(MIB);
6892   } else if (IsThumb2) {
6893     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6894                        .addReg(Data).addReg(AddrIn).addImm(StSize));
6895   } else { // arm
6896     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6897                        .addReg(Data).addReg(AddrIn).addReg(0)
6898                        .addImm(StSize));
6899   }
6900 }
6901
6902 MachineBasicBlock *
6903 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
6904                                    MachineBasicBlock *BB) const {
6905   // This pseudo instruction has 3 operands: dst, src, size
6906   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6907   // Otherwise, we will generate unrolled scalar copies.
6908   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6909   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6910   MachineFunction::iterator It = BB;
6911   ++It;
6912
6913   unsigned dest = MI->getOperand(0).getReg();
6914   unsigned src = MI->getOperand(1).getReg();
6915   unsigned SizeVal = MI->getOperand(2).getImm();
6916   unsigned Align = MI->getOperand(3).getImm();
6917   DebugLoc dl = MI->getDebugLoc();
6918
6919   MachineFunction *MF = BB->getParent();
6920   MachineRegisterInfo &MRI = MF->getRegInfo();
6921   unsigned UnitSize = 0;
6922   const TargetRegisterClass *TRC = nullptr;
6923   const TargetRegisterClass *VecTRC = nullptr;
6924
6925   bool IsThumb1 = Subtarget->isThumb1Only();
6926   bool IsThumb2 = Subtarget->isThumb2();
6927
6928   if (Align & 1) {
6929     UnitSize = 1;
6930   } else if (Align & 2) {
6931     UnitSize = 2;
6932   } else {
6933     // Check whether we can use NEON instructions.
6934     if (!MF->getFunction()->getAttributes().
6935           hasAttribute(AttributeSet::FunctionIndex,
6936                        Attribute::NoImplicitFloat) &&
6937         Subtarget->hasNEON()) {
6938       if ((Align % 16 == 0) && SizeVal >= 16)
6939         UnitSize = 16;
6940       else if ((Align % 8 == 0) && SizeVal >= 8)
6941         UnitSize = 8;
6942     }
6943     // Can't use NEON instructions.
6944     if (UnitSize == 0)
6945       UnitSize = 4;
6946   }
6947
6948   // Select the correct opcode and register class for unit size load/store
6949   bool IsNeon = UnitSize >= 8;
6950   TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
6951                                : (const TargetRegisterClass *)&ARM::GPRRegClass;
6952   if (IsNeon)
6953     VecTRC = UnitSize == 16
6954                  ? (const TargetRegisterClass *)&ARM::DPairRegClass
6955                  : UnitSize == 8
6956                        ? (const TargetRegisterClass *)&ARM::DPRRegClass
6957                        : nullptr;
6958
6959   unsigned BytesLeft = SizeVal % UnitSize;
6960   unsigned LoopSize = SizeVal - BytesLeft;
6961
6962   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6963     // Use LDR and STR to copy.
6964     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6965     // [destOut] = STR_POST(scratch, destIn, UnitSize)
6966     unsigned srcIn = src;
6967     unsigned destIn = dest;
6968     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6969       unsigned srcOut = MRI.createVirtualRegister(TRC);
6970       unsigned destOut = MRI.createVirtualRegister(TRC);
6971       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
6972       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
6973                  IsThumb1, IsThumb2);
6974       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
6975                  IsThumb1, IsThumb2);
6976       srcIn = srcOut;
6977       destIn = destOut;
6978     }
6979
6980     // Handle the leftover bytes with LDRB and STRB.
6981     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6982     // [destOut] = STRB_POST(scratch, destIn, 1)
6983     for (unsigned i = 0; i < BytesLeft; i++) {
6984       unsigned srcOut = MRI.createVirtualRegister(TRC);
6985       unsigned destOut = MRI.createVirtualRegister(TRC);
6986       unsigned scratch = MRI.createVirtualRegister(TRC);
6987       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
6988                  IsThumb1, IsThumb2);
6989       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
6990                  IsThumb1, IsThumb2);
6991       srcIn = srcOut;
6992       destIn = destOut;
6993     }
6994     MI->eraseFromParent();   // The instruction is gone now.
6995     return BB;
6996   }
6997
6998   // Expand the pseudo op to a loop.
6999   // thisMBB:
7000   //   ...
7001   //   movw varEnd, # --> with thumb2
7002   //   movt varEnd, #
7003   //   ldrcp varEnd, idx --> without thumb2
7004   //   fallthrough --> loopMBB
7005   // loopMBB:
7006   //   PHI varPhi, varEnd, varLoop
7007   //   PHI srcPhi, src, srcLoop
7008   //   PHI destPhi, dst, destLoop
7009   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7010   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7011   //   subs varLoop, varPhi, #UnitSize
7012   //   bne loopMBB
7013   //   fallthrough --> exitMBB
7014   // exitMBB:
7015   //   epilogue to handle left-over bytes
7016   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7017   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7018   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7019   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7020   MF->insert(It, loopMBB);
7021   MF->insert(It, exitMBB);
7022
7023   // Transfer the remainder of BB and its successor edges to exitMBB.
7024   exitMBB->splice(exitMBB->begin(), BB,
7025                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7026   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7027
7028   // Load an immediate to varEnd.
7029   unsigned varEnd = MRI.createVirtualRegister(TRC);
7030   if (IsThumb2) {
7031     unsigned Vtmp = varEnd;
7032     if ((LoopSize & 0xFFFF0000) != 0)
7033       Vtmp = MRI.createVirtualRegister(TRC);
7034     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7035                        .addImm(LoopSize & 0xFFFF));
7036
7037     if ((LoopSize & 0xFFFF0000) != 0)
7038       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7039                          .addReg(Vtmp).addImm(LoopSize >> 16));
7040   } else {
7041     MachineConstantPool *ConstantPool = MF->getConstantPool();
7042     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7043     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7044
7045     // MachineConstantPool wants an explicit alignment.
7046     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7047     if (Align == 0)
7048       Align = getDataLayout()->getTypeAllocSize(C->getType());
7049     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7050
7051     if (IsThumb1)
7052       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7053           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7054     else
7055       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7056           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7057   }
7058   BB->addSuccessor(loopMBB);
7059
7060   // Generate the loop body:
7061   //   varPhi = PHI(varLoop, varEnd)
7062   //   srcPhi = PHI(srcLoop, src)
7063   //   destPhi = PHI(destLoop, dst)
7064   MachineBasicBlock *entryBB = BB;
7065   BB = loopMBB;
7066   unsigned varLoop = MRI.createVirtualRegister(TRC);
7067   unsigned varPhi = MRI.createVirtualRegister(TRC);
7068   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7069   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7070   unsigned destLoop = MRI.createVirtualRegister(TRC);
7071   unsigned destPhi = MRI.createVirtualRegister(TRC);
7072
7073   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7074     .addReg(varLoop).addMBB(loopMBB)
7075     .addReg(varEnd).addMBB(entryBB);
7076   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7077     .addReg(srcLoop).addMBB(loopMBB)
7078     .addReg(src).addMBB(entryBB);
7079   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7080     .addReg(destLoop).addMBB(loopMBB)
7081     .addReg(dest).addMBB(entryBB);
7082
7083   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7084   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7085   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7086   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7087              IsThumb1, IsThumb2);
7088   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7089              IsThumb1, IsThumb2);
7090
7091   // Decrement loop variable by UnitSize.
7092   if (IsThumb1) {
7093     MachineInstrBuilder MIB =
7094         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7095     MIB = AddDefaultT1CC(MIB);
7096     MIB.addReg(varPhi).addImm(UnitSize);
7097     AddDefaultPred(MIB);
7098   } else {
7099     MachineInstrBuilder MIB =
7100         BuildMI(*BB, BB->end(), dl,
7101                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7102     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7103     MIB->getOperand(5).setReg(ARM::CPSR);
7104     MIB->getOperand(5).setIsDef(true);
7105   }
7106   BuildMI(*BB, BB->end(), dl,
7107           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7108       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7109
7110   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7111   BB->addSuccessor(loopMBB);
7112   BB->addSuccessor(exitMBB);
7113
7114   // Add epilogue to handle BytesLeft.
7115   BB = exitMBB;
7116   MachineInstr *StartOfExit = exitMBB->begin();
7117
7118   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7119   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7120   unsigned srcIn = srcLoop;
7121   unsigned destIn = destLoop;
7122   for (unsigned i = 0; i < BytesLeft; i++) {
7123     unsigned srcOut = MRI.createVirtualRegister(TRC);
7124     unsigned destOut = MRI.createVirtualRegister(TRC);
7125     unsigned scratch = MRI.createVirtualRegister(TRC);
7126     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7127                IsThumb1, IsThumb2);
7128     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7129                IsThumb1, IsThumb2);
7130     srcIn = srcOut;
7131     destIn = destOut;
7132   }
7133
7134   MI->eraseFromParent();   // The instruction is gone now.
7135   return BB;
7136 }
7137
7138 MachineBasicBlock *
7139 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7140                                        MachineBasicBlock *MBB) const {
7141   const TargetMachine &TM = getTargetMachine();
7142   const TargetInstrInfo &TII = *TM.getInstrInfo();
7143   DebugLoc DL = MI->getDebugLoc();
7144
7145   assert(Subtarget->isTargetWindows() &&
7146          "__chkstk is only supported on Windows");
7147   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7148
7149   // __chkstk takes the number of words to allocate on the stack in R4, and
7150   // returns the stack adjustment in number of bytes in R4.  This will not
7151   // clober any other registers (other than the obvious lr).
7152   //
7153   // Although, technically, IP should be considered a register which may be
7154   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7155   // thumb-2 environment, so there is no interworking required.  As a result, we
7156   // do not expect a veneer to be emitted by the linker, clobbering IP.
7157   //
7158   // Each module receives its own copy of __chkstk, so no import thunk is
7159   // required, again, ensuring that IP is not clobbered.
7160   //
7161   // Finally, although some linkers may theoretically provide a trampoline for
7162   // out of range calls (which is quite common due to a 32M range limitation of
7163   // branches for Thumb), we can generate the long-call version via
7164   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7165   // IP.
7166
7167   switch (TM.getCodeModel()) {
7168   case CodeModel::Small:
7169   case CodeModel::Medium:
7170   case CodeModel::Default:
7171   case CodeModel::Kernel:
7172     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7173       .addImm((unsigned)ARMCC::AL).addReg(0)
7174       .addExternalSymbol("__chkstk")
7175       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7176       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7177       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7178     break;
7179   case CodeModel::Large:
7180   case CodeModel::JITDefault: {
7181     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7182     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7183
7184     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7185       .addExternalSymbol("__chkstk");
7186     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7187       .addImm((unsigned)ARMCC::AL).addReg(0)
7188       .addReg(Reg, RegState::Kill)
7189       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7190       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7191       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7192     break;
7193   }
7194   }
7195
7196   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7197                                       ARM::SP)
7198                               .addReg(ARM::SP, RegState::Define)
7199                               .addReg(ARM::R4, RegState::Kill)));
7200
7201   MI->eraseFromParent();
7202   return MBB;
7203 }
7204
7205 MachineBasicBlock *
7206 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7207                                                MachineBasicBlock *BB) const {
7208   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7209   DebugLoc dl = MI->getDebugLoc();
7210   bool isThumb2 = Subtarget->isThumb2();
7211   switch (MI->getOpcode()) {
7212   default: {
7213     MI->dump();
7214     llvm_unreachable("Unexpected instr type to insert");
7215   }
7216   // The Thumb2 pre-indexed stores have the same MI operands, they just
7217   // define them differently in the .td files from the isel patterns, so
7218   // they need pseudos.
7219   case ARM::t2STR_preidx:
7220     MI->setDesc(TII->get(ARM::t2STR_PRE));
7221     return BB;
7222   case ARM::t2STRB_preidx:
7223     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7224     return BB;
7225   case ARM::t2STRH_preidx:
7226     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7227     return BB;
7228
7229   case ARM::STRi_preidx:
7230   case ARM::STRBi_preidx: {
7231     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7232       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7233     // Decode the offset.
7234     unsigned Offset = MI->getOperand(4).getImm();
7235     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7236     Offset = ARM_AM::getAM2Offset(Offset);
7237     if (isSub)
7238       Offset = -Offset;
7239
7240     MachineMemOperand *MMO = *MI->memoperands_begin();
7241     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7242       .addOperand(MI->getOperand(0))  // Rn_wb
7243       .addOperand(MI->getOperand(1))  // Rt
7244       .addOperand(MI->getOperand(2))  // Rn
7245       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7246       .addOperand(MI->getOperand(5))  // pred
7247       .addOperand(MI->getOperand(6))
7248       .addMemOperand(MMO);
7249     MI->eraseFromParent();
7250     return BB;
7251   }
7252   case ARM::STRr_preidx:
7253   case ARM::STRBr_preidx:
7254   case ARM::STRH_preidx: {
7255     unsigned NewOpc;
7256     switch (MI->getOpcode()) {
7257     default: llvm_unreachable("unexpected opcode!");
7258     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7259     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7260     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7261     }
7262     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7263     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7264       MIB.addOperand(MI->getOperand(i));
7265     MI->eraseFromParent();
7266     return BB;
7267   }
7268
7269   case ARM::tMOVCCr_pseudo: {
7270     // To "insert" a SELECT_CC instruction, we actually have to insert the
7271     // diamond control-flow pattern.  The incoming instruction knows the
7272     // destination vreg to set, the condition code register to branch on, the
7273     // true/false values to select between, and a branch opcode to use.
7274     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7275     MachineFunction::iterator It = BB;
7276     ++It;
7277
7278     //  thisMBB:
7279     //  ...
7280     //   TrueVal = ...
7281     //   cmpTY ccX, r1, r2
7282     //   bCC copy1MBB
7283     //   fallthrough --> copy0MBB
7284     MachineBasicBlock *thisMBB  = BB;
7285     MachineFunction *F = BB->getParent();
7286     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7287     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7288     F->insert(It, copy0MBB);
7289     F->insert(It, sinkMBB);
7290
7291     // Transfer the remainder of BB and its successor edges to sinkMBB.
7292     sinkMBB->splice(sinkMBB->begin(), BB,
7293                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7294     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7295
7296     BB->addSuccessor(copy0MBB);
7297     BB->addSuccessor(sinkMBB);
7298
7299     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7300       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7301
7302     //  copy0MBB:
7303     //   %FalseValue = ...
7304     //   # fallthrough to sinkMBB
7305     BB = copy0MBB;
7306
7307     // Update machine-CFG edges
7308     BB->addSuccessor(sinkMBB);
7309
7310     //  sinkMBB:
7311     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7312     //  ...
7313     BB = sinkMBB;
7314     BuildMI(*BB, BB->begin(), dl,
7315             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7316       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7317       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7318
7319     MI->eraseFromParent();   // The pseudo instruction is gone now.
7320     return BB;
7321   }
7322
7323   case ARM::BCCi64:
7324   case ARM::BCCZi64: {
7325     // If there is an unconditional branch to the other successor, remove it.
7326     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7327
7328     // Compare both parts that make up the double comparison separately for
7329     // equality.
7330     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7331
7332     unsigned LHS1 = MI->getOperand(1).getReg();
7333     unsigned LHS2 = MI->getOperand(2).getReg();
7334     if (RHSisZero) {
7335       AddDefaultPred(BuildMI(BB, dl,
7336                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7337                      .addReg(LHS1).addImm(0));
7338       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7339         .addReg(LHS2).addImm(0)
7340         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7341     } else {
7342       unsigned RHS1 = MI->getOperand(3).getReg();
7343       unsigned RHS2 = MI->getOperand(4).getReg();
7344       AddDefaultPred(BuildMI(BB, dl,
7345                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7346                      .addReg(LHS1).addReg(RHS1));
7347       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7348         .addReg(LHS2).addReg(RHS2)
7349         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7350     }
7351
7352     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7353     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7354     if (MI->getOperand(0).getImm() == ARMCC::NE)
7355       std::swap(destMBB, exitMBB);
7356
7357     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7358       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7359     if (isThumb2)
7360       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7361     else
7362       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7363
7364     MI->eraseFromParent();   // The pseudo instruction is gone now.
7365     return BB;
7366   }
7367
7368   case ARM::Int_eh_sjlj_setjmp:
7369   case ARM::Int_eh_sjlj_setjmp_nofp:
7370   case ARM::tInt_eh_sjlj_setjmp:
7371   case ARM::t2Int_eh_sjlj_setjmp:
7372   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7373     EmitSjLjDispatchBlock(MI, BB);
7374     return BB;
7375
7376   case ARM::ABS:
7377   case ARM::t2ABS: {
7378     // To insert an ABS instruction, we have to insert the
7379     // diamond control-flow pattern.  The incoming instruction knows the
7380     // source vreg to test against 0, the destination vreg to set,
7381     // the condition code register to branch on, the
7382     // true/false values to select between, and a branch opcode to use.
7383     // It transforms
7384     //     V1 = ABS V0
7385     // into
7386     //     V2 = MOVS V0
7387     //     BCC                      (branch to SinkBB if V0 >= 0)
7388     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7389     //     SinkBB: V1 = PHI(V2, V3)
7390     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7391     MachineFunction::iterator BBI = BB;
7392     ++BBI;
7393     MachineFunction *Fn = BB->getParent();
7394     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7395     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7396     Fn->insert(BBI, RSBBB);
7397     Fn->insert(BBI, SinkBB);
7398
7399     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7400     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7401     bool isThumb2 = Subtarget->isThumb2();
7402     MachineRegisterInfo &MRI = Fn->getRegInfo();
7403     // In Thumb mode S must not be specified if source register is the SP or
7404     // PC and if destination register is the SP, so restrict register class
7405     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7406       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7407       (const TargetRegisterClass*)&ARM::GPRRegClass);
7408
7409     // Transfer the remainder of BB and its successor edges to sinkMBB.
7410     SinkBB->splice(SinkBB->begin(), BB,
7411                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7412     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7413
7414     BB->addSuccessor(RSBBB);
7415     BB->addSuccessor(SinkBB);
7416
7417     // fall through to SinkMBB
7418     RSBBB->addSuccessor(SinkBB);
7419
7420     // insert a cmp at the end of BB
7421     AddDefaultPred(BuildMI(BB, dl,
7422                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7423                    .addReg(ABSSrcReg).addImm(0));
7424
7425     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7426     BuildMI(BB, dl,
7427       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7428       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7429
7430     // insert rsbri in RSBBB
7431     // Note: BCC and rsbri will be converted into predicated rsbmi
7432     // by if-conversion pass
7433     BuildMI(*RSBBB, RSBBB->begin(), dl,
7434       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7435       .addReg(ABSSrcReg, RegState::Kill)
7436       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7437
7438     // insert PHI in SinkBB,
7439     // reuse ABSDstReg to not change uses of ABS instruction
7440     BuildMI(*SinkBB, SinkBB->begin(), dl,
7441       TII->get(ARM::PHI), ABSDstReg)
7442       .addReg(NewRsbDstReg).addMBB(RSBBB)
7443       .addReg(ABSSrcReg).addMBB(BB);
7444
7445     // remove ABS instruction
7446     MI->eraseFromParent();
7447
7448     // return last added BB
7449     return SinkBB;
7450   }
7451   case ARM::COPY_STRUCT_BYVAL_I32:
7452     ++NumLoopByVals;
7453     return EmitStructByval(MI, BB);
7454   case ARM::WIN__CHKSTK:
7455     return EmitLowered__chkstk(MI, BB);
7456   }
7457 }
7458
7459 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7460                                                       SDNode *Node) const {
7461   if (!MI->hasPostISelHook()) {
7462     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7463            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7464     return;
7465   }
7466
7467   const MCInstrDesc *MCID = &MI->getDesc();
7468   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7469   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7470   // operand is still set to noreg. If needed, set the optional operand's
7471   // register to CPSR, and remove the redundant implicit def.
7472   //
7473   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7474
7475   // Rename pseudo opcodes.
7476   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7477   if (NewOpc) {
7478     const ARMBaseInstrInfo *TII =
7479       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7480     MCID = &TII->get(NewOpc);
7481
7482     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7483            "converted opcode should be the same except for cc_out");
7484
7485     MI->setDesc(*MCID);
7486
7487     // Add the optional cc_out operand
7488     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7489   }
7490   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7491
7492   // Any ARM instruction that sets the 's' bit should specify an optional
7493   // "cc_out" operand in the last operand position.
7494   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7495     assert(!NewOpc && "Optional cc_out operand required");
7496     return;
7497   }
7498   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7499   // since we already have an optional CPSR def.
7500   bool definesCPSR = false;
7501   bool deadCPSR = false;
7502   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7503        i != e; ++i) {
7504     const MachineOperand &MO = MI->getOperand(i);
7505     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7506       definesCPSR = true;
7507       if (MO.isDead())
7508         deadCPSR = true;
7509       MI->RemoveOperand(i);
7510       break;
7511     }
7512   }
7513   if (!definesCPSR) {
7514     assert(!NewOpc && "Optional cc_out operand required");
7515     return;
7516   }
7517   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7518   if (deadCPSR) {
7519     assert(!MI->getOperand(ccOutIdx).getReg() &&
7520            "expect uninitialized optional cc_out operand");
7521     return;
7522   }
7523
7524   // If this instruction was defined with an optional CPSR def and its dag node
7525   // had a live implicit CPSR def, then activate the optional CPSR def.
7526   MachineOperand &MO = MI->getOperand(ccOutIdx);
7527   MO.setReg(ARM::CPSR);
7528   MO.setIsDef(true);
7529 }
7530
7531 //===----------------------------------------------------------------------===//
7532 //                           ARM Optimization Hooks
7533 //===----------------------------------------------------------------------===//
7534
7535 // Helper function that checks if N is a null or all ones constant.
7536 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7537   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7538   if (!C)
7539     return false;
7540   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7541 }
7542
7543 // Return true if N is conditionally 0 or all ones.
7544 // Detects these expressions where cc is an i1 value:
7545 //
7546 //   (select cc 0, y)   [AllOnes=0]
7547 //   (select cc y, 0)   [AllOnes=0]
7548 //   (zext cc)          [AllOnes=0]
7549 //   (sext cc)          [AllOnes=0/1]
7550 //   (select cc -1, y)  [AllOnes=1]
7551 //   (select cc y, -1)  [AllOnes=1]
7552 //
7553 // Invert is set when N is the null/all ones constant when CC is false.
7554 // OtherOp is set to the alternative value of N.
7555 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7556                                        SDValue &CC, bool &Invert,
7557                                        SDValue &OtherOp,
7558                                        SelectionDAG &DAG) {
7559   switch (N->getOpcode()) {
7560   default: return false;
7561   case ISD::SELECT: {
7562     CC = N->getOperand(0);
7563     SDValue N1 = N->getOperand(1);
7564     SDValue N2 = N->getOperand(2);
7565     if (isZeroOrAllOnes(N1, AllOnes)) {
7566       Invert = false;
7567       OtherOp = N2;
7568       return true;
7569     }
7570     if (isZeroOrAllOnes(N2, AllOnes)) {
7571       Invert = true;
7572       OtherOp = N1;
7573       return true;
7574     }
7575     return false;
7576   }
7577   case ISD::ZERO_EXTEND:
7578     // (zext cc) can never be the all ones value.
7579     if (AllOnes)
7580       return false;
7581     // Fall through.
7582   case ISD::SIGN_EXTEND: {
7583     EVT VT = N->getValueType(0);
7584     CC = N->getOperand(0);
7585     if (CC.getValueType() != MVT::i1)
7586       return false;
7587     Invert = !AllOnes;
7588     if (AllOnes)
7589       // When looking for an AllOnes constant, N is an sext, and the 'other'
7590       // value is 0.
7591       OtherOp = DAG.getConstant(0, VT);
7592     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7593       // When looking for a 0 constant, N can be zext or sext.
7594       OtherOp = DAG.getConstant(1, VT);
7595     else
7596       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7597     return true;
7598   }
7599   }
7600 }
7601
7602 // Combine a constant select operand into its use:
7603 //
7604 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7605 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7606 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7607 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7608 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7609 //
7610 // The transform is rejected if the select doesn't have a constant operand that
7611 // is null, or all ones when AllOnes is set.
7612 //
7613 // Also recognize sext/zext from i1:
7614 //
7615 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7616 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7617 //
7618 // These transformations eventually create predicated instructions.
7619 //
7620 // @param N       The node to transform.
7621 // @param Slct    The N operand that is a select.
7622 // @param OtherOp The other N operand (x above).
7623 // @param DCI     Context.
7624 // @param AllOnes Require the select constant to be all ones instead of null.
7625 // @returns The new node, or SDValue() on failure.
7626 static
7627 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7628                             TargetLowering::DAGCombinerInfo &DCI,
7629                             bool AllOnes = false) {
7630   SelectionDAG &DAG = DCI.DAG;
7631   EVT VT = N->getValueType(0);
7632   SDValue NonConstantVal;
7633   SDValue CCOp;
7634   bool SwapSelectOps;
7635   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7636                                   NonConstantVal, DAG))
7637     return SDValue();
7638
7639   // Slct is now know to be the desired identity constant when CC is true.
7640   SDValue TrueVal = OtherOp;
7641   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7642                                  OtherOp, NonConstantVal);
7643   // Unless SwapSelectOps says CC should be false.
7644   if (SwapSelectOps)
7645     std::swap(TrueVal, FalseVal);
7646
7647   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7648                      CCOp, TrueVal, FalseVal);
7649 }
7650
7651 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7652 static
7653 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7654                                        TargetLowering::DAGCombinerInfo &DCI) {
7655   SDValue N0 = N->getOperand(0);
7656   SDValue N1 = N->getOperand(1);
7657   if (N0.getNode()->hasOneUse()) {
7658     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7659     if (Result.getNode())
7660       return Result;
7661   }
7662   if (N1.getNode()->hasOneUse()) {
7663     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7664     if (Result.getNode())
7665       return Result;
7666   }
7667   return SDValue();
7668 }
7669
7670 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7671 // (only after legalization).
7672 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7673                                  TargetLowering::DAGCombinerInfo &DCI,
7674                                  const ARMSubtarget *Subtarget) {
7675
7676   // Only perform optimization if after legalize, and if NEON is available. We
7677   // also expected both operands to be BUILD_VECTORs.
7678   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7679       || N0.getOpcode() != ISD::BUILD_VECTOR
7680       || N1.getOpcode() != ISD::BUILD_VECTOR)
7681     return SDValue();
7682
7683   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7684   EVT VT = N->getValueType(0);
7685   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7686     return SDValue();
7687
7688   // Check that the vector operands are of the right form.
7689   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7690   // operands, where N is the size of the formed vector.
7691   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7692   // index such that we have a pair wise add pattern.
7693
7694   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7695   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7696     return SDValue();
7697   SDValue Vec = N0->getOperand(0)->getOperand(0);
7698   SDNode *V = Vec.getNode();
7699   unsigned nextIndex = 0;
7700
7701   // For each operands to the ADD which are BUILD_VECTORs,
7702   // check to see if each of their operands are an EXTRACT_VECTOR with
7703   // the same vector and appropriate index.
7704   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7705     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7706         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7707
7708       SDValue ExtVec0 = N0->getOperand(i);
7709       SDValue ExtVec1 = N1->getOperand(i);
7710
7711       // First operand is the vector, verify its the same.
7712       if (V != ExtVec0->getOperand(0).getNode() ||
7713           V != ExtVec1->getOperand(0).getNode())
7714         return SDValue();
7715
7716       // Second is the constant, verify its correct.
7717       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7718       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7719
7720       // For the constant, we want to see all the even or all the odd.
7721       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7722           || C1->getZExtValue() != nextIndex+1)
7723         return SDValue();
7724
7725       // Increment index.
7726       nextIndex+=2;
7727     } else
7728       return SDValue();
7729   }
7730
7731   // Create VPADDL node.
7732   SelectionDAG &DAG = DCI.DAG;
7733   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7734
7735   // Build operand list.
7736   SmallVector<SDValue, 8> Ops;
7737   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7738                                 TLI.getPointerTy()));
7739
7740   // Input is the vector.
7741   Ops.push_back(Vec);
7742
7743   // Get widened type and narrowed type.
7744   MVT widenType;
7745   unsigned numElem = VT.getVectorNumElements();
7746   
7747   EVT inputLaneType = Vec.getValueType().getVectorElementType();
7748   switch (inputLaneType.getSimpleVT().SimpleTy) {
7749     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7750     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7751     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7752     default:
7753       llvm_unreachable("Invalid vector element type for padd optimization.");
7754   }
7755
7756   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7757   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7758   return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7759 }
7760
7761 static SDValue findMUL_LOHI(SDValue V) {
7762   if (V->getOpcode() == ISD::UMUL_LOHI ||
7763       V->getOpcode() == ISD::SMUL_LOHI)
7764     return V;
7765   return SDValue();
7766 }
7767
7768 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7769                                      TargetLowering::DAGCombinerInfo &DCI,
7770                                      const ARMSubtarget *Subtarget) {
7771
7772   if (Subtarget->isThumb1Only()) return SDValue();
7773
7774   // Only perform the checks after legalize when the pattern is available.
7775   if (DCI.isBeforeLegalize()) return SDValue();
7776
7777   // Look for multiply add opportunities.
7778   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7779   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7780   // a glue link from the first add to the second add.
7781   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7782   // a S/UMLAL instruction.
7783   //          loAdd   UMUL_LOHI
7784   //            \    / :lo    \ :hi
7785   //             \  /          \          [no multiline comment]
7786   //              ADDC         |  hiAdd
7787   //                 \ :glue  /  /
7788   //                  \      /  /
7789   //                    ADDE
7790   //
7791   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7792   SDValue AddcOp0 = AddcNode->getOperand(0);
7793   SDValue AddcOp1 = AddcNode->getOperand(1);
7794
7795   // Check if the two operands are from the same mul_lohi node.
7796   if (AddcOp0.getNode() == AddcOp1.getNode())
7797     return SDValue();
7798
7799   assert(AddcNode->getNumValues() == 2 &&
7800          AddcNode->getValueType(0) == MVT::i32 &&
7801          "Expect ADDC with two result values. First: i32");
7802
7803   // Check that we have a glued ADDC node.
7804   if (AddcNode->getValueType(1) != MVT::Glue)
7805     return SDValue();
7806
7807   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7808   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7809       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7810       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7811       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7812     return SDValue();
7813
7814   // Look for the glued ADDE.
7815   SDNode* AddeNode = AddcNode->getGluedUser();
7816   if (!AddeNode)
7817     return SDValue();
7818
7819   // Make sure it is really an ADDE.
7820   if (AddeNode->getOpcode() != ISD::ADDE)
7821     return SDValue();
7822
7823   assert(AddeNode->getNumOperands() == 3 &&
7824          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7825          "ADDE node has the wrong inputs");
7826
7827   // Check for the triangle shape.
7828   SDValue AddeOp0 = AddeNode->getOperand(0);
7829   SDValue AddeOp1 = AddeNode->getOperand(1);
7830
7831   // Make sure that the ADDE operands are not coming from the same node.
7832   if (AddeOp0.getNode() == AddeOp1.getNode())
7833     return SDValue();
7834
7835   // Find the MUL_LOHI node walking up ADDE's operands.
7836   bool IsLeftOperandMUL = false;
7837   SDValue MULOp = findMUL_LOHI(AddeOp0);
7838   if (MULOp == SDValue())
7839    MULOp = findMUL_LOHI(AddeOp1);
7840   else
7841     IsLeftOperandMUL = true;
7842   if (MULOp == SDValue())
7843      return SDValue();
7844
7845   // Figure out the right opcode.
7846   unsigned Opc = MULOp->getOpcode();
7847   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7848
7849   // Figure out the high and low input values to the MLAL node.
7850   SDValue* HiMul = &MULOp;
7851   SDValue* HiAdd = nullptr;
7852   SDValue* LoMul = nullptr;
7853   SDValue* LowAdd = nullptr;
7854
7855   if (IsLeftOperandMUL)
7856     HiAdd = &AddeOp1;
7857   else
7858     HiAdd = &AddeOp0;
7859
7860
7861   if (AddcOp0->getOpcode() == Opc) {
7862     LoMul = &AddcOp0;
7863     LowAdd = &AddcOp1;
7864   }
7865   if (AddcOp1->getOpcode() == Opc) {
7866     LoMul = &AddcOp1;
7867     LowAdd = &AddcOp0;
7868   }
7869
7870   if (!LoMul)
7871     return SDValue();
7872
7873   if (LoMul->getNode() != HiMul->getNode())
7874     return SDValue();
7875
7876   // Create the merged node.
7877   SelectionDAG &DAG = DCI.DAG;
7878
7879   // Build operand list.
7880   SmallVector<SDValue, 8> Ops;
7881   Ops.push_back(LoMul->getOperand(0));
7882   Ops.push_back(LoMul->getOperand(1));
7883   Ops.push_back(*LowAdd);
7884   Ops.push_back(*HiAdd);
7885
7886   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
7887                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
7888
7889   // Replace the ADDs' nodes uses by the MLA node's values.
7890   SDValue HiMLALResult(MLALNode.getNode(), 1);
7891   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7892
7893   SDValue LoMLALResult(MLALNode.getNode(), 0);
7894   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7895
7896   // Return original node to notify the driver to stop replacing.
7897   SDValue resNode(AddcNode, 0);
7898   return resNode;
7899 }
7900
7901 /// PerformADDCCombine - Target-specific dag combine transform from
7902 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7903 static SDValue PerformADDCCombine(SDNode *N,
7904                                  TargetLowering::DAGCombinerInfo &DCI,
7905                                  const ARMSubtarget *Subtarget) {
7906
7907   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7908
7909 }
7910
7911 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7912 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
7913 /// called with the default operands, and if that fails, with commuted
7914 /// operands.
7915 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7916                                           TargetLowering::DAGCombinerInfo &DCI,
7917                                           const ARMSubtarget *Subtarget){
7918
7919   // Attempt to create vpaddl for this add.
7920   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7921   if (Result.getNode())
7922     return Result;
7923
7924   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7925   if (N0.getNode()->hasOneUse()) {
7926     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7927     if (Result.getNode()) return Result;
7928   }
7929   return SDValue();
7930 }
7931
7932 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7933 ///
7934 static SDValue PerformADDCombine(SDNode *N,
7935                                  TargetLowering::DAGCombinerInfo &DCI,
7936                                  const ARMSubtarget *Subtarget) {
7937   SDValue N0 = N->getOperand(0);
7938   SDValue N1 = N->getOperand(1);
7939
7940   // First try with the default operand order.
7941   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7942   if (Result.getNode())
7943     return Result;
7944
7945   // If that didn't work, try again with the operands commuted.
7946   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7947 }
7948
7949 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7950 ///
7951 static SDValue PerformSUBCombine(SDNode *N,
7952                                  TargetLowering::DAGCombinerInfo &DCI) {
7953   SDValue N0 = N->getOperand(0);
7954   SDValue N1 = N->getOperand(1);
7955
7956   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7957   if (N1.getNode()->hasOneUse()) {
7958     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7959     if (Result.getNode()) return Result;
7960   }
7961
7962   return SDValue();
7963 }
7964
7965 /// PerformVMULCombine
7966 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7967 /// special multiplier accumulator forwarding.
7968 ///   vmul d3, d0, d2
7969 ///   vmla d3, d1, d2
7970 /// is faster than
7971 ///   vadd d3, d0, d1
7972 ///   vmul d3, d3, d2
7973 //  However, for (A + B) * (A + B),
7974 //    vadd d2, d0, d1
7975 //    vmul d3, d0, d2
7976 //    vmla d3, d1, d2
7977 //  is slower than
7978 //    vadd d2, d0, d1
7979 //    vmul d3, d2, d2
7980 static SDValue PerformVMULCombine(SDNode *N,
7981                                   TargetLowering::DAGCombinerInfo &DCI,
7982                                   const ARMSubtarget *Subtarget) {
7983   if (!Subtarget->hasVMLxForwarding())
7984     return SDValue();
7985
7986   SelectionDAG &DAG = DCI.DAG;
7987   SDValue N0 = N->getOperand(0);
7988   SDValue N1 = N->getOperand(1);
7989   unsigned Opcode = N0.getOpcode();
7990   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7991       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7992     Opcode = N1.getOpcode();
7993     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7994         Opcode != ISD::FADD && Opcode != ISD::FSUB)
7995       return SDValue();
7996     std::swap(N0, N1);
7997   }
7998
7999   if (N0 == N1)
8000     return SDValue();
8001
8002   EVT VT = N->getValueType(0);
8003   SDLoc DL(N);
8004   SDValue N00 = N0->getOperand(0);
8005   SDValue N01 = N0->getOperand(1);
8006   return DAG.getNode(Opcode, DL, VT,
8007                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8008                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8009 }
8010
8011 static SDValue PerformMULCombine(SDNode *N,
8012                                  TargetLowering::DAGCombinerInfo &DCI,
8013                                  const ARMSubtarget *Subtarget) {
8014   SelectionDAG &DAG = DCI.DAG;
8015
8016   if (Subtarget->isThumb1Only())
8017     return SDValue();
8018
8019   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8020     return SDValue();
8021
8022   EVT VT = N->getValueType(0);
8023   if (VT.is64BitVector() || VT.is128BitVector())
8024     return PerformVMULCombine(N, DCI, Subtarget);
8025   if (VT != MVT::i32)
8026     return SDValue();
8027
8028   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8029   if (!C)
8030     return SDValue();
8031
8032   int64_t MulAmt = C->getSExtValue();
8033   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8034
8035   ShiftAmt = ShiftAmt & (32 - 1);
8036   SDValue V = N->getOperand(0);
8037   SDLoc DL(N);
8038
8039   SDValue Res;
8040   MulAmt >>= ShiftAmt;
8041
8042   if (MulAmt >= 0) {
8043     if (isPowerOf2_32(MulAmt - 1)) {
8044       // (mul x, 2^N + 1) => (add (shl x, N), x)
8045       Res = DAG.getNode(ISD::ADD, DL, VT,
8046                         V,
8047                         DAG.getNode(ISD::SHL, DL, VT,
8048                                     V,
8049                                     DAG.getConstant(Log2_32(MulAmt - 1),
8050                                                     MVT::i32)));
8051     } else if (isPowerOf2_32(MulAmt + 1)) {
8052       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8053       Res = DAG.getNode(ISD::SUB, DL, VT,
8054                         DAG.getNode(ISD::SHL, DL, VT,
8055                                     V,
8056                                     DAG.getConstant(Log2_32(MulAmt + 1),
8057                                                     MVT::i32)),
8058                         V);
8059     } else
8060       return SDValue();
8061   } else {
8062     uint64_t MulAmtAbs = -MulAmt;
8063     if (isPowerOf2_32(MulAmtAbs + 1)) {
8064       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8065       Res = DAG.getNode(ISD::SUB, DL, VT,
8066                         V,
8067                         DAG.getNode(ISD::SHL, DL, VT,
8068                                     V,
8069                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8070                                                     MVT::i32)));
8071     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8072       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8073       Res = DAG.getNode(ISD::ADD, DL, VT,
8074                         V,
8075                         DAG.getNode(ISD::SHL, DL, VT,
8076                                     V,
8077                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8078                                                     MVT::i32)));
8079       Res = DAG.getNode(ISD::SUB, DL, VT,
8080                         DAG.getConstant(0, MVT::i32),Res);
8081
8082     } else
8083       return SDValue();
8084   }
8085
8086   if (ShiftAmt != 0)
8087     Res = DAG.getNode(ISD::SHL, DL, VT,
8088                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8089
8090   // Do not add new nodes to DAG combiner worklist.
8091   DCI.CombineTo(N, Res, false);
8092   return SDValue();
8093 }
8094
8095 static SDValue PerformANDCombine(SDNode *N,
8096                                  TargetLowering::DAGCombinerInfo &DCI,
8097                                  const ARMSubtarget *Subtarget) {
8098
8099   // Attempt to use immediate-form VBIC
8100   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8101   SDLoc dl(N);
8102   EVT VT = N->getValueType(0);
8103   SelectionDAG &DAG = DCI.DAG;
8104
8105   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8106     return SDValue();
8107
8108   APInt SplatBits, SplatUndef;
8109   unsigned SplatBitSize;
8110   bool HasAnyUndefs;
8111   if (BVN &&
8112       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8113     if (SplatBitSize <= 64) {
8114       EVT VbicVT;
8115       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8116                                       SplatUndef.getZExtValue(), SplatBitSize,
8117                                       DAG, VbicVT, VT.is128BitVector(),
8118                                       OtherModImm);
8119       if (Val.getNode()) {
8120         SDValue Input =
8121           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8122         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8123         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8124       }
8125     }
8126   }
8127
8128   if (!Subtarget->isThumb1Only()) {
8129     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8130     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8131     if (Result.getNode())
8132       return Result;
8133   }
8134
8135   return SDValue();
8136 }
8137
8138 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8139 static SDValue PerformORCombine(SDNode *N,
8140                                 TargetLowering::DAGCombinerInfo &DCI,
8141                                 const ARMSubtarget *Subtarget) {
8142   // Attempt to use immediate-form VORR
8143   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8144   SDLoc dl(N);
8145   EVT VT = N->getValueType(0);
8146   SelectionDAG &DAG = DCI.DAG;
8147
8148   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8149     return SDValue();
8150
8151   APInt SplatBits, SplatUndef;
8152   unsigned SplatBitSize;
8153   bool HasAnyUndefs;
8154   if (BVN && Subtarget->hasNEON() &&
8155       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8156     if (SplatBitSize <= 64) {
8157       EVT VorrVT;
8158       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8159                                       SplatUndef.getZExtValue(), SplatBitSize,
8160                                       DAG, VorrVT, VT.is128BitVector(),
8161                                       OtherModImm);
8162       if (Val.getNode()) {
8163         SDValue Input =
8164           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8165         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8166         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8167       }
8168     }
8169   }
8170
8171   if (!Subtarget->isThumb1Only()) {
8172     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8173     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8174     if (Result.getNode())
8175       return Result;
8176   }
8177
8178   // The code below optimizes (or (and X, Y), Z).
8179   // The AND operand needs to have a single user to make these optimizations
8180   // profitable.
8181   SDValue N0 = N->getOperand(0);
8182   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8183     return SDValue();
8184   SDValue N1 = N->getOperand(1);
8185
8186   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8187   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8188       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8189     APInt SplatUndef;
8190     unsigned SplatBitSize;
8191     bool HasAnyUndefs;
8192
8193     APInt SplatBits0, SplatBits1;
8194     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8195     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8196     // Ensure that the second operand of both ands are constants
8197     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8198                                       HasAnyUndefs) && !HasAnyUndefs) {
8199         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8200                                           HasAnyUndefs) && !HasAnyUndefs) {
8201             // Ensure that the bit width of the constants are the same and that
8202             // the splat arguments are logical inverses as per the pattern we
8203             // are trying to simplify.
8204             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8205                 SplatBits0 == ~SplatBits1) {
8206                 // Canonicalize the vector type to make instruction selection
8207                 // simpler.
8208                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8209                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8210                                              N0->getOperand(1),
8211                                              N0->getOperand(0),
8212                                              N1->getOperand(0));
8213                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8214             }
8215         }
8216     }
8217   }
8218
8219   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8220   // reasonable.
8221
8222   // BFI is only available on V6T2+
8223   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8224     return SDValue();
8225
8226   SDLoc DL(N);
8227   // 1) or (and A, mask), val => ARMbfi A, val, mask
8228   //      iff (val & mask) == val
8229   //
8230   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8231   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8232   //          && mask == ~mask2
8233   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8234   //          && ~mask == mask2
8235   //  (i.e., copy a bitfield value into another bitfield of the same width)
8236
8237   if (VT != MVT::i32)
8238     return SDValue();
8239
8240   SDValue N00 = N0.getOperand(0);
8241
8242   // The value and the mask need to be constants so we can verify this is
8243   // actually a bitfield set. If the mask is 0xffff, we can do better
8244   // via a movt instruction, so don't use BFI in that case.
8245   SDValue MaskOp = N0.getOperand(1);
8246   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8247   if (!MaskC)
8248     return SDValue();
8249   unsigned Mask = MaskC->getZExtValue();
8250   if (Mask == 0xffff)
8251     return SDValue();
8252   SDValue Res;
8253   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8254   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8255   if (N1C) {
8256     unsigned Val = N1C->getZExtValue();
8257     if ((Val & ~Mask) != Val)
8258       return SDValue();
8259
8260     if (ARM::isBitFieldInvertedMask(Mask)) {
8261       Val >>= countTrailingZeros(~Mask);
8262
8263       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8264                         DAG.getConstant(Val, MVT::i32),
8265                         DAG.getConstant(Mask, MVT::i32));
8266
8267       // Do not add new nodes to DAG combiner worklist.
8268       DCI.CombineTo(N, Res, false);
8269       return SDValue();
8270     }
8271   } else if (N1.getOpcode() == ISD::AND) {
8272     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8273     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8274     if (!N11C)
8275       return SDValue();
8276     unsigned Mask2 = N11C->getZExtValue();
8277
8278     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8279     // as is to match.
8280     if (ARM::isBitFieldInvertedMask(Mask) &&
8281         (Mask == ~Mask2)) {
8282       // The pack halfword instruction works better for masks that fit it,
8283       // so use that when it's available.
8284       if (Subtarget->hasT2ExtractPack() &&
8285           (Mask == 0xffff || Mask == 0xffff0000))
8286         return SDValue();
8287       // 2a
8288       unsigned amt = countTrailingZeros(Mask2);
8289       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8290                         DAG.getConstant(amt, MVT::i32));
8291       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8292                         DAG.getConstant(Mask, MVT::i32));
8293       // Do not add new nodes to DAG combiner worklist.
8294       DCI.CombineTo(N, Res, false);
8295       return SDValue();
8296     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8297                (~Mask == Mask2)) {
8298       // The pack halfword instruction works better for masks that fit it,
8299       // so use that when it's available.
8300       if (Subtarget->hasT2ExtractPack() &&
8301           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8302         return SDValue();
8303       // 2b
8304       unsigned lsb = countTrailingZeros(Mask);
8305       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8306                         DAG.getConstant(lsb, MVT::i32));
8307       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8308                         DAG.getConstant(Mask2, MVT::i32));
8309       // Do not add new nodes to DAG combiner worklist.
8310       DCI.CombineTo(N, Res, false);
8311       return SDValue();
8312     }
8313   }
8314
8315   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8316       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8317       ARM::isBitFieldInvertedMask(~Mask)) {
8318     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8319     // where lsb(mask) == #shamt and masked bits of B are known zero.
8320     SDValue ShAmt = N00.getOperand(1);
8321     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8322     unsigned LSB = countTrailingZeros(Mask);
8323     if (ShAmtC != LSB)
8324       return SDValue();
8325
8326     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8327                       DAG.getConstant(~Mask, MVT::i32));
8328
8329     // Do not add new nodes to DAG combiner worklist.
8330     DCI.CombineTo(N, Res, false);
8331   }
8332
8333   return SDValue();
8334 }
8335
8336 static SDValue PerformXORCombine(SDNode *N,
8337                                  TargetLowering::DAGCombinerInfo &DCI,
8338                                  const ARMSubtarget *Subtarget) {
8339   EVT VT = N->getValueType(0);
8340   SelectionDAG &DAG = DCI.DAG;
8341
8342   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8343     return SDValue();
8344
8345   if (!Subtarget->isThumb1Only()) {
8346     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8347     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8348     if (Result.getNode())
8349       return Result;
8350   }
8351
8352   return SDValue();
8353 }
8354
8355 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8356 /// the bits being cleared by the AND are not demanded by the BFI.
8357 static SDValue PerformBFICombine(SDNode *N,
8358                                  TargetLowering::DAGCombinerInfo &DCI) {
8359   SDValue N1 = N->getOperand(1);
8360   if (N1.getOpcode() == ISD::AND) {
8361     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8362     if (!N11C)
8363       return SDValue();
8364     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8365     unsigned LSB = countTrailingZeros(~InvMask);
8366     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8367     unsigned Mask = (1 << Width)-1;
8368     unsigned Mask2 = N11C->getZExtValue();
8369     if ((Mask & (~Mask2)) == 0)
8370       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8371                              N->getOperand(0), N1.getOperand(0),
8372                              N->getOperand(2));
8373   }
8374   return SDValue();
8375 }
8376
8377 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8378 /// ARMISD::VMOVRRD.
8379 static SDValue PerformVMOVRRDCombine(SDNode *N,
8380                                      TargetLowering::DAGCombinerInfo &DCI) {
8381   // vmovrrd(vmovdrr x, y) -> x,y
8382   SDValue InDouble = N->getOperand(0);
8383   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8384     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8385
8386   // vmovrrd(load f64) -> (load i32), (load i32)
8387   SDNode *InNode = InDouble.getNode();
8388   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8389       InNode->getValueType(0) == MVT::f64 &&
8390       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8391       !cast<LoadSDNode>(InNode)->isVolatile()) {
8392     // TODO: Should this be done for non-FrameIndex operands?
8393     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8394
8395     SelectionDAG &DAG = DCI.DAG;
8396     SDLoc DL(LD);
8397     SDValue BasePtr = LD->getBasePtr();
8398     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8399                                  LD->getPointerInfo(), LD->isVolatile(),
8400                                  LD->isNonTemporal(), LD->isInvariant(),
8401                                  LD->getAlignment());
8402
8403     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8404                                     DAG.getConstant(4, MVT::i32));
8405     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8406                                  LD->getPointerInfo(), LD->isVolatile(),
8407                                  LD->isNonTemporal(), LD->isInvariant(),
8408                                  std::min(4U, LD->getAlignment() / 2));
8409
8410     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8411     if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8412       std::swap (NewLD1, NewLD2);
8413     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8414     DCI.RemoveFromWorklist(LD);
8415     DAG.DeleteNode(LD);
8416     return Result;
8417   }
8418
8419   return SDValue();
8420 }
8421
8422 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8423 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8424 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8425   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8426   SDValue Op0 = N->getOperand(0);
8427   SDValue Op1 = N->getOperand(1);
8428   if (Op0.getOpcode() == ISD::BITCAST)
8429     Op0 = Op0.getOperand(0);
8430   if (Op1.getOpcode() == ISD::BITCAST)
8431     Op1 = Op1.getOperand(0);
8432   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8433       Op0.getNode() == Op1.getNode() &&
8434       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8435     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8436                        N->getValueType(0), Op0.getOperand(0));
8437   return SDValue();
8438 }
8439
8440 /// PerformSTORECombine - Target-specific dag combine xforms for
8441 /// ISD::STORE.
8442 static SDValue PerformSTORECombine(SDNode *N,
8443                                    TargetLowering::DAGCombinerInfo &DCI) {
8444   StoreSDNode *St = cast<StoreSDNode>(N);
8445   if (St->isVolatile())
8446     return SDValue();
8447
8448   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8449   // pack all of the elements in one place.  Next, store to memory in fewer
8450   // chunks.
8451   SDValue StVal = St->getValue();
8452   EVT VT = StVal.getValueType();
8453   if (St->isTruncatingStore() && VT.isVector()) {
8454     SelectionDAG &DAG = DCI.DAG;
8455     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8456     EVT StVT = St->getMemoryVT();
8457     unsigned NumElems = VT.getVectorNumElements();
8458     assert(StVT != VT && "Cannot truncate to the same type");
8459     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8460     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8461
8462     // From, To sizes and ElemCount must be pow of two
8463     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8464
8465     // We are going to use the original vector elt for storing.
8466     // Accumulated smaller vector elements must be a multiple of the store size.
8467     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8468
8469     unsigned SizeRatio  = FromEltSz / ToEltSz;
8470     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8471
8472     // Create a type on which we perform the shuffle.
8473     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8474                                      NumElems*SizeRatio);
8475     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8476
8477     SDLoc DL(St);
8478     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8479     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8480     for (unsigned i = 0; i < NumElems; ++i)
8481       ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
8482
8483     // Can't shuffle using an illegal type.
8484     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8485
8486     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8487                                 DAG.getUNDEF(WideVec.getValueType()),
8488                                 ShuffleVec.data());
8489     // At this point all of the data is stored at the bottom of the
8490     // register. We now need to save it to mem.
8491
8492     // Find the largest store unit
8493     MVT StoreType = MVT::i8;
8494     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8495          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8496       MVT Tp = (MVT::SimpleValueType)tp;
8497       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8498         StoreType = Tp;
8499     }
8500     // Didn't find a legal store type.
8501     if (!TLI.isTypeLegal(StoreType))
8502       return SDValue();
8503
8504     // Bitcast the original vector into a vector of store-size units
8505     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8506             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8507     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8508     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8509     SmallVector<SDValue, 8> Chains;
8510     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8511                                         TLI.getPointerTy());
8512     SDValue BasePtr = St->getBasePtr();
8513
8514     // Perform one or more big stores into memory.
8515     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8516     for (unsigned I = 0; I < E; I++) {
8517       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8518                                    StoreType, ShuffWide,
8519                                    DAG.getIntPtrConstant(I));
8520       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8521                                 St->getPointerInfo(), St->isVolatile(),
8522                                 St->isNonTemporal(), St->getAlignment());
8523       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8524                             Increment);
8525       Chains.push_back(Ch);
8526     }
8527     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
8528   }
8529
8530   if (!ISD::isNormalStore(St))
8531     return SDValue();
8532
8533   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8534   // ARM stores of arguments in the same cache line.
8535   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8536       StVal.getNode()->hasOneUse()) {
8537     SelectionDAG  &DAG = DCI.DAG;
8538     bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
8539     SDLoc DL(St);
8540     SDValue BasePtr = St->getBasePtr();
8541     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8542                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
8543                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
8544                                   St->isNonTemporal(), St->getAlignment());
8545
8546     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8547                                     DAG.getConstant(4, MVT::i32));
8548     return DAG.getStore(NewST1.getValue(0), DL,
8549                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
8550                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8551                         St->isNonTemporal(),
8552                         std::min(4U, St->getAlignment() / 2));
8553   }
8554
8555   if (StVal.getValueType() != MVT::i64 ||
8556       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8557     return SDValue();
8558
8559   // Bitcast an i64 store extracted from a vector to f64.
8560   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8561   SelectionDAG &DAG = DCI.DAG;
8562   SDLoc dl(StVal);
8563   SDValue IntVec = StVal.getOperand(0);
8564   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8565                                  IntVec.getValueType().getVectorNumElements());
8566   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8567   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8568                                Vec, StVal.getOperand(1));
8569   dl = SDLoc(N);
8570   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8571   // Make the DAGCombiner fold the bitcasts.
8572   DCI.AddToWorklist(Vec.getNode());
8573   DCI.AddToWorklist(ExtElt.getNode());
8574   DCI.AddToWorklist(V.getNode());
8575   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8576                       St->getPointerInfo(), St->isVolatile(),
8577                       St->isNonTemporal(), St->getAlignment(),
8578                       St->getTBAAInfo());
8579 }
8580
8581 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8582 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8583 /// i64 vector to have f64 elements, since the value can then be loaded
8584 /// directly into a VFP register.
8585 static bool hasNormalLoadOperand(SDNode *N) {
8586   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8587   for (unsigned i = 0; i < NumElts; ++i) {
8588     SDNode *Elt = N->getOperand(i).getNode();
8589     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8590       return true;
8591   }
8592   return false;
8593 }
8594
8595 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8596 /// ISD::BUILD_VECTOR.
8597 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8598                                           TargetLowering::DAGCombinerInfo &DCI){
8599   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8600   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8601   // into a pair of GPRs, which is fine when the value is used as a scalar,
8602   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8603   SelectionDAG &DAG = DCI.DAG;
8604   if (N->getNumOperands() == 2) {
8605     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8606     if (RV.getNode())
8607       return RV;
8608   }
8609
8610   // Load i64 elements as f64 values so that type legalization does not split
8611   // them up into i32 values.
8612   EVT VT = N->getValueType(0);
8613   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8614     return SDValue();
8615   SDLoc dl(N);
8616   SmallVector<SDValue, 8> Ops;
8617   unsigned NumElts = VT.getVectorNumElements();
8618   for (unsigned i = 0; i < NumElts; ++i) {
8619     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8620     Ops.push_back(V);
8621     // Make the DAGCombiner fold the bitcast.
8622     DCI.AddToWorklist(V.getNode());
8623   }
8624   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8625   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8626   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8627 }
8628
8629 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8630 static SDValue
8631 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8632   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8633   // At that time, we may have inserted bitcasts from integer to float.
8634   // If these bitcasts have survived DAGCombine, change the lowering of this
8635   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8636   // force to use floating point types.
8637
8638   // Make sure we can change the type of the vector.
8639   // This is possible iff:
8640   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8641   //    1.1. Vector is used only once.
8642   //    1.2. Use is a bit convert to an integer type.
8643   // 2. The size of its operands are 32-bits (64-bits are not legal).
8644   EVT VT = N->getValueType(0);
8645   EVT EltVT = VT.getVectorElementType();
8646
8647   // Check 1.1. and 2.
8648   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8649     return SDValue();
8650
8651   // By construction, the input type must be float.
8652   assert(EltVT == MVT::f32 && "Unexpected type!");
8653
8654   // Check 1.2.
8655   SDNode *Use = *N->use_begin();
8656   if (Use->getOpcode() != ISD::BITCAST ||
8657       Use->getValueType(0).isFloatingPoint())
8658     return SDValue();
8659
8660   // Check profitability.
8661   // Model is, if more than half of the relevant operands are bitcast from
8662   // i32, turn the build_vector into a sequence of insert_vector_elt.
8663   // Relevant operands are everything that is not statically
8664   // (i.e., at compile time) bitcasted.
8665   unsigned NumOfBitCastedElts = 0;
8666   unsigned NumElts = VT.getVectorNumElements();
8667   unsigned NumOfRelevantElts = NumElts;
8668   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8669     SDValue Elt = N->getOperand(Idx);
8670     if (Elt->getOpcode() == ISD::BITCAST) {
8671       // Assume only bit cast to i32 will go away.
8672       if (Elt->getOperand(0).getValueType() == MVT::i32)
8673         ++NumOfBitCastedElts;
8674     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8675       // Constants are statically casted, thus do not count them as
8676       // relevant operands.
8677       --NumOfRelevantElts;
8678   }
8679
8680   // Check if more than half of the elements require a non-free bitcast.
8681   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8682     return SDValue();
8683
8684   SelectionDAG &DAG = DCI.DAG;
8685   // Create the new vector type.
8686   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8687   // Check if the type is legal.
8688   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8689   if (!TLI.isTypeLegal(VecVT))
8690     return SDValue();
8691
8692   // Combine:
8693   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8694   // => BITCAST INSERT_VECTOR_ELT
8695   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8696   //                      (BITCAST EN), N.
8697   SDValue Vec = DAG.getUNDEF(VecVT);
8698   SDLoc dl(N);
8699   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8700     SDValue V = N->getOperand(Idx);
8701     if (V.getOpcode() == ISD::UNDEF)
8702       continue;
8703     if (V.getOpcode() == ISD::BITCAST &&
8704         V->getOperand(0).getValueType() == MVT::i32)
8705       // Fold obvious case.
8706       V = V.getOperand(0);
8707     else {
8708       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8709       // Make the DAGCombiner fold the bitcasts.
8710       DCI.AddToWorklist(V.getNode());
8711     }
8712     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8713     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8714   }
8715   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8716   // Make the DAGCombiner fold the bitcasts.
8717   DCI.AddToWorklist(Vec.getNode());
8718   return Vec;
8719 }
8720
8721 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8722 /// ISD::INSERT_VECTOR_ELT.
8723 static SDValue PerformInsertEltCombine(SDNode *N,
8724                                        TargetLowering::DAGCombinerInfo &DCI) {
8725   // Bitcast an i64 load inserted into a vector to f64.
8726   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8727   EVT VT = N->getValueType(0);
8728   SDNode *Elt = N->getOperand(1).getNode();
8729   if (VT.getVectorElementType() != MVT::i64 ||
8730       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8731     return SDValue();
8732
8733   SelectionDAG &DAG = DCI.DAG;
8734   SDLoc dl(N);
8735   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8736                                  VT.getVectorNumElements());
8737   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8738   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8739   // Make the DAGCombiner fold the bitcasts.
8740   DCI.AddToWorklist(Vec.getNode());
8741   DCI.AddToWorklist(V.getNode());
8742   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8743                                Vec, V, N->getOperand(2));
8744   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8745 }
8746
8747 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8748 /// ISD::VECTOR_SHUFFLE.
8749 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8750   // The LLVM shufflevector instruction does not require the shuffle mask
8751   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8752   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8753   // operands do not match the mask length, they are extended by concatenating
8754   // them with undef vectors.  That is probably the right thing for other
8755   // targets, but for NEON it is better to concatenate two double-register
8756   // size vector operands into a single quad-register size vector.  Do that
8757   // transformation here:
8758   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8759   //   shuffle(concat(v1, v2), undef)
8760   SDValue Op0 = N->getOperand(0);
8761   SDValue Op1 = N->getOperand(1);
8762   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8763       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8764       Op0.getNumOperands() != 2 ||
8765       Op1.getNumOperands() != 2)
8766     return SDValue();
8767   SDValue Concat0Op1 = Op0.getOperand(1);
8768   SDValue Concat1Op1 = Op1.getOperand(1);
8769   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8770       Concat1Op1.getOpcode() != ISD::UNDEF)
8771     return SDValue();
8772   // Skip the transformation if any of the types are illegal.
8773   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8774   EVT VT = N->getValueType(0);
8775   if (!TLI.isTypeLegal(VT) ||
8776       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8777       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8778     return SDValue();
8779
8780   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8781                                   Op0.getOperand(0), Op1.getOperand(0));
8782   // Translate the shuffle mask.
8783   SmallVector<int, 16> NewMask;
8784   unsigned NumElts = VT.getVectorNumElements();
8785   unsigned HalfElts = NumElts/2;
8786   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8787   for (unsigned n = 0; n < NumElts; ++n) {
8788     int MaskElt = SVN->getMaskElt(n);
8789     int NewElt = -1;
8790     if (MaskElt < (int)HalfElts)
8791       NewElt = MaskElt;
8792     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8793       NewElt = HalfElts + MaskElt - NumElts;
8794     NewMask.push_back(NewElt);
8795   }
8796   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8797                               DAG.getUNDEF(VT), NewMask.data());
8798 }
8799
8800 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8801 /// NEON load/store intrinsics to merge base address updates.
8802 static SDValue CombineBaseUpdate(SDNode *N,
8803                                  TargetLowering::DAGCombinerInfo &DCI) {
8804   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8805     return SDValue();
8806
8807   SelectionDAG &DAG = DCI.DAG;
8808   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8809                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8810   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8811   SDValue Addr = N->getOperand(AddrOpIdx);
8812
8813   // Search for a use of the address operand that is an increment.
8814   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8815          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8816     SDNode *User = *UI;
8817     if (User->getOpcode() != ISD::ADD ||
8818         UI.getUse().getResNo() != Addr.getResNo())
8819       continue;
8820
8821     // Check that the add is independent of the load/store.  Otherwise, folding
8822     // it would create a cycle.
8823     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8824       continue;
8825
8826     // Find the new opcode for the updating load/store.
8827     bool isLoad = true;
8828     bool isLaneOp = false;
8829     unsigned NewOpc = 0;
8830     unsigned NumVecs = 0;
8831     if (isIntrinsic) {
8832       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8833       switch (IntNo) {
8834       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8835       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8836         NumVecs = 1; break;
8837       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8838         NumVecs = 2; break;
8839       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8840         NumVecs = 3; break;
8841       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8842         NumVecs = 4; break;
8843       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8844         NumVecs = 2; isLaneOp = true; break;
8845       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8846         NumVecs = 3; isLaneOp = true; break;
8847       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8848         NumVecs = 4; isLaneOp = true; break;
8849       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8850         NumVecs = 1; isLoad = false; break;
8851       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8852         NumVecs = 2; isLoad = false; break;
8853       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8854         NumVecs = 3; isLoad = false; break;
8855       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8856         NumVecs = 4; isLoad = false; break;
8857       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8858         NumVecs = 2; isLoad = false; isLaneOp = true; break;
8859       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8860         NumVecs = 3; isLoad = false; isLaneOp = true; break;
8861       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8862         NumVecs = 4; isLoad = false; isLaneOp = true; break;
8863       }
8864     } else {
8865       isLaneOp = true;
8866       switch (N->getOpcode()) {
8867       default: llvm_unreachable("unexpected opcode for Neon base update");
8868       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8869       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8870       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8871       }
8872     }
8873
8874     // Find the size of memory referenced by the load/store.
8875     EVT VecTy;
8876     if (isLoad)
8877       VecTy = N->getValueType(0);
8878     else
8879       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8880     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8881     if (isLaneOp)
8882       NumBytes /= VecTy.getVectorNumElements();
8883
8884     // If the increment is a constant, it must match the memory ref size.
8885     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8886     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8887       uint64_t IncVal = CInc->getZExtValue();
8888       if (IncVal != NumBytes)
8889         continue;
8890     } else if (NumBytes >= 3 * 16) {
8891       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8892       // separate instructions that make it harder to use a non-constant update.
8893       continue;
8894     }
8895
8896     // Create the new updating load/store node.
8897     EVT Tys[6];
8898     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8899     unsigned n;
8900     for (n = 0; n < NumResultVecs; ++n)
8901       Tys[n] = VecTy;
8902     Tys[n++] = MVT::i32;
8903     Tys[n] = MVT::Other;
8904     SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumResultVecs+2));
8905     SmallVector<SDValue, 8> Ops;
8906     Ops.push_back(N->getOperand(0)); // incoming chain
8907     Ops.push_back(N->getOperand(AddrOpIdx));
8908     Ops.push_back(Inc);
8909     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8910       Ops.push_back(N->getOperand(i));
8911     }
8912     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8913     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8914                                            Ops, MemInt->getMemoryVT(),
8915                                            MemInt->getMemOperand());
8916
8917     // Update the uses.
8918     std::vector<SDValue> NewResults;
8919     for (unsigned i = 0; i < NumResultVecs; ++i) {
8920       NewResults.push_back(SDValue(UpdN.getNode(), i));
8921     }
8922     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8923     DCI.CombineTo(N, NewResults);
8924     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8925
8926     break;
8927   }
8928   return SDValue();
8929 }
8930
8931 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8932 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8933 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
8934 /// return true.
8935 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8936   SelectionDAG &DAG = DCI.DAG;
8937   EVT VT = N->getValueType(0);
8938   // vldN-dup instructions only support 64-bit vectors for N > 1.
8939   if (!VT.is64BitVector())
8940     return false;
8941
8942   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8943   SDNode *VLD = N->getOperand(0).getNode();
8944   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8945     return false;
8946   unsigned NumVecs = 0;
8947   unsigned NewOpc = 0;
8948   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8949   if (IntNo == Intrinsic::arm_neon_vld2lane) {
8950     NumVecs = 2;
8951     NewOpc = ARMISD::VLD2DUP;
8952   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8953     NumVecs = 3;
8954     NewOpc = ARMISD::VLD3DUP;
8955   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8956     NumVecs = 4;
8957     NewOpc = ARMISD::VLD4DUP;
8958   } else {
8959     return false;
8960   }
8961
8962   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8963   // numbers match the load.
8964   unsigned VLDLaneNo =
8965     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8966   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8967        UI != UE; ++UI) {
8968     // Ignore uses of the chain result.
8969     if (UI.getUse().getResNo() == NumVecs)
8970       continue;
8971     SDNode *User = *UI;
8972     if (User->getOpcode() != ARMISD::VDUPLANE ||
8973         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8974       return false;
8975   }
8976
8977   // Create the vldN-dup node.
8978   EVT Tys[5];
8979   unsigned n;
8980   for (n = 0; n < NumVecs; ++n)
8981     Tys[n] = VT;
8982   Tys[n] = MVT::Other;
8983   SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumVecs+1));
8984   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8985   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8986   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
8987                                            Ops, VLDMemInt->getMemoryVT(),
8988                                            VLDMemInt->getMemOperand());
8989
8990   // Update the uses.
8991   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8992        UI != UE; ++UI) {
8993     unsigned ResNo = UI.getUse().getResNo();
8994     // Ignore uses of the chain result.
8995     if (ResNo == NumVecs)
8996       continue;
8997     SDNode *User = *UI;
8998     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8999   }
9000
9001   // Now the vldN-lane intrinsic is dead except for its chain result.
9002   // Update uses of the chain.
9003   std::vector<SDValue> VLDDupResults;
9004   for (unsigned n = 0; n < NumVecs; ++n)
9005     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9006   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9007   DCI.CombineTo(VLD, VLDDupResults);
9008
9009   return true;
9010 }
9011
9012 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9013 /// ARMISD::VDUPLANE.
9014 static SDValue PerformVDUPLANECombine(SDNode *N,
9015                                       TargetLowering::DAGCombinerInfo &DCI) {
9016   SDValue Op = N->getOperand(0);
9017
9018   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9019   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9020   if (CombineVLDDUP(N, DCI))
9021     return SDValue(N, 0);
9022
9023   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9024   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9025   while (Op.getOpcode() == ISD::BITCAST)
9026     Op = Op.getOperand(0);
9027   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9028     return SDValue();
9029
9030   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9031   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9032   // The canonical VMOV for a zero vector uses a 32-bit element size.
9033   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9034   unsigned EltBits;
9035   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9036     EltSize = 8;
9037   EVT VT = N->getValueType(0);
9038   if (EltSize > VT.getVectorElementType().getSizeInBits())
9039     return SDValue();
9040
9041   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9042 }
9043
9044 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9045 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9046 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9047 {
9048   integerPart cN;
9049   integerPart c0 = 0;
9050   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9051        I != E; I++) {
9052     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9053     if (!C)
9054       return false;
9055
9056     bool isExact;
9057     APFloat APF = C->getValueAPF();
9058     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9059         != APFloat::opOK || !isExact)
9060       return false;
9061
9062     c0 = (I == 0) ? cN : c0;
9063     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9064       return false;
9065   }
9066   C = c0;
9067   return true;
9068 }
9069
9070 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9071 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9072 /// when the VMUL has a constant operand that is a power of 2.
9073 ///
9074 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9075 ///  vmul.f32        d16, d17, d16
9076 ///  vcvt.s32.f32    d16, d16
9077 /// becomes:
9078 ///  vcvt.s32.f32    d16, d16, #3
9079 static SDValue PerformVCVTCombine(SDNode *N,
9080                                   TargetLowering::DAGCombinerInfo &DCI,
9081                                   const ARMSubtarget *Subtarget) {
9082   SelectionDAG &DAG = DCI.DAG;
9083   SDValue Op = N->getOperand(0);
9084
9085   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9086       Op.getOpcode() != ISD::FMUL)
9087     return SDValue();
9088
9089   uint64_t C;
9090   SDValue N0 = Op->getOperand(0);
9091   SDValue ConstVec = Op->getOperand(1);
9092   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9093
9094   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9095       !isConstVecPow2(ConstVec, isSigned, C))
9096     return SDValue();
9097
9098   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9099   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9100   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9101     // These instructions only exist converting from f32 to i32. We can handle
9102     // smaller integers by generating an extra truncate, but larger ones would
9103     // be lossy.
9104     return SDValue();
9105   }
9106
9107   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9108     Intrinsic::arm_neon_vcvtfp2fxu;
9109   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9110   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9111                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9112                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9113                                  DAG.getConstant(Log2_64(C), MVT::i32));
9114
9115   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9116     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9117
9118   return FixConv;
9119 }
9120
9121 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9122 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9123 /// when the VDIV has a constant operand that is a power of 2.
9124 ///
9125 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9126 ///  vcvt.f32.s32    d16, d16
9127 ///  vdiv.f32        d16, d17, d16
9128 /// becomes:
9129 ///  vcvt.f32.s32    d16, d16, #3
9130 static SDValue PerformVDIVCombine(SDNode *N,
9131                                   TargetLowering::DAGCombinerInfo &DCI,
9132                                   const ARMSubtarget *Subtarget) {
9133   SelectionDAG &DAG = DCI.DAG;
9134   SDValue Op = N->getOperand(0);
9135   unsigned OpOpcode = Op.getNode()->getOpcode();
9136
9137   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9138       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9139     return SDValue();
9140
9141   uint64_t C;
9142   SDValue ConstVec = N->getOperand(1);
9143   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9144
9145   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9146       !isConstVecPow2(ConstVec, isSigned, C))
9147     return SDValue();
9148
9149   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9150   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9151   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9152     // These instructions only exist converting from i32 to f32. We can handle
9153     // smaller integers by generating an extra extend, but larger ones would
9154     // be lossy.
9155     return SDValue();
9156   }
9157
9158   SDValue ConvInput = Op.getOperand(0);
9159   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9160   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9161     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9162                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9163                             ConvInput);
9164
9165   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9166     Intrinsic::arm_neon_vcvtfxu2fp;
9167   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9168                      Op.getValueType(),
9169                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9170                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9171 }
9172
9173 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9174 /// operand of a vector shift operation, where all the elements of the
9175 /// build_vector must have the same constant integer value.
9176 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9177   // Ignore bit_converts.
9178   while (Op.getOpcode() == ISD::BITCAST)
9179     Op = Op.getOperand(0);
9180   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9181   APInt SplatBits, SplatUndef;
9182   unsigned SplatBitSize;
9183   bool HasAnyUndefs;
9184   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9185                                       HasAnyUndefs, ElementBits) ||
9186       SplatBitSize > ElementBits)
9187     return false;
9188   Cnt = SplatBits.getSExtValue();
9189   return true;
9190 }
9191
9192 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9193 /// operand of a vector shift left operation.  That value must be in the range:
9194 ///   0 <= Value < ElementBits for a left shift; or
9195 ///   0 <= Value <= ElementBits for a long left shift.
9196 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9197   assert(VT.isVector() && "vector shift count is not a vector type");
9198   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9199   if (! getVShiftImm(Op, ElementBits, Cnt))
9200     return false;
9201   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9202 }
9203
9204 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9205 /// operand of a vector shift right operation.  For a shift opcode, the value
9206 /// is positive, but for an intrinsic the value count must be negative. The
9207 /// absolute value must be in the range:
9208 ///   1 <= |Value| <= ElementBits for a right shift; or
9209 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9210 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9211                          int64_t &Cnt) {
9212   assert(VT.isVector() && "vector shift count is not a vector type");
9213   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9214   if (! getVShiftImm(Op, ElementBits, Cnt))
9215     return false;
9216   if (isIntrinsic)
9217     Cnt = -Cnt;
9218   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9219 }
9220
9221 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9222 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9223   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9224   switch (IntNo) {
9225   default:
9226     // Don't do anything for most intrinsics.
9227     break;
9228
9229   // Vector shifts: check for immediate versions and lower them.
9230   // Note: This is done during DAG combining instead of DAG legalizing because
9231   // the build_vectors for 64-bit vector element shift counts are generally
9232   // not legal, and it is hard to see their values after they get legalized to
9233   // loads from a constant pool.
9234   case Intrinsic::arm_neon_vshifts:
9235   case Intrinsic::arm_neon_vshiftu:
9236   case Intrinsic::arm_neon_vrshifts:
9237   case Intrinsic::arm_neon_vrshiftu:
9238   case Intrinsic::arm_neon_vrshiftn:
9239   case Intrinsic::arm_neon_vqshifts:
9240   case Intrinsic::arm_neon_vqshiftu:
9241   case Intrinsic::arm_neon_vqshiftsu:
9242   case Intrinsic::arm_neon_vqshiftns:
9243   case Intrinsic::arm_neon_vqshiftnu:
9244   case Intrinsic::arm_neon_vqshiftnsu:
9245   case Intrinsic::arm_neon_vqrshiftns:
9246   case Intrinsic::arm_neon_vqrshiftnu:
9247   case Intrinsic::arm_neon_vqrshiftnsu: {
9248     EVT VT = N->getOperand(1).getValueType();
9249     int64_t Cnt;
9250     unsigned VShiftOpc = 0;
9251
9252     switch (IntNo) {
9253     case Intrinsic::arm_neon_vshifts:
9254     case Intrinsic::arm_neon_vshiftu:
9255       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9256         VShiftOpc = ARMISD::VSHL;
9257         break;
9258       }
9259       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9260         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9261                      ARMISD::VSHRs : ARMISD::VSHRu);
9262         break;
9263       }
9264       return SDValue();
9265
9266     case Intrinsic::arm_neon_vrshifts:
9267     case Intrinsic::arm_neon_vrshiftu:
9268       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9269         break;
9270       return SDValue();
9271
9272     case Intrinsic::arm_neon_vqshifts:
9273     case Intrinsic::arm_neon_vqshiftu:
9274       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9275         break;
9276       return SDValue();
9277
9278     case Intrinsic::arm_neon_vqshiftsu:
9279       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9280         break;
9281       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9282
9283     case Intrinsic::arm_neon_vrshiftn:
9284     case Intrinsic::arm_neon_vqshiftns:
9285     case Intrinsic::arm_neon_vqshiftnu:
9286     case Intrinsic::arm_neon_vqshiftnsu:
9287     case Intrinsic::arm_neon_vqrshiftns:
9288     case Intrinsic::arm_neon_vqrshiftnu:
9289     case Intrinsic::arm_neon_vqrshiftnsu:
9290       // Narrowing shifts require an immediate right shift.
9291       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9292         break;
9293       llvm_unreachable("invalid shift count for narrowing vector shift "
9294                        "intrinsic");
9295
9296     default:
9297       llvm_unreachable("unhandled vector shift");
9298     }
9299
9300     switch (IntNo) {
9301     case Intrinsic::arm_neon_vshifts:
9302     case Intrinsic::arm_neon_vshiftu:
9303       // Opcode already set above.
9304       break;
9305     case Intrinsic::arm_neon_vrshifts:
9306       VShiftOpc = ARMISD::VRSHRs; break;
9307     case Intrinsic::arm_neon_vrshiftu:
9308       VShiftOpc = ARMISD::VRSHRu; break;
9309     case Intrinsic::arm_neon_vrshiftn:
9310       VShiftOpc = ARMISD::VRSHRN; break;
9311     case Intrinsic::arm_neon_vqshifts:
9312       VShiftOpc = ARMISD::VQSHLs; break;
9313     case Intrinsic::arm_neon_vqshiftu:
9314       VShiftOpc = ARMISD::VQSHLu; break;
9315     case Intrinsic::arm_neon_vqshiftsu:
9316       VShiftOpc = ARMISD::VQSHLsu; break;
9317     case Intrinsic::arm_neon_vqshiftns:
9318       VShiftOpc = ARMISD::VQSHRNs; break;
9319     case Intrinsic::arm_neon_vqshiftnu:
9320       VShiftOpc = ARMISD::VQSHRNu; break;
9321     case Intrinsic::arm_neon_vqshiftnsu:
9322       VShiftOpc = ARMISD::VQSHRNsu; break;
9323     case Intrinsic::arm_neon_vqrshiftns:
9324       VShiftOpc = ARMISD::VQRSHRNs; break;
9325     case Intrinsic::arm_neon_vqrshiftnu:
9326       VShiftOpc = ARMISD::VQRSHRNu; break;
9327     case Intrinsic::arm_neon_vqrshiftnsu:
9328       VShiftOpc = ARMISD::VQRSHRNsu; break;
9329     }
9330
9331     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9332                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9333   }
9334
9335   case Intrinsic::arm_neon_vshiftins: {
9336     EVT VT = N->getOperand(1).getValueType();
9337     int64_t Cnt;
9338     unsigned VShiftOpc = 0;
9339
9340     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9341       VShiftOpc = ARMISD::VSLI;
9342     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9343       VShiftOpc = ARMISD::VSRI;
9344     else {
9345       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9346     }
9347
9348     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9349                        N->getOperand(1), N->getOperand(2),
9350                        DAG.getConstant(Cnt, MVT::i32));
9351   }
9352
9353   case Intrinsic::arm_neon_vqrshifts:
9354   case Intrinsic::arm_neon_vqrshiftu:
9355     // No immediate versions of these to check for.
9356     break;
9357   }
9358
9359   return SDValue();
9360 }
9361
9362 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9363 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9364 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9365 /// vector element shift counts are generally not legal, and it is hard to see
9366 /// their values after they get legalized to loads from a constant pool.
9367 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9368                                    const ARMSubtarget *ST) {
9369   EVT VT = N->getValueType(0);
9370   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9371     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9372     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9373     SDValue N1 = N->getOperand(1);
9374     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9375       SDValue N0 = N->getOperand(0);
9376       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9377           DAG.MaskedValueIsZero(N0.getOperand(0),
9378                                 APInt::getHighBitsSet(32, 16)))
9379         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9380     }
9381   }
9382
9383   // Nothing to be done for scalar shifts.
9384   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9385   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9386     return SDValue();
9387
9388   assert(ST->hasNEON() && "unexpected vector shift");
9389   int64_t Cnt;
9390
9391   switch (N->getOpcode()) {
9392   default: llvm_unreachable("unexpected shift opcode");
9393
9394   case ISD::SHL:
9395     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9396       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9397                          DAG.getConstant(Cnt, MVT::i32));
9398     break;
9399
9400   case ISD::SRA:
9401   case ISD::SRL:
9402     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9403       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9404                             ARMISD::VSHRs : ARMISD::VSHRu);
9405       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9406                          DAG.getConstant(Cnt, MVT::i32));
9407     }
9408   }
9409   return SDValue();
9410 }
9411
9412 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9413 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9414 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9415                                     const ARMSubtarget *ST) {
9416   SDValue N0 = N->getOperand(0);
9417
9418   // Check for sign- and zero-extensions of vector extract operations of 8-
9419   // and 16-bit vector elements.  NEON supports these directly.  They are
9420   // handled during DAG combining because type legalization will promote them
9421   // to 32-bit types and it is messy to recognize the operations after that.
9422   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9423     SDValue Vec = N0.getOperand(0);
9424     SDValue Lane = N0.getOperand(1);
9425     EVT VT = N->getValueType(0);
9426     EVT EltVT = N0.getValueType();
9427     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9428
9429     if (VT == MVT::i32 &&
9430         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9431         TLI.isTypeLegal(Vec.getValueType()) &&
9432         isa<ConstantSDNode>(Lane)) {
9433
9434       unsigned Opc = 0;
9435       switch (N->getOpcode()) {
9436       default: llvm_unreachable("unexpected opcode");
9437       case ISD::SIGN_EXTEND:
9438         Opc = ARMISD::VGETLANEs;
9439         break;
9440       case ISD::ZERO_EXTEND:
9441       case ISD::ANY_EXTEND:
9442         Opc = ARMISD::VGETLANEu;
9443         break;
9444       }
9445       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9446     }
9447   }
9448
9449   return SDValue();
9450 }
9451
9452 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9453 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9454 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9455                                        const ARMSubtarget *ST) {
9456   // If the target supports NEON, try to use vmax/vmin instructions for f32
9457   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9458   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9459   // a NaN; only do the transformation when it matches that behavior.
9460
9461   // For now only do this when using NEON for FP operations; if using VFP, it
9462   // is not obvious that the benefit outweighs the cost of switching to the
9463   // NEON pipeline.
9464   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9465       N->getValueType(0) != MVT::f32)
9466     return SDValue();
9467
9468   SDValue CondLHS = N->getOperand(0);
9469   SDValue CondRHS = N->getOperand(1);
9470   SDValue LHS = N->getOperand(2);
9471   SDValue RHS = N->getOperand(3);
9472   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9473
9474   unsigned Opcode = 0;
9475   bool IsReversed;
9476   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9477     IsReversed = false; // x CC y ? x : y
9478   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9479     IsReversed = true ; // x CC y ? y : x
9480   } else {
9481     return SDValue();
9482   }
9483
9484   bool IsUnordered;
9485   switch (CC) {
9486   default: break;
9487   case ISD::SETOLT:
9488   case ISD::SETOLE:
9489   case ISD::SETLT:
9490   case ISD::SETLE:
9491   case ISD::SETULT:
9492   case ISD::SETULE:
9493     // If LHS is NaN, an ordered comparison will be false and the result will
9494     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9495     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9496     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9497     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9498       break;
9499     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9500     // will return -0, so vmin can only be used for unsafe math or if one of
9501     // the operands is known to be nonzero.
9502     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9503         !DAG.getTarget().Options.UnsafeFPMath &&
9504         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9505       break;
9506     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9507     break;
9508
9509   case ISD::SETOGT:
9510   case ISD::SETOGE:
9511   case ISD::SETGT:
9512   case ISD::SETGE:
9513   case ISD::SETUGT:
9514   case ISD::SETUGE:
9515     // If LHS is NaN, an ordered comparison will be false and the result will
9516     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9517     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9518     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9519     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9520       break;
9521     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9522     // will return +0, so vmax can only be used for unsafe math or if one of
9523     // the operands is known to be nonzero.
9524     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9525         !DAG.getTarget().Options.UnsafeFPMath &&
9526         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9527       break;
9528     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9529     break;
9530   }
9531
9532   if (!Opcode)
9533     return SDValue();
9534   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9535 }
9536
9537 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9538 SDValue
9539 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9540   SDValue Cmp = N->getOperand(4);
9541   if (Cmp.getOpcode() != ARMISD::CMPZ)
9542     // Only looking at EQ and NE cases.
9543     return SDValue();
9544
9545   EVT VT = N->getValueType(0);
9546   SDLoc dl(N);
9547   SDValue LHS = Cmp.getOperand(0);
9548   SDValue RHS = Cmp.getOperand(1);
9549   SDValue FalseVal = N->getOperand(0);
9550   SDValue TrueVal = N->getOperand(1);
9551   SDValue ARMcc = N->getOperand(2);
9552   ARMCC::CondCodes CC =
9553     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9554
9555   // Simplify
9556   //   mov     r1, r0
9557   //   cmp     r1, x
9558   //   mov     r0, y
9559   //   moveq   r0, x
9560   // to
9561   //   cmp     r0, x
9562   //   movne   r0, y
9563   //
9564   //   mov     r1, r0
9565   //   cmp     r1, x
9566   //   mov     r0, x
9567   //   movne   r0, y
9568   // to
9569   //   cmp     r0, x
9570   //   movne   r0, y
9571   /// FIXME: Turn this into a target neutral optimization?
9572   SDValue Res;
9573   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9574     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9575                       N->getOperand(3), Cmp);
9576   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9577     SDValue ARMcc;
9578     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9579     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9580                       N->getOperand(3), NewCmp);
9581   }
9582
9583   if (Res.getNode()) {
9584     APInt KnownZero, KnownOne;
9585     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9586     // Capture demanded bits information that would be otherwise lost.
9587     if (KnownZero == 0xfffffffe)
9588       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9589                         DAG.getValueType(MVT::i1));
9590     else if (KnownZero == 0xffffff00)
9591       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9592                         DAG.getValueType(MVT::i8));
9593     else if (KnownZero == 0xffff0000)
9594       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9595                         DAG.getValueType(MVT::i16));
9596   }
9597
9598   return Res;
9599 }
9600
9601 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9602                                              DAGCombinerInfo &DCI) const {
9603   switch (N->getOpcode()) {
9604   default: break;
9605   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9606   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9607   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9608   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9609   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9610   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9611   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9612   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9613   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9614   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9615   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9616   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9617   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9618   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9619   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9620   case ISD::FP_TO_SINT:
9621   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9622   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9623   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9624   case ISD::SHL:
9625   case ISD::SRA:
9626   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9627   case ISD::SIGN_EXTEND:
9628   case ISD::ZERO_EXTEND:
9629   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9630   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9631   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9632   case ARMISD::VLD2DUP:
9633   case ARMISD::VLD3DUP:
9634   case ARMISD::VLD4DUP:
9635     return CombineBaseUpdate(N, DCI);
9636   case ARMISD::BUILD_VECTOR:
9637     return PerformARMBUILD_VECTORCombine(N, DCI);
9638   case ISD::INTRINSIC_VOID:
9639   case ISD::INTRINSIC_W_CHAIN:
9640     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9641     case Intrinsic::arm_neon_vld1:
9642     case Intrinsic::arm_neon_vld2:
9643     case Intrinsic::arm_neon_vld3:
9644     case Intrinsic::arm_neon_vld4:
9645     case Intrinsic::arm_neon_vld2lane:
9646     case Intrinsic::arm_neon_vld3lane:
9647     case Intrinsic::arm_neon_vld4lane:
9648     case Intrinsic::arm_neon_vst1:
9649     case Intrinsic::arm_neon_vst2:
9650     case Intrinsic::arm_neon_vst3:
9651     case Intrinsic::arm_neon_vst4:
9652     case Intrinsic::arm_neon_vst2lane:
9653     case Intrinsic::arm_neon_vst3lane:
9654     case Intrinsic::arm_neon_vst4lane:
9655       return CombineBaseUpdate(N, DCI);
9656     default: break;
9657     }
9658     break;
9659   }
9660   return SDValue();
9661 }
9662
9663 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9664                                                           EVT VT) const {
9665   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9666 }
9667
9668 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, unsigned,
9669                                                       bool *Fast) const {
9670   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9671   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9672
9673   switch (VT.getSimpleVT().SimpleTy) {
9674   default:
9675     return false;
9676   case MVT::i8:
9677   case MVT::i16:
9678   case MVT::i32: {
9679     // Unaligned access can use (for example) LRDB, LRDH, LDR
9680     if (AllowsUnaligned) {
9681       if (Fast)
9682         *Fast = Subtarget->hasV7Ops();
9683       return true;
9684     }
9685     return false;
9686   }
9687   case MVT::f64:
9688   case MVT::v2f64: {
9689     // For any little-endian targets with neon, we can support unaligned ld/st
9690     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9691     // A big-endian target may also explicitly support unaligned accesses
9692     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9693       if (Fast)
9694         *Fast = true;
9695       return true;
9696     }
9697     return false;
9698   }
9699   }
9700 }
9701
9702 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9703                        unsigned AlignCheck) {
9704   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9705           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9706 }
9707
9708 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9709                                            unsigned DstAlign, unsigned SrcAlign,
9710                                            bool IsMemset, bool ZeroMemset,
9711                                            bool MemcpyStrSrc,
9712                                            MachineFunction &MF) const {
9713   const Function *F = MF.getFunction();
9714
9715   // See if we can use NEON instructions for this...
9716   if ((!IsMemset || ZeroMemset) &&
9717       Subtarget->hasNEON() &&
9718       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9719                                        Attribute::NoImplicitFloat)) {
9720     bool Fast;
9721     if (Size >= 16 &&
9722         (memOpAlign(SrcAlign, DstAlign, 16) ||
9723          (allowsUnalignedMemoryAccesses(MVT::v2f64, 0, &Fast) && Fast))) {
9724       return MVT::v2f64;
9725     } else if (Size >= 8 &&
9726                (memOpAlign(SrcAlign, DstAlign, 8) ||
9727                 (allowsUnalignedMemoryAccesses(MVT::f64, 0, &Fast) && Fast))) {
9728       return MVT::f64;
9729     }
9730   }
9731
9732   // Lowering to i32/i16 if the size permits.
9733   if (Size >= 4)
9734     return MVT::i32;
9735   else if (Size >= 2)
9736     return MVT::i16;
9737
9738   // Let the target-independent logic figure it out.
9739   return MVT::Other;
9740 }
9741
9742 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9743   if (Val.getOpcode() != ISD::LOAD)
9744     return false;
9745
9746   EVT VT1 = Val.getValueType();
9747   if (!VT1.isSimple() || !VT1.isInteger() ||
9748       !VT2.isSimple() || !VT2.isInteger())
9749     return false;
9750
9751   switch (VT1.getSimpleVT().SimpleTy) {
9752   default: break;
9753   case MVT::i1:
9754   case MVT::i8:
9755   case MVT::i16:
9756     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9757     return true;
9758   }
9759
9760   return false;
9761 }
9762
9763 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9764   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9765     return false;
9766
9767   if (!isTypeLegal(EVT::getEVT(Ty1)))
9768     return false;
9769
9770   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9771
9772   // Assuming the caller doesn't have a zeroext or signext return parameter,
9773   // truncation all the way down to i1 is valid.
9774   return true;
9775 }
9776
9777
9778 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9779   if (V < 0)
9780     return false;
9781
9782   unsigned Scale = 1;
9783   switch (VT.getSimpleVT().SimpleTy) {
9784   default: return false;
9785   case MVT::i1:
9786   case MVT::i8:
9787     // Scale == 1;
9788     break;
9789   case MVT::i16:
9790     // Scale == 2;
9791     Scale = 2;
9792     break;
9793   case MVT::i32:
9794     // Scale == 4;
9795     Scale = 4;
9796     break;
9797   }
9798
9799   if ((V & (Scale - 1)) != 0)
9800     return false;
9801   V /= Scale;
9802   return V == (V & ((1LL << 5) - 1));
9803 }
9804
9805 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9806                                       const ARMSubtarget *Subtarget) {
9807   bool isNeg = false;
9808   if (V < 0) {
9809     isNeg = true;
9810     V = - V;
9811   }
9812
9813   switch (VT.getSimpleVT().SimpleTy) {
9814   default: return false;
9815   case MVT::i1:
9816   case MVT::i8:
9817   case MVT::i16:
9818   case MVT::i32:
9819     // + imm12 or - imm8
9820     if (isNeg)
9821       return V == (V & ((1LL << 8) - 1));
9822     return V == (V & ((1LL << 12) - 1));
9823   case MVT::f32:
9824   case MVT::f64:
9825     // Same as ARM mode. FIXME: NEON?
9826     if (!Subtarget->hasVFP2())
9827       return false;
9828     if ((V & 3) != 0)
9829       return false;
9830     V >>= 2;
9831     return V == (V & ((1LL << 8) - 1));
9832   }
9833 }
9834
9835 /// isLegalAddressImmediate - Return true if the integer value can be used
9836 /// as the offset of the target addressing mode for load / store of the
9837 /// given type.
9838 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9839                                     const ARMSubtarget *Subtarget) {
9840   if (V == 0)
9841     return true;
9842
9843   if (!VT.isSimple())
9844     return false;
9845
9846   if (Subtarget->isThumb1Only())
9847     return isLegalT1AddressImmediate(V, VT);
9848   else if (Subtarget->isThumb2())
9849     return isLegalT2AddressImmediate(V, VT, Subtarget);
9850
9851   // ARM mode.
9852   if (V < 0)
9853     V = - V;
9854   switch (VT.getSimpleVT().SimpleTy) {
9855   default: return false;
9856   case MVT::i1:
9857   case MVT::i8:
9858   case MVT::i32:
9859     // +- imm12
9860     return V == (V & ((1LL << 12) - 1));
9861   case MVT::i16:
9862     // +- imm8
9863     return V == (V & ((1LL << 8) - 1));
9864   case MVT::f32:
9865   case MVT::f64:
9866     if (!Subtarget->hasVFP2()) // FIXME: NEON?
9867       return false;
9868     if ((V & 3) != 0)
9869       return false;
9870     V >>= 2;
9871     return V == (V & ((1LL << 8) - 1));
9872   }
9873 }
9874
9875 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9876                                                       EVT VT) const {
9877   int Scale = AM.Scale;
9878   if (Scale < 0)
9879     return false;
9880
9881   switch (VT.getSimpleVT().SimpleTy) {
9882   default: return false;
9883   case MVT::i1:
9884   case MVT::i8:
9885   case MVT::i16:
9886   case MVT::i32:
9887     if (Scale == 1)
9888       return true;
9889     // r + r << imm
9890     Scale = Scale & ~1;
9891     return Scale == 2 || Scale == 4 || Scale == 8;
9892   case MVT::i64:
9893     // r + r
9894     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9895       return true;
9896     return false;
9897   case MVT::isVoid:
9898     // Note, we allow "void" uses (basically, uses that aren't loads or
9899     // stores), because arm allows folding a scale into many arithmetic
9900     // operations.  This should be made more precise and revisited later.
9901
9902     // Allow r << imm, but the imm has to be a multiple of two.
9903     if (Scale & 1) return false;
9904     return isPowerOf2_32(Scale);
9905   }
9906 }
9907
9908 /// isLegalAddressingMode - Return true if the addressing mode represented
9909 /// by AM is legal for this target, for a load/store of the specified type.
9910 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9911                                               Type *Ty) const {
9912   EVT VT = getValueType(Ty, true);
9913   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9914     return false;
9915
9916   // Can never fold addr of global into load/store.
9917   if (AM.BaseGV)
9918     return false;
9919
9920   switch (AM.Scale) {
9921   case 0:  // no scale reg, must be "r+i" or "r", or "i".
9922     break;
9923   case 1:
9924     if (Subtarget->isThumb1Only())
9925       return false;
9926     // FALL THROUGH.
9927   default:
9928     // ARM doesn't support any R+R*scale+imm addr modes.
9929     if (AM.BaseOffs)
9930       return false;
9931
9932     if (!VT.isSimple())
9933       return false;
9934
9935     if (Subtarget->isThumb2())
9936       return isLegalT2ScaledAddressingMode(AM, VT);
9937
9938     int Scale = AM.Scale;
9939     switch (VT.getSimpleVT().SimpleTy) {
9940     default: return false;
9941     case MVT::i1:
9942     case MVT::i8:
9943     case MVT::i32:
9944       if (Scale < 0) Scale = -Scale;
9945       if (Scale == 1)
9946         return true;
9947       // r + r << imm
9948       return isPowerOf2_32(Scale & ~1);
9949     case MVT::i16:
9950     case MVT::i64:
9951       // r + r
9952       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9953         return true;
9954       return false;
9955
9956     case MVT::isVoid:
9957       // Note, we allow "void" uses (basically, uses that aren't loads or
9958       // stores), because arm allows folding a scale into many arithmetic
9959       // operations.  This should be made more precise and revisited later.
9960
9961       // Allow r << imm, but the imm has to be a multiple of two.
9962       if (Scale & 1) return false;
9963       return isPowerOf2_32(Scale);
9964     }
9965   }
9966   return true;
9967 }
9968
9969 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9970 /// icmp immediate, that is the target has icmp instructions which can compare
9971 /// a register against the immediate without having to materialize the
9972 /// immediate into a register.
9973 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9974   // Thumb2 and ARM modes can use cmn for negative immediates.
9975   if (!Subtarget->isThumb())
9976     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9977   if (Subtarget->isThumb2())
9978     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9979   // Thumb1 doesn't have cmn, and only 8-bit immediates.
9980   return Imm >= 0 && Imm <= 255;
9981 }
9982
9983 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9984 /// *or sub* immediate, that is the target has add or sub instructions which can
9985 /// add a register with the immediate without having to materialize the
9986 /// immediate into a register.
9987 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9988   // Same encoding for add/sub, just flip the sign.
9989   int64_t AbsImm = llvm::abs64(Imm);
9990   if (!Subtarget->isThumb())
9991     return ARM_AM::getSOImmVal(AbsImm) != -1;
9992   if (Subtarget->isThumb2())
9993     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9994   // Thumb1 only has 8-bit unsigned immediate.
9995   return AbsImm >= 0 && AbsImm <= 255;
9996 }
9997
9998 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9999                                       bool isSEXTLoad, SDValue &Base,
10000                                       SDValue &Offset, bool &isInc,
10001                                       SelectionDAG &DAG) {
10002   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10003     return false;
10004
10005   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10006     // AddressingMode 3
10007     Base = Ptr->getOperand(0);
10008     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10009       int RHSC = (int)RHS->getZExtValue();
10010       if (RHSC < 0 && RHSC > -256) {
10011         assert(Ptr->getOpcode() == ISD::ADD);
10012         isInc = false;
10013         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10014         return true;
10015       }
10016     }
10017     isInc = (Ptr->getOpcode() == ISD::ADD);
10018     Offset = Ptr->getOperand(1);
10019     return true;
10020   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10021     // AddressingMode 2
10022     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10023       int RHSC = (int)RHS->getZExtValue();
10024       if (RHSC < 0 && RHSC > -0x1000) {
10025         assert(Ptr->getOpcode() == ISD::ADD);
10026         isInc = false;
10027         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10028         Base = Ptr->getOperand(0);
10029         return true;
10030       }
10031     }
10032
10033     if (Ptr->getOpcode() == ISD::ADD) {
10034       isInc = true;
10035       ARM_AM::ShiftOpc ShOpcVal=
10036         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10037       if (ShOpcVal != ARM_AM::no_shift) {
10038         Base = Ptr->getOperand(1);
10039         Offset = Ptr->getOperand(0);
10040       } else {
10041         Base = Ptr->getOperand(0);
10042         Offset = Ptr->getOperand(1);
10043       }
10044       return true;
10045     }
10046
10047     isInc = (Ptr->getOpcode() == ISD::ADD);
10048     Base = Ptr->getOperand(0);
10049     Offset = Ptr->getOperand(1);
10050     return true;
10051   }
10052
10053   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10054   return false;
10055 }
10056
10057 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10058                                      bool isSEXTLoad, SDValue &Base,
10059                                      SDValue &Offset, bool &isInc,
10060                                      SelectionDAG &DAG) {
10061   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10062     return false;
10063
10064   Base = Ptr->getOperand(0);
10065   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10066     int RHSC = (int)RHS->getZExtValue();
10067     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10068       assert(Ptr->getOpcode() == ISD::ADD);
10069       isInc = false;
10070       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10071       return true;
10072     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10073       isInc = Ptr->getOpcode() == ISD::ADD;
10074       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10075       return true;
10076     }
10077   }
10078
10079   return false;
10080 }
10081
10082 /// getPreIndexedAddressParts - returns true by value, base pointer and
10083 /// offset pointer and addressing mode by reference if the node's address
10084 /// can be legally represented as pre-indexed load / store address.
10085 bool
10086 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10087                                              SDValue &Offset,
10088                                              ISD::MemIndexedMode &AM,
10089                                              SelectionDAG &DAG) const {
10090   if (Subtarget->isThumb1Only())
10091     return false;
10092
10093   EVT VT;
10094   SDValue Ptr;
10095   bool isSEXTLoad = false;
10096   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10097     Ptr = LD->getBasePtr();
10098     VT  = LD->getMemoryVT();
10099     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10100   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10101     Ptr = ST->getBasePtr();
10102     VT  = ST->getMemoryVT();
10103   } else
10104     return false;
10105
10106   bool isInc;
10107   bool isLegal = false;
10108   if (Subtarget->isThumb2())
10109     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10110                                        Offset, isInc, DAG);
10111   else
10112     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10113                                         Offset, isInc, DAG);
10114   if (!isLegal)
10115     return false;
10116
10117   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10118   return true;
10119 }
10120
10121 /// getPostIndexedAddressParts - returns true by value, base pointer and
10122 /// offset pointer and addressing mode by reference if this node can be
10123 /// combined with a load / store to form a post-indexed load / store.
10124 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10125                                                    SDValue &Base,
10126                                                    SDValue &Offset,
10127                                                    ISD::MemIndexedMode &AM,
10128                                                    SelectionDAG &DAG) const {
10129   if (Subtarget->isThumb1Only())
10130     return false;
10131
10132   EVT VT;
10133   SDValue Ptr;
10134   bool isSEXTLoad = false;
10135   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10136     VT  = LD->getMemoryVT();
10137     Ptr = LD->getBasePtr();
10138     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10139   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10140     VT  = ST->getMemoryVT();
10141     Ptr = ST->getBasePtr();
10142   } else
10143     return false;
10144
10145   bool isInc;
10146   bool isLegal = false;
10147   if (Subtarget->isThumb2())
10148     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10149                                        isInc, DAG);
10150   else
10151     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10152                                         isInc, DAG);
10153   if (!isLegal)
10154     return false;
10155
10156   if (Ptr != Base) {
10157     // Swap base ptr and offset to catch more post-index load / store when
10158     // it's legal. In Thumb2 mode, offset must be an immediate.
10159     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10160         !Subtarget->isThumb2())
10161       std::swap(Base, Offset);
10162
10163     // Post-indexed load / store update the base pointer.
10164     if (Ptr != Base)
10165       return false;
10166   }
10167
10168   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10169   return true;
10170 }
10171
10172 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10173                                                       APInt &KnownZero,
10174                                                       APInt &KnownOne,
10175                                                       const SelectionDAG &DAG,
10176                                                       unsigned Depth) const {
10177   unsigned BitWidth = KnownOne.getBitWidth();
10178   KnownZero = KnownOne = APInt(BitWidth, 0);
10179   switch (Op.getOpcode()) {
10180   default: break;
10181   case ARMISD::ADDC:
10182   case ARMISD::ADDE:
10183   case ARMISD::SUBC:
10184   case ARMISD::SUBE:
10185     // These nodes' second result is a boolean
10186     if (Op.getResNo() == 0)
10187       break;
10188     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10189     break;
10190   case ARMISD::CMOV: {
10191     // Bits are known zero/one if known on the LHS and RHS.
10192     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10193     if (KnownZero == 0 && KnownOne == 0) return;
10194
10195     APInt KnownZeroRHS, KnownOneRHS;
10196     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10197     KnownZero &= KnownZeroRHS;
10198     KnownOne  &= KnownOneRHS;
10199     return;
10200   }
10201   case ISD::INTRINSIC_W_CHAIN: {
10202     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10203     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10204     switch (IntID) {
10205     default: return;
10206     case Intrinsic::arm_ldaex:
10207     case Intrinsic::arm_ldrex: {
10208       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10209       unsigned MemBits = VT.getScalarType().getSizeInBits();
10210       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10211       return;
10212     }
10213     }
10214   }
10215   }
10216 }
10217
10218 //===----------------------------------------------------------------------===//
10219 //                           ARM Inline Assembly Support
10220 //===----------------------------------------------------------------------===//
10221
10222 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10223   // Looking for "rev" which is V6+.
10224   if (!Subtarget->hasV6Ops())
10225     return false;
10226
10227   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10228   std::string AsmStr = IA->getAsmString();
10229   SmallVector<StringRef, 4> AsmPieces;
10230   SplitString(AsmStr, AsmPieces, ";\n");
10231
10232   switch (AsmPieces.size()) {
10233   default: return false;
10234   case 1:
10235     AsmStr = AsmPieces[0];
10236     AsmPieces.clear();
10237     SplitString(AsmStr, AsmPieces, " \t,");
10238
10239     // rev $0, $1
10240     if (AsmPieces.size() == 3 &&
10241         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10242         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10243       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10244       if (Ty && Ty->getBitWidth() == 32)
10245         return IntrinsicLowering::LowerToByteSwap(CI);
10246     }
10247     break;
10248   }
10249
10250   return false;
10251 }
10252
10253 /// getConstraintType - Given a constraint letter, return the type of
10254 /// constraint it is for this target.
10255 ARMTargetLowering::ConstraintType
10256 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10257   if (Constraint.size() == 1) {
10258     switch (Constraint[0]) {
10259     default:  break;
10260     case 'l': return C_RegisterClass;
10261     case 'w': return C_RegisterClass;
10262     case 'h': return C_RegisterClass;
10263     case 'x': return C_RegisterClass;
10264     case 't': return C_RegisterClass;
10265     case 'j': return C_Other; // Constant for movw.
10266       // An address with a single base register. Due to the way we
10267       // currently handle addresses it is the same as an 'r' memory constraint.
10268     case 'Q': return C_Memory;
10269     }
10270   } else if (Constraint.size() == 2) {
10271     switch (Constraint[0]) {
10272     default: break;
10273     // All 'U+' constraints are addresses.
10274     case 'U': return C_Memory;
10275     }
10276   }
10277   return TargetLowering::getConstraintType(Constraint);
10278 }
10279
10280 /// Examine constraint type and operand type and determine a weight value.
10281 /// This object must already have been set up with the operand type
10282 /// and the current alternative constraint selected.
10283 TargetLowering::ConstraintWeight
10284 ARMTargetLowering::getSingleConstraintMatchWeight(
10285     AsmOperandInfo &info, const char *constraint) const {
10286   ConstraintWeight weight = CW_Invalid;
10287   Value *CallOperandVal = info.CallOperandVal;
10288     // If we don't have a value, we can't do a match,
10289     // but allow it at the lowest weight.
10290   if (!CallOperandVal)
10291     return CW_Default;
10292   Type *type = CallOperandVal->getType();
10293   // Look at the constraint type.
10294   switch (*constraint) {
10295   default:
10296     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10297     break;
10298   case 'l':
10299     if (type->isIntegerTy()) {
10300       if (Subtarget->isThumb())
10301         weight = CW_SpecificReg;
10302       else
10303         weight = CW_Register;
10304     }
10305     break;
10306   case 'w':
10307     if (type->isFloatingPointTy())
10308       weight = CW_Register;
10309     break;
10310   }
10311   return weight;
10312 }
10313
10314 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10315 RCPair
10316 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10317                                                 MVT VT) const {
10318   if (Constraint.size() == 1) {
10319     // GCC ARM Constraint Letters
10320     switch (Constraint[0]) {
10321     case 'l': // Low regs or general regs.
10322       if (Subtarget->isThumb())
10323         return RCPair(0U, &ARM::tGPRRegClass);
10324       return RCPair(0U, &ARM::GPRRegClass);
10325     case 'h': // High regs or no regs.
10326       if (Subtarget->isThumb())
10327         return RCPair(0U, &ARM::hGPRRegClass);
10328       break;
10329     case 'r':
10330       return RCPair(0U, &ARM::GPRRegClass);
10331     case 'w':
10332       if (VT == MVT::Other)
10333         break;
10334       if (VT == MVT::f32)
10335         return RCPair(0U, &ARM::SPRRegClass);
10336       if (VT.getSizeInBits() == 64)
10337         return RCPair(0U, &ARM::DPRRegClass);
10338       if (VT.getSizeInBits() == 128)
10339         return RCPair(0U, &ARM::QPRRegClass);
10340       break;
10341     case 'x':
10342       if (VT == MVT::Other)
10343         break;
10344       if (VT == MVT::f32)
10345         return RCPair(0U, &ARM::SPR_8RegClass);
10346       if (VT.getSizeInBits() == 64)
10347         return RCPair(0U, &ARM::DPR_8RegClass);
10348       if (VT.getSizeInBits() == 128)
10349         return RCPair(0U, &ARM::QPR_8RegClass);
10350       break;
10351     case 't':
10352       if (VT == MVT::f32)
10353         return RCPair(0U, &ARM::SPRRegClass);
10354       break;
10355     }
10356   }
10357   if (StringRef("{cc}").equals_lower(Constraint))
10358     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10359
10360   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10361 }
10362
10363 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10364 /// vector.  If it is invalid, don't add anything to Ops.
10365 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10366                                                      std::string &Constraint,
10367                                                      std::vector<SDValue>&Ops,
10368                                                      SelectionDAG &DAG) const {
10369   SDValue Result;
10370
10371   // Currently only support length 1 constraints.
10372   if (Constraint.length() != 1) return;
10373
10374   char ConstraintLetter = Constraint[0];
10375   switch (ConstraintLetter) {
10376   default: break;
10377   case 'j':
10378   case 'I': case 'J': case 'K': case 'L':
10379   case 'M': case 'N': case 'O':
10380     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10381     if (!C)
10382       return;
10383
10384     int64_t CVal64 = C->getSExtValue();
10385     int CVal = (int) CVal64;
10386     // None of these constraints allow values larger than 32 bits.  Check
10387     // that the value fits in an int.
10388     if (CVal != CVal64)
10389       return;
10390
10391     switch (ConstraintLetter) {
10392       case 'j':
10393         // Constant suitable for movw, must be between 0 and
10394         // 65535.
10395         if (Subtarget->hasV6T2Ops())
10396           if (CVal >= 0 && CVal <= 65535)
10397             break;
10398         return;
10399       case 'I':
10400         if (Subtarget->isThumb1Only()) {
10401           // This must be a constant between 0 and 255, for ADD
10402           // immediates.
10403           if (CVal >= 0 && CVal <= 255)
10404             break;
10405         } else if (Subtarget->isThumb2()) {
10406           // A constant that can be used as an immediate value in a
10407           // data-processing instruction.
10408           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10409             break;
10410         } else {
10411           // A constant that can be used as an immediate value in a
10412           // data-processing instruction.
10413           if (ARM_AM::getSOImmVal(CVal) != -1)
10414             break;
10415         }
10416         return;
10417
10418       case 'J':
10419         if (Subtarget->isThumb()) {  // FIXME thumb2
10420           // This must be a constant between -255 and -1, for negated ADD
10421           // immediates. This can be used in GCC with an "n" modifier that
10422           // prints the negated value, for use with SUB instructions. It is
10423           // not useful otherwise but is implemented for compatibility.
10424           if (CVal >= -255 && CVal <= -1)
10425             break;
10426         } else {
10427           // This must be a constant between -4095 and 4095. It is not clear
10428           // what this constraint is intended for. Implemented for
10429           // compatibility with GCC.
10430           if (CVal >= -4095 && CVal <= 4095)
10431             break;
10432         }
10433         return;
10434
10435       case 'K':
10436         if (Subtarget->isThumb1Only()) {
10437           // A 32-bit value where only one byte has a nonzero value. Exclude
10438           // zero to match GCC. This constraint is used by GCC internally for
10439           // constants that can be loaded with a move/shift combination.
10440           // It is not useful otherwise but is implemented for compatibility.
10441           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10442             break;
10443         } else if (Subtarget->isThumb2()) {
10444           // A constant whose bitwise inverse can be used as an immediate
10445           // value in a data-processing instruction. This can be used in GCC
10446           // with a "B" modifier that prints the inverted value, for use with
10447           // BIC and MVN instructions. It is not useful otherwise but is
10448           // implemented for compatibility.
10449           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10450             break;
10451         } else {
10452           // A constant whose bitwise inverse can be used as an immediate
10453           // value in a data-processing instruction. This can be used in GCC
10454           // with a "B" modifier that prints the inverted value, for use with
10455           // BIC and MVN instructions. It is not useful otherwise but is
10456           // implemented for compatibility.
10457           if (ARM_AM::getSOImmVal(~CVal) != -1)
10458             break;
10459         }
10460         return;
10461
10462       case 'L':
10463         if (Subtarget->isThumb1Only()) {
10464           // This must be a constant between -7 and 7,
10465           // for 3-operand ADD/SUB immediate instructions.
10466           if (CVal >= -7 && CVal < 7)
10467             break;
10468         } else if (Subtarget->isThumb2()) {
10469           // A constant whose negation can be used as an immediate value in a
10470           // data-processing instruction. This can be used in GCC with an "n"
10471           // modifier that prints the negated value, for use with SUB
10472           // instructions. It is not useful otherwise but is implemented for
10473           // compatibility.
10474           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10475             break;
10476         } else {
10477           // A constant whose negation can be used as an immediate value in a
10478           // data-processing instruction. This can be used in GCC with an "n"
10479           // modifier that prints the negated value, for use with SUB
10480           // instructions. It is not useful otherwise but is implemented for
10481           // compatibility.
10482           if (ARM_AM::getSOImmVal(-CVal) != -1)
10483             break;
10484         }
10485         return;
10486
10487       case 'M':
10488         if (Subtarget->isThumb()) { // FIXME thumb2
10489           // This must be a multiple of 4 between 0 and 1020, for
10490           // ADD sp + immediate.
10491           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10492             break;
10493         } else {
10494           // A power of two or a constant between 0 and 32.  This is used in
10495           // GCC for the shift amount on shifted register operands, but it is
10496           // useful in general for any shift amounts.
10497           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10498             break;
10499         }
10500         return;
10501
10502       case 'N':
10503         if (Subtarget->isThumb()) {  // FIXME thumb2
10504           // This must be a constant between 0 and 31, for shift amounts.
10505           if (CVal >= 0 && CVal <= 31)
10506             break;
10507         }
10508         return;
10509
10510       case 'O':
10511         if (Subtarget->isThumb()) {  // FIXME thumb2
10512           // This must be a multiple of 4 between -508 and 508, for
10513           // ADD/SUB sp = sp + immediate.
10514           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10515             break;
10516         }
10517         return;
10518     }
10519     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10520     break;
10521   }
10522
10523   if (Result.getNode()) {
10524     Ops.push_back(Result);
10525     return;
10526   }
10527   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10528 }
10529
10530 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10531   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10532   unsigned Opcode = Op->getOpcode();
10533   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10534       "Invalid opcode for Div/Rem lowering");
10535   bool isSigned = (Opcode == ISD::SDIVREM);
10536   EVT VT = Op->getValueType(0);
10537   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10538
10539   RTLIB::Libcall LC;
10540   switch (VT.getSimpleVT().SimpleTy) {
10541   default: llvm_unreachable("Unexpected request for libcall!");
10542   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10543   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10544   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10545   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10546   }
10547
10548   SDValue InChain = DAG.getEntryNode();
10549
10550   TargetLowering::ArgListTy Args;
10551   TargetLowering::ArgListEntry Entry;
10552   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10553     EVT ArgVT = Op->getOperand(i).getValueType();
10554     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10555     Entry.Node = Op->getOperand(i);
10556     Entry.Ty = ArgTy;
10557     Entry.isSExt = isSigned;
10558     Entry.isZExt = !isSigned;
10559     Args.push_back(Entry);
10560   }
10561
10562   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10563                                          getPointerTy());
10564
10565   Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10566
10567   SDLoc dl(Op);
10568   TargetLowering::CallLoweringInfo CLI(DAG);
10569   CLI.setDebugLoc(dl).setChain(InChain)
10570     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10571     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10572
10573   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10574   return CallInfo.first;
10575 }
10576
10577 SDValue
10578 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10579   assert(Subtarget->isTargetWindows() && "unsupported target platform");
10580   SDLoc DL(Op);
10581
10582   // Get the inputs.
10583   SDValue Chain = Op.getOperand(0);
10584   SDValue Size  = Op.getOperand(1);
10585
10586   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10587                               DAG.getConstant(2, MVT::i32));
10588
10589   SDValue Flag;
10590   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10591   Flag = Chain.getValue(1);
10592
10593   SDVTList NodeTys = DAG.getVTList(MVT::i32, MVT::Glue);
10594   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10595
10596   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10597   Chain = NewSP.getValue(1);
10598
10599   SDValue Ops[2] = { NewSP, Chain };
10600   return DAG.getMergeValues(Ops, DL);
10601 }
10602
10603 bool
10604 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10605   // The ARM target isn't yet aware of offsets.
10606   return false;
10607 }
10608
10609 bool ARM::isBitFieldInvertedMask(unsigned v) {
10610   if (v == 0xffffffff)
10611     return false;
10612
10613   // there can be 1's on either or both "outsides", all the "inside"
10614   // bits must be 0's
10615   unsigned TO = CountTrailingOnes_32(v);
10616   unsigned LO = CountLeadingOnes_32(v);
10617   v = (v >> TO) << TO;
10618   v = (v << LO) >> LO;
10619   return v == 0;
10620 }
10621
10622 /// isFPImmLegal - Returns true if the target can instruction select the
10623 /// specified FP immediate natively. If false, the legalizer will
10624 /// materialize the FP immediate as a load from a constant pool.
10625 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10626   if (!Subtarget->hasVFP3())
10627     return false;
10628   if (VT == MVT::f32)
10629     return ARM_AM::getFP32Imm(Imm) != -1;
10630   if (VT == MVT::f64)
10631     return ARM_AM::getFP64Imm(Imm) != -1;
10632   return false;
10633 }
10634
10635 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10636 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10637 /// specified in the intrinsic calls.
10638 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10639                                            const CallInst &I,
10640                                            unsigned Intrinsic) const {
10641   switch (Intrinsic) {
10642   case Intrinsic::arm_neon_vld1:
10643   case Intrinsic::arm_neon_vld2:
10644   case Intrinsic::arm_neon_vld3:
10645   case Intrinsic::arm_neon_vld4:
10646   case Intrinsic::arm_neon_vld2lane:
10647   case Intrinsic::arm_neon_vld3lane:
10648   case Intrinsic::arm_neon_vld4lane: {
10649     Info.opc = ISD::INTRINSIC_W_CHAIN;
10650     // Conservatively set memVT to the entire set of vectors loaded.
10651     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10652     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10653     Info.ptrVal = I.getArgOperand(0);
10654     Info.offset = 0;
10655     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10656     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10657     Info.vol = false; // volatile loads with NEON intrinsics not supported
10658     Info.readMem = true;
10659     Info.writeMem = false;
10660     return true;
10661   }
10662   case Intrinsic::arm_neon_vst1:
10663   case Intrinsic::arm_neon_vst2:
10664   case Intrinsic::arm_neon_vst3:
10665   case Intrinsic::arm_neon_vst4:
10666   case Intrinsic::arm_neon_vst2lane:
10667   case Intrinsic::arm_neon_vst3lane:
10668   case Intrinsic::arm_neon_vst4lane: {
10669     Info.opc = ISD::INTRINSIC_VOID;
10670     // Conservatively set memVT to the entire set of vectors stored.
10671     unsigned NumElts = 0;
10672     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10673       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10674       if (!ArgTy->isVectorTy())
10675         break;
10676       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10677     }
10678     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10679     Info.ptrVal = I.getArgOperand(0);
10680     Info.offset = 0;
10681     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10682     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10683     Info.vol = false; // volatile stores with NEON intrinsics not supported
10684     Info.readMem = false;
10685     Info.writeMem = true;
10686     return true;
10687   }
10688   case Intrinsic::arm_ldaex:
10689   case Intrinsic::arm_ldrex: {
10690     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10691     Info.opc = ISD::INTRINSIC_W_CHAIN;
10692     Info.memVT = MVT::getVT(PtrTy->getElementType());
10693     Info.ptrVal = I.getArgOperand(0);
10694     Info.offset = 0;
10695     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10696     Info.vol = true;
10697     Info.readMem = true;
10698     Info.writeMem = false;
10699     return true;
10700   }
10701   case Intrinsic::arm_stlex:
10702   case Intrinsic::arm_strex: {
10703     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10704     Info.opc = ISD::INTRINSIC_W_CHAIN;
10705     Info.memVT = MVT::getVT(PtrTy->getElementType());
10706     Info.ptrVal = I.getArgOperand(1);
10707     Info.offset = 0;
10708     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10709     Info.vol = true;
10710     Info.readMem = false;
10711     Info.writeMem = true;
10712     return true;
10713   }
10714   case Intrinsic::arm_stlexd:
10715   case Intrinsic::arm_strexd: {
10716     Info.opc = ISD::INTRINSIC_W_CHAIN;
10717     Info.memVT = MVT::i64;
10718     Info.ptrVal = I.getArgOperand(2);
10719     Info.offset = 0;
10720     Info.align = 8;
10721     Info.vol = true;
10722     Info.readMem = false;
10723     Info.writeMem = true;
10724     return true;
10725   }
10726   case Intrinsic::arm_ldaexd:
10727   case Intrinsic::arm_ldrexd: {
10728     Info.opc = ISD::INTRINSIC_W_CHAIN;
10729     Info.memVT = MVT::i64;
10730     Info.ptrVal = I.getArgOperand(0);
10731     Info.offset = 0;
10732     Info.align = 8;
10733     Info.vol = true;
10734     Info.readMem = true;
10735     Info.writeMem = false;
10736     return true;
10737   }
10738   default:
10739     break;
10740   }
10741
10742   return false;
10743 }
10744
10745 /// \brief Returns true if it is beneficial to convert a load of a constant
10746 /// to just the constant itself.
10747 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10748                                                           Type *Ty) const {
10749   assert(Ty->isIntegerTy());
10750
10751   unsigned Bits = Ty->getPrimitiveSizeInBits();
10752   if (Bits == 0 || Bits > 32)
10753     return false;
10754   return true;
10755 }
10756
10757 bool ARMTargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
10758   // Loads and stores less than 64-bits are already atomic; ones above that
10759   // are doomed anyway, so defer to the default libcall and blame the OS when
10760   // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
10761   // anything for those.
10762   bool IsMClass = Subtarget->isMClass();
10763   if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
10764     unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10765     return Size == 64 && !IsMClass;
10766   } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
10767     return LI->getType()->getPrimitiveSizeInBits() == 64 && !IsMClass;
10768   }
10769
10770   // For the real atomic operations, we have ldrex/strex up to 32 bits,
10771   // and up to 64 bits on the non-M profiles
10772   unsigned AtomicLimit = IsMClass ? 32 : 64;
10773   return Inst->getType()->getPrimitiveSizeInBits() <= AtomicLimit;
10774 }
10775
10776 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10777                                          AtomicOrdering Ord) const {
10778   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10779   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10780   bool IsAcquire =
10781       Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10782
10783   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
10784   // intrinsic must return {i32, i32} and we have to recombine them into a
10785   // single i64 here.
10786   if (ValTy->getPrimitiveSizeInBits() == 64) {
10787     Intrinsic::ID Int =
10788         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
10789     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
10790
10791     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10792     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
10793
10794     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10795     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10796     if (!Subtarget->isLittle())
10797       std::swap (Lo, Hi);
10798     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10799     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10800     return Builder.CreateOr(
10801         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
10802   }
10803
10804   Type *Tys[] = { Addr->getType() };
10805   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
10806   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10807
10808   return Builder.CreateTruncOrBitCast(
10809       Builder.CreateCall(Ldrex, Addr),
10810       cast<PointerType>(Addr->getType())->getElementType());
10811 }
10812
10813 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
10814                                                Value *Addr,
10815                                                AtomicOrdering Ord) const {
10816   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10817   bool IsRelease =
10818       Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10819
10820   // Since the intrinsics must have legal type, the i64 intrinsics take two
10821   // parameters: "i32, i32". We must marshal Val into the appropriate form
10822   // before the call.
10823   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
10824     Intrinsic::ID Int =
10825         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
10826     Function *Strex = Intrinsic::getDeclaration(M, Int);
10827     Type *Int32Ty = Type::getInt32Ty(M->getContext());
10828
10829     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
10830     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
10831     if (!Subtarget->isLittle())
10832       std::swap (Lo, Hi);
10833     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10834     return Builder.CreateCall3(Strex, Lo, Hi, Addr);
10835   }
10836
10837   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
10838   Type *Tys[] = { Addr->getType() };
10839   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
10840
10841   return Builder.CreateCall2(
10842       Strex, Builder.CreateZExtOrBitCast(
10843                  Val, Strex->getFunctionType()->getParamType(0)),
10844       Addr);
10845 }
10846
10847 enum HABaseType {
10848   HA_UNKNOWN = 0,
10849   HA_FLOAT,
10850   HA_DOUBLE,
10851   HA_VECT64,
10852   HA_VECT128
10853 };
10854
10855 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
10856                                    uint64_t &Members) {
10857   if (const StructType *ST = dyn_cast<StructType>(Ty)) {
10858     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
10859       uint64_t SubMembers = 0;
10860       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
10861         return false;
10862       Members += SubMembers;
10863     }
10864   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
10865     uint64_t SubMembers = 0;
10866     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
10867       return false;
10868     Members += SubMembers * AT->getNumElements();
10869   } else if (Ty->isFloatTy()) {
10870     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
10871       return false;
10872     Members = 1;
10873     Base = HA_FLOAT;
10874   } else if (Ty->isDoubleTy()) {
10875     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
10876       return false;
10877     Members = 1;
10878     Base = HA_DOUBLE;
10879   } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
10880     Members = 1;
10881     switch (Base) {
10882     case HA_FLOAT:
10883     case HA_DOUBLE:
10884       return false;
10885     case HA_VECT64:
10886       return VT->getBitWidth() == 64;
10887     case HA_VECT128:
10888       return VT->getBitWidth() == 128;
10889     case HA_UNKNOWN:
10890       switch (VT->getBitWidth()) {
10891       case 64:
10892         Base = HA_VECT64;
10893         return true;
10894       case 128:
10895         Base = HA_VECT128;
10896         return true;
10897       default:
10898         return false;
10899       }
10900     }
10901   }
10902
10903   return (Members > 0 && Members <= 4);
10904 }
10905
10906 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate.
10907 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
10908     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10909   if (getEffectiveCallingConv(CallConv, isVarArg) !=
10910       CallingConv::ARM_AAPCS_VFP)
10911     return false;
10912
10913   HABaseType Base = HA_UNKNOWN;
10914   uint64_t Members = 0;
10915   bool result = isHomogeneousAggregate(Ty, Base, Members);
10916   DEBUG(dbgs() << "isHA: " << result << " "; Ty->dump(); dbgs() << "\n");
10917   return result;
10918 }