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 #define DEBUG_TYPE "arm-isel"
16 #include "ARM.h"
17 #include "ARMAddressingModes.h"
18 #include "ARMCallingConv.h"
19 #include "ARMConstantPoolValue.h"
20 #include "ARMISelLowering.h"
21 #include "ARMMachineFunctionInfo.h"
22 #include "ARMPerfectShuffle.h"
23 #include "ARMRegisterInfo.h"
24 #include "ARMSubtarget.h"
25 #include "ARMTargetMachine.h"
26 #include "ARMTargetObjectFile.h"
27 #include "llvm/CallingConv.h"
28 #include "llvm/Constants.h"
29 #include "llvm/Function.h"
30 #include "llvm/GlobalValue.h"
31 #include "llvm/Instruction.h"
32 #include "llvm/Instructions.h"
33 #include "llvm/Intrinsics.h"
34 #include "llvm/Type.h"
35 #include "llvm/CodeGen/CallingConvLower.h"
36 #include "llvm/CodeGen/IntrinsicLowering.h"
37 #include "llvm/CodeGen/MachineBasicBlock.h"
38 #include "llvm/CodeGen/MachineFrameInfo.h"
39 #include "llvm/CodeGen/MachineFunction.h"
40 #include "llvm/CodeGen/MachineInstrBuilder.h"
41 #include "llvm/CodeGen/MachineRegisterInfo.h"
42 #include "llvm/CodeGen/PseudoSourceValue.h"
43 #include "llvm/CodeGen/SelectionDAG.h"
44 #include "llvm/MC/MCSectionMachO.h"
45 #include "llvm/Target/TargetOptions.h"
46 #include "llvm/ADT/VectorExtras.h"
47 #include "llvm/ADT/StringExtras.h"
48 #include "llvm/ADT/Statistic.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include <sstream>
54 using namespace llvm;
55 
56 STATISTIC(NumTailCalls, "Number of tail calls");
57 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
58 
59 // This option should go away when tail calls fully work.
60 static cl::opt<bool>
61 EnableARMTailCalls("arm-tail-calls", cl::Hidden,
62   cl::desc("Generate tail calls (TEMPORARY OPTION)."),
63   cl::init(false));
64 
65 cl::opt<bool>
66 EnableARMLongCalls("arm-long-calls", cl::Hidden,
67   cl::desc("Generate calls via indirect call instructions"),
68   cl::init(false));
69 
70 static cl::opt<bool>
71 ARMInterworking("arm-interworking", cl::Hidden,
72   cl::desc("Enable / disable ARM interworking (for debugging only)"),
73   cl::init(true));
74 
75 void ARMTargetLowering::addTypeForNEON(EVT VT, EVT PromotedLdStVT,
76                                        EVT PromotedBitwiseVT) {
77   if (VT != PromotedLdStVT) {
78     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
79     AddPromotedToType (ISD::LOAD, VT.getSimpleVT(),
80                        PromotedLdStVT.getSimpleVT());
81 
82     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
83     AddPromotedToType (ISD::STORE, VT.getSimpleVT(),
84                        PromotedLdStVT.getSimpleVT());
85   }
86 
87   EVT ElemTy = VT.getVectorElementType();
88   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
89     setOperationAction(ISD::VSETCC, VT.getSimpleVT(), Custom);
90   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
91   if (ElemTy != MVT::i32) {
92     setOperationAction(ISD::SINT_TO_FP, VT.getSimpleVT(), Expand);
93     setOperationAction(ISD::UINT_TO_FP, VT.getSimpleVT(), Expand);
94     setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Expand);
95     setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Expand);
96   }
97   setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
98   setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
99   setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
100   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Legal);
101   setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
102   setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
103   if (VT.isInteger()) {
104     setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
105     setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
106     setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
107     setLoadExtAction(ISD::SEXTLOAD, VT.getSimpleVT(), Expand);
108     setLoadExtAction(ISD::ZEXTLOAD, VT.getSimpleVT(), Expand);
109     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
110          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
111       setTruncStoreAction(VT.getSimpleVT(),
112                           (MVT::SimpleValueType)InnerVT, Expand);
113   }
114   setLoadExtAction(ISD::EXTLOAD, VT.getSimpleVT(), Expand);
115 
116   // Promote all bit-wise operations.
117   if (VT.isInteger() && VT != PromotedBitwiseVT) {
118     setOperationAction(ISD::AND, VT.getSimpleVT(), Promote);
119     AddPromotedToType (ISD::AND, VT.getSimpleVT(),
120                        PromotedBitwiseVT.getSimpleVT());
121     setOperationAction(ISD::OR,  VT.getSimpleVT(), Promote);
122     AddPromotedToType (ISD::OR,  VT.getSimpleVT(),
123                        PromotedBitwiseVT.getSimpleVT());
124     setOperationAction(ISD::XOR, VT.getSimpleVT(), Promote);
125     AddPromotedToType (ISD::XOR, VT.getSimpleVT(),
126                        PromotedBitwiseVT.getSimpleVT());
127   }
128 
129   // Neon does not support vector divide/remainder operations.
130   setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
131   setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
132   setOperationAction(ISD::FDIV, VT.getSimpleVT(), Expand);
133   setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
134   setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
135   setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
136 }
137 
138 void ARMTargetLowering::addDRTypeForNEON(EVT VT) {
139   addRegisterClass(VT, ARM::DPRRegisterClass);
140   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
141 }
142 
143 void ARMTargetLowering::addQRTypeForNEON(EVT VT) {
144   addRegisterClass(VT, ARM::QPRRegisterClass);
145   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
146 }
147 
148 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
149   if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
150     return new TargetLoweringObjectFileMachO();
151 
152   return new ARMElfTargetObjectFile();
153 }
154 
155 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
156     : TargetLowering(TM, createTLOF(TM)) {
157   Subtarget = &TM.getSubtarget<ARMSubtarget>();
158   RegInfo = TM.getRegisterInfo();
159   Itins = TM.getInstrItineraryData();
160 
161   if (Subtarget->isTargetDarwin()) {
162     // Uses VFP for Thumb libfuncs if available.
163     if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
164       // Single-precision floating-point arithmetic.
165       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
166       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
167       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
168       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
169 
170       // Double-precision floating-point arithmetic.
171       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
172       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
173       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
174       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
175 
176       // Single-precision comparisons.
177       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
178       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
179       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
180       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
181       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
182       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
183       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
184       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
185 
186       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
187       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
188       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
189       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
190       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
191       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
192       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
193       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
194 
195       // Double-precision comparisons.
196       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
197       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
198       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
199       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
200       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
201       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
202       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
203       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
204 
205       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
206       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
207       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
208       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
209       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
210       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
211       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
212       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
213 
214       // Floating-point to integer conversions.
215       // i64 conversions are done via library routines even when generating VFP
216       // instructions, so use the same ones.
217       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
218       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
219       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
220       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
221 
222       // Conversions between floating types.
223       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
224       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
225 
226       // Integer to floating-point conversions.
227       // i64 conversions are done via library routines even when generating VFP
228       // instructions, so use the same ones.
229       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
230       // e.g., __floatunsidf vs. __floatunssidfvfp.
231       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
232       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
233       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
234       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
235     }
236   }
237 
238   // These libcalls are not available in 32-bit.
239   setLibcallName(RTLIB::SHL_I128, 0);
240   setLibcallName(RTLIB::SRL_I128, 0);
241   setLibcallName(RTLIB::SRA_I128, 0);
242 
243   if (Subtarget->isAAPCS_ABI()) {
244     // Double-precision floating-point arithmetic helper functions
245     // RTABI chapter 4.1.2, Table 2
246     setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
247     setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
248     setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
249     setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
250     setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
251     setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
252     setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
253     setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
254 
255     // Double-precision floating-point comparison helper functions
256     // RTABI chapter 4.1.2, Table 3
257     setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
258     setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
259     setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
260     setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
261     setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
262     setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
263     setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
264     setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
265     setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
266     setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
267     setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
268     setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
269     setLibcallName(RTLIB::UO_F64,  "__aeabi_dcmpun");
270     setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
271     setLibcallName(RTLIB::O_F64,   "__aeabi_dcmpun");
272     setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
273     setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
274     setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
275     setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
276     setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
277     setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
278     setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
279     setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
280     setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
281 
282     // Single-precision floating-point arithmetic helper functions
283     // RTABI chapter 4.1.2, Table 4
284     setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
285     setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
286     setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
287     setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
288     setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
289     setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
290     setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
291     setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
292 
293     // Single-precision floating-point comparison helper functions
294     // RTABI chapter 4.1.2, Table 5
295     setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
296     setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
297     setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
298     setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
299     setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
300     setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
301     setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
302     setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
303     setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
304     setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
305     setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
306     setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
307     setLibcallName(RTLIB::UO_F32,  "__aeabi_fcmpun");
308     setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
309     setLibcallName(RTLIB::O_F32,   "__aeabi_fcmpun");
310     setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
311     setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
312     setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
313     setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
314     setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
315     setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
316     setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
317     setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
318     setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
319 
320     // Floating-point to integer conversions.
321     // RTABI chapter 4.1.2, Table 6
322     setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
323     setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
324     setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
325     setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
326     setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
327     setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
328     setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
329     setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
330     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
331     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
332     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
333     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
334     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
335     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
336     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
337     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
338 
339     // Conversions between floating types.
340     // RTABI chapter 4.1.2, Table 7
341     setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
342     setLibcallName(RTLIB::FPEXT_F32_F64,   "__aeabi_f2d");
343     setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
344     setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
345 
346     // Integer to floating-point conversions.
347     // RTABI chapter 4.1.2, Table 8
348     setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
349     setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
350     setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
351     setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
352     setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
353     setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
354     setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
355     setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
356     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
357     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
358     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
359     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
360     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
361     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
362     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
363     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
364 
365     // Long long helper functions
366     // RTABI chapter 4.2, Table 9
367     setLibcallName(RTLIB::MUL_I64,  "__aeabi_lmul");
368     setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
369     setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
370     setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
371     setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
372     setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
373     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
374     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
375     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
376     setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
377     setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
378     setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
379 
380     // Integer division functions
381     // RTABI chapter 4.3.1
382     setLibcallName(RTLIB::SDIV_I8,  "__aeabi_idiv");
383     setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
384     setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
385     setLibcallName(RTLIB::UDIV_I8,  "__aeabi_uidiv");
386     setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
387     setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
388     setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
389     setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
390     setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
391     setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
392     setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
393     setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
394   }
395 
396   if (HasDivModLibcall) {
397     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
398     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
399   }
400 
401   if (Subtarget->isThumb1Only())
402     addRegisterClass(MVT::i32, ARM::tGPRRegisterClass);
403   else
404     addRegisterClass(MVT::i32, ARM::GPRRegisterClass);
405   if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb1Only()) {
406     addRegisterClass(MVT::f32, ARM::SPRRegisterClass);
407     if (!Subtarget->isFPOnlySP())
408       addRegisterClass(MVT::f64, ARM::DPRRegisterClass);
409 
410     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
411   }
412 
413   if (Subtarget->hasNEON()) {
414     addDRTypeForNEON(MVT::v2f32);
415     addDRTypeForNEON(MVT::v8i8);
416     addDRTypeForNEON(MVT::v4i16);
417     addDRTypeForNEON(MVT::v2i32);
418     addDRTypeForNEON(MVT::v1i64);
419 
420     addQRTypeForNEON(MVT::v4f32);
421     addQRTypeForNEON(MVT::v2f64);
422     addQRTypeForNEON(MVT::v16i8);
423     addQRTypeForNEON(MVT::v8i16);
424     addQRTypeForNEON(MVT::v4i32);
425     addQRTypeForNEON(MVT::v2i64);
426 
427     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
428     // neither Neon nor VFP support any arithmetic operations on it.
429     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
430     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
431     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
432     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
433     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
434     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
435     setOperationAction(ISD::VSETCC, MVT::v2f64, Expand);
436     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
437     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
438     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
439     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
440     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
441     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
442     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
443     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
444     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
445     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
446     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
447     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
448     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
449     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
450     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
451     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
452     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
453 
454     setTruncStoreAction(MVT::v2f64, MVT::v2f32, Expand);
455 
456     // Neon does not support some operations on v1i64 and v2i64 types.
457     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
458     // Custom handling for some quad-vector types to detect VMULL.
459     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
460     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
461     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
462     // Custom handling for some vector types to avoid expensive expansions
463     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
464     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
465     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
466     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
467     setOperationAction(ISD::VSETCC, MVT::v1i64, Expand);
468     setOperationAction(ISD::VSETCC, MVT::v2i64, Expand);
469     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
470     // a destination type that is wider than the source.
471     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
472     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
473 
474     setTargetDAGCombine(ISD::INTRINSIC_VOID);
475     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
476     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
477     setTargetDAGCombine(ISD::SHL);
478     setTargetDAGCombine(ISD::SRL);
479     setTargetDAGCombine(ISD::SRA);
480     setTargetDAGCombine(ISD::SIGN_EXTEND);
481     setTargetDAGCombine(ISD::ZERO_EXTEND);
482     setTargetDAGCombine(ISD::ANY_EXTEND);
483     setTargetDAGCombine(ISD::SELECT_CC);
484     setTargetDAGCombine(ISD::BUILD_VECTOR);
485     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
486     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
487     setTargetDAGCombine(ISD::STORE);
488   }
489 
490   computeRegisterProperties();
491 
492   // ARM does not have f32 extending load.
493   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
494 
495   // ARM does not have i1 sign extending load.
496   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
497 
498   // ARM supports all 4 flavors of integer indexed load / store.
499   if (!Subtarget->isThumb1Only()) {
500     for (unsigned im = (unsigned)ISD::PRE_INC;
501          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
502       setIndexedLoadAction(im,  MVT::i1,  Legal);
503       setIndexedLoadAction(im,  MVT::i8,  Legal);
504       setIndexedLoadAction(im,  MVT::i16, Legal);
505       setIndexedLoadAction(im,  MVT::i32, Legal);
506       setIndexedStoreAction(im, MVT::i1,  Legal);
507       setIndexedStoreAction(im, MVT::i8,  Legal);
508       setIndexedStoreAction(im, MVT::i16, Legal);
509       setIndexedStoreAction(im, MVT::i32, Legal);
510     }
511   }
512 
513   // i64 operation support.
514   if (Subtarget->isThumb1Only()) {
515     setOperationAction(ISD::MUL,     MVT::i64, Expand);
516     setOperationAction(ISD::MULHU,   MVT::i32, Expand);
517     setOperationAction(ISD::MULHS,   MVT::i32, Expand);
518     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
519     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
520   } else {
521     setOperationAction(ISD::MUL,     MVT::i64, Expand);
522     setOperationAction(ISD::MULHU,   MVT::i32, Expand);
523     if (!Subtarget->hasV6Ops())
524       setOperationAction(ISD::MULHS, MVT::i32, Expand);
525   }
526   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
527   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
528   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
529   setOperationAction(ISD::SRL,       MVT::i64, Custom);
530   setOperationAction(ISD::SRA,       MVT::i64, Custom);
531 
532   // ARM does not have ROTL.
533   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
534   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
535   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
536   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
537     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
538 
539   // Only ARMv6 has BSWAP.
540   if (!Subtarget->hasV6Ops())
541     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
542 
543   // These are expanded into libcalls.
544   if (!Subtarget->hasDivide() || !Subtarget->isThumb2()) {
545     // v7M has a hardware divider
546     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
547     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
548   }
549   setOperationAction(ISD::SREM,  MVT::i32, Expand);
550   setOperationAction(ISD::UREM,  MVT::i32, Expand);
551   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
552   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
553 
554   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
555   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
556   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
557   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
558   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
559 
560   setOperationAction(ISD::TRAP, MVT::Other, Legal);
561 
562   // Use the default implementation.
563   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
564   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
565   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
566   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
567   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
568   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
569   setOperationAction(ISD::EHSELECTION,        MVT::i32,   Expand);
570   setOperationAction(ISD::EXCEPTIONADDR,      MVT::i32,   Expand);
571   setExceptionPointerRegister(ARM::R0);
572   setExceptionSelectorRegister(ARM::R1);
573 
574   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
575   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
576   // the default expansion.
577   if (Subtarget->hasDataBarrier() ||
578       (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
579     // membarrier needs custom lowering; the rest are legal and handled
580     // normally.
581     setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
582   } else {
583     // Set them all for expansion, which will force libcalls.
584     setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
585     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i8,  Expand);
586     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i16, Expand);
587     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
588     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i8,  Expand);
589     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i16, Expand);
590     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
591     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i8,  Expand);
592     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i16, Expand);
593     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
594     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i8,  Expand);
595     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i16, Expand);
596     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
597     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i8,  Expand);
598     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i16, Expand);
599     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
600     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i8,  Expand);
601     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i16, Expand);
602     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
603     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i8,  Expand);
604     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i16, Expand);
605     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
606     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i8,  Expand);
607     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i16, Expand);
608     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
609     // Since the libcalls include locking, fold in the fences
610     setShouldFoldAtomicFences(true);
611   }
612   // 64-bit versions are always libcalls (for now)
613   setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Expand);
614   setOperationAction(ISD::ATOMIC_SWAP,      MVT::i64, Expand);
615   setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i64, Expand);
616   setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i64, Expand);
617   setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i64, Expand);
618   setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i64, Expand);
619   setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i64, Expand);
620   setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Expand);
621 
622   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
623 
624   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
625   if (!Subtarget->hasV6Ops()) {
626     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
627     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
628   }
629   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
630 
631   if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb1Only()) {
632     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
633     // iff target supports vfp2.
634     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
635     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
636   }
637 
638   // We want to custom lower some of our intrinsics.
639   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
640   if (Subtarget->isTargetDarwin()) {
641     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
642     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
643     setOperationAction(ISD::EH_SJLJ_DISPATCHSETUP, MVT::Other, Custom);
644   }
645 
646   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
647   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
648   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
649   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
650   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
651   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
652   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
653   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
654   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
655 
656   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
657   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
658   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
659   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
660   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
661 
662   // We don't support sin/cos/fmod/copysign/pow
663   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
664   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
665   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
666   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
667   setOperationAction(ISD::FREM,      MVT::f64, Expand);
668   setOperationAction(ISD::FREM,      MVT::f32, Expand);
669   if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb1Only()) {
670     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
671     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
672   }
673   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
674   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
675 
676   // Various VFP goodness
677   if (!UseSoftFloat && !Subtarget->isThumb1Only()) {
678     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
679     if (Subtarget->hasVFP2()) {
680       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
681       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
682       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
683       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
684     }
685     // Special handling for half-precision FP.
686     if (!Subtarget->hasFP16()) {
687       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
688       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
689     }
690   }
691 
692   // We have target-specific dag combine patterns for the following nodes:
693   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
694   setTargetDAGCombine(ISD::ADD);
695   setTargetDAGCombine(ISD::SUB);
696   setTargetDAGCombine(ISD::MUL);
697 
698   if (Subtarget->hasV6T2Ops() || Subtarget->hasNEON())
699     setTargetDAGCombine(ISD::OR);
700   if (Subtarget->hasNEON())
701     setTargetDAGCombine(ISD::AND);
702 
703   setStackPointerRegisterToSaveRestore(ARM::SP);
704 
705   if (UseSoftFloat || Subtarget->isThumb1Only() || !Subtarget->hasVFP2())
706     setSchedulingPreference(Sched::RegPressure);
707   else
708     setSchedulingPreference(Sched::Hybrid);
709 
710   //// temporary - rewrite interface to use type
711   maxStoresPerMemcpy = maxStoresPerMemcpyOptSize = 1;
712 
713   // On ARM arguments smaller than 4 bytes are extended, so all arguments
714   // are at least 4 bytes aligned.
715   setMinStackArgumentAlignment(4);
716 
717   benefitFromCodePlacementOpt = true;
718 }
719 
720 // FIXME: It might make sense to define the representative register class as the
721 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
722 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
723 // SPR's representative would be DPR_VFP2. This should work well if register
724 // pressure tracking were modified such that a register use would increment the
725 // pressure of the register class's representative and all of it's super
726 // classes' representatives transitively. We have not implemented this because
727 // of the difficulty prior to coalescing of modeling operand register classes
728 // due to the common occurrence of cross class copies and subregister insertions
729 // and extractions.
730 std::pair<const TargetRegisterClass*, uint8_t>
731 ARMTargetLowering::findRepresentativeClass(EVT VT) const{
732   const TargetRegisterClass *RRC = 0;
733   uint8_t Cost = 1;
734   switch (VT.getSimpleVT().SimpleTy) {
735   default:
736     return TargetLowering::findRepresentativeClass(VT);
737   // Use DPR as representative register class for all floating point
738   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
739   // the cost is 1 for both f32 and f64.
740   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
741   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
742     RRC = ARM::DPRRegisterClass;
743     // When NEON is used for SP, only half of the register file is available
744     // because operations that define both SP and DP results will be constrained
745     // to the VFP2 class (D0-D15). We currently model this constraint prior to
746     // coalescing by double-counting the SP regs. See the FIXME above.
747     if (Subtarget->useNEONForSinglePrecisionFP())
748       Cost = 2;
749     break;
750   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
751   case MVT::v4f32: case MVT::v2f64:
752     RRC = ARM::DPRRegisterClass;
753     Cost = 2;
754     break;
755   case MVT::v4i64:
756     RRC = ARM::DPRRegisterClass;
757     Cost = 4;
758     break;
759   case MVT::v8i64:
760     RRC = ARM::DPRRegisterClass;
761     Cost = 8;
762     break;
763   }
764   return std::make_pair(RRC, Cost);
765 }
766 
767 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
768   switch (Opcode) {
769   default: return 0;
770   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
771   case ARMISD::WrapperDYN:    return "ARMISD::WrapperDYN";
772   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
773   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
774   case ARMISD::CALL:          return "ARMISD::CALL";
775   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
776   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
777   case ARMISD::tCALL:         return "ARMISD::tCALL";
778   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
779   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
780   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
781   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
782   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
783   case ARMISD::CMP:           return "ARMISD::CMP";
784   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
785   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
786   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
787   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
788   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
789   case ARMISD::CMOV:          return "ARMISD::CMOV";
790 
791   case ARMISD::RBIT:          return "ARMISD::RBIT";
792 
793   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
794   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
795   case ARMISD::SITOF:         return "ARMISD::SITOF";
796   case ARMISD::UITOF:         return "ARMISD::UITOF";
797 
798   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
799   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
800   case ARMISD::RRX:           return "ARMISD::RRX";
801 
802   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
803   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
804 
805   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
806   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
807   case ARMISD::EH_SJLJ_DISPATCHSETUP:return "ARMISD::EH_SJLJ_DISPATCHSETUP";
808 
809   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
810 
811   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
812 
813   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
814 
815   case ARMISD::MEMBARRIER:    return "ARMISD::MEMBARRIER";
816   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
817 
818   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
819 
820   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
821   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
822   case ARMISD::VCGE:          return "ARMISD::VCGE";
823   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
824   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
825   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
826   case ARMISD::VCGT:          return "ARMISD::VCGT";
827   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
828   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
829   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
830   case ARMISD::VTST:          return "ARMISD::VTST";
831 
832   case ARMISD::VSHL:          return "ARMISD::VSHL";
833   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
834   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
835   case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
836   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
837   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
838   case ARMISD::VSHRN:         return "ARMISD::VSHRN";
839   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
840   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
841   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
842   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
843   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
844   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
845   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
846   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
847   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
848   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
849   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
850   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
851   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
852   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
853   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
854   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
855   case ARMISD::VDUP:          return "ARMISD::VDUP";
856   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
857   case ARMISD::VEXT:          return "ARMISD::VEXT";
858   case ARMISD::VREV64:        return "ARMISD::VREV64";
859   case ARMISD::VREV32:        return "ARMISD::VREV32";
860   case ARMISD::VREV16:        return "ARMISD::VREV16";
861   case ARMISD::VZIP:          return "ARMISD::VZIP";
862   case ARMISD::VUZP:          return "ARMISD::VUZP";
863   case ARMISD::VTRN:          return "ARMISD::VTRN";
864   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
865   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
866   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
867   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
868   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
869   case ARMISD::FMAX:          return "ARMISD::FMAX";
870   case ARMISD::FMIN:          return "ARMISD::FMIN";
871   case ARMISD::BFI:           return "ARMISD::BFI";
872   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
873   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
874   case ARMISD::VBSL:          return "ARMISD::VBSL";
875   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
876   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
877   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
878   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
879   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
880   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
881   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
882   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
883   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
884   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
885   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
886   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
887   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
888   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
889   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
890   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
891   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
892   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
893   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
894   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
895   }
896 }
897 
898 /// getRegClassFor - Return the register class that should be used for the
899 /// specified value type.
900 TargetRegisterClass *ARMTargetLowering::getRegClassFor(EVT VT) const {
901   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
902   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
903   // load / store 4 to 8 consecutive D registers.
904   if (Subtarget->hasNEON()) {
905     if (VT == MVT::v4i64)
906       return ARM::QQPRRegisterClass;
907     else if (VT == MVT::v8i64)
908       return ARM::QQQQPRRegisterClass;
909   }
910   return TargetLowering::getRegClassFor(VT);
911 }
912 
913 // Create a fast isel object.
914 FastISel *
915 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
916   return ARM::createFastISel(funcInfo);
917 }
918 
919 /// getFunctionAlignment - Return the Log2 alignment of this function.
920 unsigned ARMTargetLowering::getFunctionAlignment(const Function *F) const {
921   return getTargetMachine().getSubtarget<ARMSubtarget>().isThumb() ? 1 : 2;
922 }
923 
924 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
925 /// be used for loads / stores from the global.
926 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
927   return (Subtarget->isThumb1Only() ? 127 : 4095);
928 }
929 
930 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
931   unsigned NumVals = N->getNumValues();
932   if (!NumVals)
933     return Sched::RegPressure;
934 
935   for (unsigned i = 0; i != NumVals; ++i) {
936     EVT VT = N->getValueType(i);
937     if (VT == MVT::Glue || VT == MVT::Other)
938       continue;
939     if (VT.isFloatingPoint() || VT.isVector())
940       return Sched::Latency;
941   }
942 
943   if (!N->isMachineOpcode())
944     return Sched::RegPressure;
945 
946   // Load are scheduled for latency even if there instruction itinerary
947   // is not available.
948   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
949   const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
950 
951   if (TID.getNumDefs() == 0)
952     return Sched::RegPressure;
953   if (!Itins->isEmpty() &&
954       Itins->getOperandCycle(TID.getSchedClass(), 0) > 2)
955     return Sched::Latency;
956 
957   return Sched::RegPressure;
958 }
959 
960 //===----------------------------------------------------------------------===//
961 // Lowering Code
962 //===----------------------------------------------------------------------===//
963 
964 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
965 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
966   switch (CC) {
967   default: llvm_unreachable("Unknown condition code!");
968   case ISD::SETNE:  return ARMCC::NE;
969   case ISD::SETEQ:  return ARMCC::EQ;
970   case ISD::SETGT:  return ARMCC::GT;
971   case ISD::SETGE:  return ARMCC::GE;
972   case ISD::SETLT:  return ARMCC::LT;
973   case ISD::SETLE:  return ARMCC::LE;
974   case ISD::SETUGT: return ARMCC::HI;
975   case ISD::SETUGE: return ARMCC::HS;
976   case ISD::SETULT: return ARMCC::LO;
977   case ISD::SETULE: return ARMCC::LS;
978   }
979 }
980 
981 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
982 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
983                         ARMCC::CondCodes &CondCode2) {
984   CondCode2 = ARMCC::AL;
985   switch (CC) {
986   default: llvm_unreachable("Unknown FP condition!");
987   case ISD::SETEQ:
988   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
989   case ISD::SETGT:
990   case ISD::SETOGT: CondCode = ARMCC::GT; break;
991   case ISD::SETGE:
992   case ISD::SETOGE: CondCode = ARMCC::GE; break;
993   case ISD::SETOLT: CondCode = ARMCC::MI; break;
994   case ISD::SETOLE: CondCode = ARMCC::LS; break;
995   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
996   case ISD::SETO:   CondCode = ARMCC::VC; break;
997   case ISD::SETUO:  CondCode = ARMCC::VS; break;
998   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
999   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1000   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1001   case ISD::SETLT:
1002   case ISD::SETULT: CondCode = ARMCC::LT; break;
1003   case ISD::SETLE:
1004   case ISD::SETULE: CondCode = ARMCC::LE; break;
1005   case ISD::SETNE:
1006   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1007   }
1008 }
1009 
1010 //===----------------------------------------------------------------------===//
1011 //                      Calling Convention Implementation
1012 //===----------------------------------------------------------------------===//
1013 
1014 #include "ARMGenCallingConv.inc"
1015 
1016 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1017 /// given CallingConvention value.
1018 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1019                                                  bool Return,
1020                                                  bool isVarArg) const {
1021   switch (CC) {
1022   default:
1023     llvm_unreachable("Unsupported calling convention");
1024   case CallingConv::Fast:
1025     if (Subtarget->hasVFP2() && !isVarArg) {
1026       if (!Subtarget->isAAPCS_ABI())
1027         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1028       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1029       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1030     }
1031     // Fallthrough
1032   case CallingConv::C: {
1033     // Use target triple & subtarget features to do actual dispatch.
1034     if (!Subtarget->isAAPCS_ABI())
1035       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1036     else if (Subtarget->hasVFP2() &&
1037              FloatABIType == FloatABI::Hard && !isVarArg)
1038       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1039     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1040   }
1041   case CallingConv::ARM_AAPCS_VFP:
1042     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1043   case CallingConv::ARM_AAPCS:
1044     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1045   case CallingConv::ARM_APCS:
1046     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1047   }
1048 }
1049 
1050 /// LowerCallResult - Lower the result values of a call into the
1051 /// appropriate copies out of appropriate physical registers.
1052 SDValue
1053 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1054                                    CallingConv::ID CallConv, bool isVarArg,
1055                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1056                                    DebugLoc dl, SelectionDAG &DAG,
1057                                    SmallVectorImpl<SDValue> &InVals) const {
1058 
1059   // Assign locations to each value returned by this call.
1060   SmallVector<CCValAssign, 16> RVLocs;
1061   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1062                  RVLocs, *DAG.getContext());
1063   CCInfo.AnalyzeCallResult(Ins,
1064                            CCAssignFnForNode(CallConv, /* Return*/ true,
1065                                              isVarArg));
1066 
1067   // Copy all of the result registers out of their specified physreg.
1068   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1069     CCValAssign VA = RVLocs[i];
1070 
1071     SDValue Val;
1072     if (VA.needsCustom()) {
1073       // Handle f64 or half of a v2f64.
1074       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1075                                       InFlag);
1076       Chain = Lo.getValue(1);
1077       InFlag = Lo.getValue(2);
1078       VA = RVLocs[++i]; // skip ahead to next loc
1079       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1080                                       InFlag);
1081       Chain = Hi.getValue(1);
1082       InFlag = Hi.getValue(2);
1083       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1084 
1085       if (VA.getLocVT() == MVT::v2f64) {
1086         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1087         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1088                           DAG.getConstant(0, MVT::i32));
1089 
1090         VA = RVLocs[++i]; // skip ahead to next loc
1091         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1092         Chain = Lo.getValue(1);
1093         InFlag = Lo.getValue(2);
1094         VA = RVLocs[++i]; // skip ahead to next loc
1095         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1096         Chain = Hi.getValue(1);
1097         InFlag = Hi.getValue(2);
1098         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1099         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1100                           DAG.getConstant(1, MVT::i32));
1101       }
1102     } else {
1103       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1104                                InFlag);
1105       Chain = Val.getValue(1);
1106       InFlag = Val.getValue(2);
1107     }
1108 
1109     switch (VA.getLocInfo()) {
1110     default: llvm_unreachable("Unknown loc info!");
1111     case CCValAssign::Full: break;
1112     case CCValAssign::BCvt:
1113       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1114       break;
1115     }
1116 
1117     InVals.push_back(Val);
1118   }
1119 
1120   return Chain;
1121 }
1122 
1123 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1124 /// by "Src" to address "Dst" of size "Size".  Alignment information is
1125 /// specified by the specific parameter attribute.  The copy will be passed as
1126 /// a byval function parameter.
1127 /// Sometimes what we are copying is the end of a larger object, the part that
1128 /// does not fit in registers.
1129 static SDValue
1130 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1131                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1132                           DebugLoc dl) {
1133   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1134   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1135                        /*isVolatile=*/false, /*AlwaysInline=*/false,
1136                        MachinePointerInfo(0), MachinePointerInfo(0));
1137 }
1138 
1139 /// LowerMemOpCallTo - Store the argument to the stack.
1140 SDValue
1141 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1142                                     SDValue StackPtr, SDValue Arg,
1143                                     DebugLoc dl, SelectionDAG &DAG,
1144                                     const CCValAssign &VA,
1145                                     ISD::ArgFlagsTy Flags) const {
1146   unsigned LocMemOffset = VA.getLocMemOffset();
1147   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1148   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1149   if (Flags.isByVal())
1150     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1151 
1152   return DAG.getStore(Chain, dl, Arg, PtrOff,
1153                       MachinePointerInfo::getStack(LocMemOffset),
1154                       false, false, 0);
1155 }
1156 
1157 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
1158                                          SDValue Chain, SDValue &Arg,
1159                                          RegsToPassVector &RegsToPass,
1160                                          CCValAssign &VA, CCValAssign &NextVA,
1161                                          SDValue &StackPtr,
1162                                          SmallVector<SDValue, 8> &MemOpChains,
1163                                          ISD::ArgFlagsTy Flags) const {
1164 
1165   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1166                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1167   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1168 
1169   if (NextVA.isRegLoc())
1170     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1171   else {
1172     assert(NextVA.isMemLoc());
1173     if (StackPtr.getNode() == 0)
1174       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1175 
1176     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1177                                            dl, DAG, NextVA,
1178                                            Flags));
1179   }
1180 }
1181 
1182 /// LowerCall - Lowering a call into a callseq_start <-
1183 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1184 /// nodes.
1185 SDValue
1186 ARMTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1187                              CallingConv::ID CallConv, bool isVarArg,
1188                              bool &isTailCall,
1189                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1190                              const SmallVectorImpl<SDValue> &OutVals,
1191                              const SmallVectorImpl<ISD::InputArg> &Ins,
1192                              DebugLoc dl, SelectionDAG &DAG,
1193                              SmallVectorImpl<SDValue> &InVals) const {
1194   MachineFunction &MF = DAG.getMachineFunction();
1195   bool IsStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1196   bool IsSibCall = false;
1197   // Temporarily disable tail calls so things don't break.
1198   if (!EnableARMTailCalls)
1199     isTailCall = false;
1200   if (isTailCall) {
1201     // Check if it's really possible to do a tail call.
1202     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1203                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1204                                                    Outs, OutVals, Ins, DAG);
1205     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1206     // detected sibcalls.
1207     if (isTailCall) {
1208       ++NumTailCalls;
1209       IsSibCall = true;
1210     }
1211   }
1212 
1213   // Analyze operands of the call, assigning locations to each operand.
1214   SmallVector<CCValAssign, 16> ArgLocs;
1215   CCState CCInfo(CallConv, isVarArg, getTargetMachine(), ArgLocs,
1216                  *DAG.getContext());
1217   CCInfo.AnalyzeCallOperands(Outs,
1218                              CCAssignFnForNode(CallConv, /* Return*/ false,
1219                                                isVarArg));
1220 
1221   // Get a count of how many bytes are to be pushed on the stack.
1222   unsigned NumBytes = CCInfo.getNextStackOffset();
1223 
1224   // For tail calls, memory operands are available in our caller's stack.
1225   if (IsSibCall)
1226     NumBytes = 0;
1227 
1228   // Adjust the stack pointer for the new arguments...
1229   // These operations are automatically eliminated by the prolog/epilog pass
1230   if (!IsSibCall)
1231     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1232 
1233   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1234 
1235   RegsToPassVector RegsToPass;
1236   SmallVector<SDValue, 8> MemOpChains;
1237 
1238   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1239   // of tail call optimization, arguments are handled later.
1240   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1241        i != e;
1242        ++i, ++realArgIdx) {
1243     CCValAssign &VA = ArgLocs[i];
1244     SDValue Arg = OutVals[realArgIdx];
1245     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1246     bool isByVal = Flags.isByVal();
1247 
1248     // Promote the value if needed.
1249     switch (VA.getLocInfo()) {
1250     default: llvm_unreachable("Unknown loc info!");
1251     case CCValAssign::Full: break;
1252     case CCValAssign::SExt:
1253       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1254       break;
1255     case CCValAssign::ZExt:
1256       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1257       break;
1258     case CCValAssign::AExt:
1259       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1260       break;
1261     case CCValAssign::BCvt:
1262       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1263       break;
1264     }
1265 
1266     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1267     if (VA.needsCustom()) {
1268       if (VA.getLocVT() == MVT::v2f64) {
1269         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1270                                   DAG.getConstant(0, MVT::i32));
1271         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1272                                   DAG.getConstant(1, MVT::i32));
1273 
1274         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1275                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1276 
1277         VA = ArgLocs[++i]; // skip ahead to next loc
1278         if (VA.isRegLoc()) {
1279           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1280                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1281         } else {
1282           assert(VA.isMemLoc());
1283 
1284           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1285                                                  dl, DAG, VA, Flags));
1286         }
1287       } else {
1288         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1289                          StackPtr, MemOpChains, Flags);
1290       }
1291     } else if (VA.isRegLoc()) {
1292       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1293     } else if (!IsSibCall || isByVal) {
1294       assert(VA.isMemLoc());
1295 
1296       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1297                                              dl, DAG, VA, Flags));
1298     }
1299   }
1300 
1301   if (!MemOpChains.empty())
1302     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1303                         &MemOpChains[0], MemOpChains.size());
1304 
1305   // Build a sequence of copy-to-reg nodes chained together with token chain
1306   // and flag operands which copy the outgoing args into the appropriate regs.
1307   SDValue InFlag;
1308   // Tail call byval lowering might overwrite argument registers so in case of
1309   // tail call optimization the copies to registers are lowered later.
1310   if (!isTailCall)
1311     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1312       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1313                                RegsToPass[i].second, InFlag);
1314       InFlag = Chain.getValue(1);
1315     }
1316 
1317   // For tail calls lower the arguments to the 'real' stack slot.
1318   if (isTailCall) {
1319     // Force all the incoming stack arguments to be loaded from the stack
1320     // before any new outgoing arguments are stored to the stack, because the
1321     // outgoing stack slots may alias the incoming argument stack slots, and
1322     // the alias isn't otherwise explicit. This is slightly more conservative
1323     // than necessary, because it means that each store effectively depends
1324     // on every argument instead of just those arguments it would clobber.
1325 
1326     // Do not flag preceding copytoreg stuff together with the following stuff.
1327     InFlag = SDValue();
1328     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1329       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1330                                RegsToPass[i].second, InFlag);
1331       InFlag = Chain.getValue(1);
1332     }
1333     InFlag =SDValue();
1334   }
1335 
1336   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1337   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1338   // node so that legalize doesn't hack it.
1339   bool isDirect = false;
1340   bool isARMFunc = false;
1341   bool isLocalARMFunc = false;
1342   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1343 
1344   if (EnableARMLongCalls) {
1345     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1346             && "long-calls with non-static relocation model!");
1347     // Handle a global address or an external symbol. If it's not one of
1348     // those, the target's already in a register, so we don't need to do
1349     // anything extra.
1350     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1351       const GlobalValue *GV = G->getGlobal();
1352       // Create a constant pool entry for the callee address
1353       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1354       ARMConstantPoolValue *CPV = new ARMConstantPoolValue(GV,
1355                                                            ARMPCLabelIndex,
1356                                                            ARMCP::CPValue, 0);
1357       // Get the address of the callee into a register
1358       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1359       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1360       Callee = DAG.getLoad(getPointerTy(), dl,
1361                            DAG.getEntryNode(), CPAddr,
1362                            MachinePointerInfo::getConstantPool(),
1363                            false, false, 0);
1364     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1365       const char *Sym = S->getSymbol();
1366 
1367       // Create a constant pool entry for the callee address
1368       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1369       ARMConstantPoolValue *CPV = new ARMConstantPoolValue(*DAG.getContext(),
1370                                                        Sym, ARMPCLabelIndex, 0);
1371       // Get the address of the callee into a register
1372       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1373       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1374       Callee = DAG.getLoad(getPointerTy(), dl,
1375                            DAG.getEntryNode(), CPAddr,
1376                            MachinePointerInfo::getConstantPool(),
1377                            false, false, 0);
1378     }
1379   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1380     const GlobalValue *GV = G->getGlobal();
1381     isDirect = true;
1382     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1383     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1384                    getTargetMachine().getRelocationModel() != Reloc::Static;
1385     isARMFunc = !Subtarget->isThumb() || isStub;
1386     // ARM call to a local ARM function is predicable.
1387     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1388     // tBX takes a register source operand.
1389     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1390       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1391       ARMConstantPoolValue *CPV = new ARMConstantPoolValue(GV,
1392                                                            ARMPCLabelIndex,
1393                                                            ARMCP::CPValue, 4);
1394       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1395       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1396       Callee = DAG.getLoad(getPointerTy(), dl,
1397                            DAG.getEntryNode(), CPAddr,
1398                            MachinePointerInfo::getConstantPool(),
1399                            false, false, 0);
1400       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1401       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1402                            getPointerTy(), Callee, PICLabel);
1403     } else {
1404       // On ELF targets for PIC code, direct calls should go through the PLT
1405       unsigned OpFlags = 0;
1406       if (Subtarget->isTargetELF() &&
1407                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1408         OpFlags = ARMII::MO_PLT;
1409       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1410     }
1411   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1412     isDirect = true;
1413     bool isStub = Subtarget->isTargetDarwin() &&
1414                   getTargetMachine().getRelocationModel() != Reloc::Static;
1415     isARMFunc = !Subtarget->isThumb() || isStub;
1416     // tBX takes a register source operand.
1417     const char *Sym = S->getSymbol();
1418     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1419       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1420       ARMConstantPoolValue *CPV = new ARMConstantPoolValue(*DAG.getContext(),
1421                                                        Sym, ARMPCLabelIndex, 4);
1422       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1423       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1424       Callee = DAG.getLoad(getPointerTy(), dl,
1425                            DAG.getEntryNode(), CPAddr,
1426                            MachinePointerInfo::getConstantPool(),
1427                            false, false, 0);
1428       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1429       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1430                            getPointerTy(), Callee, PICLabel);
1431     } else {
1432       unsigned OpFlags = 0;
1433       // On ELF targets for PIC code, direct calls should go through the PLT
1434       if (Subtarget->isTargetELF() &&
1435                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1436         OpFlags = ARMII::MO_PLT;
1437       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1438     }
1439   }
1440 
1441   // FIXME: handle tail calls differently.
1442   unsigned CallOpc;
1443   if (Subtarget->isThumb()) {
1444     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1445       CallOpc = ARMISD::CALL_NOLINK;
1446     else
1447       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1448   } else {
1449     CallOpc = (isDirect || Subtarget->hasV5TOps())
1450       ? (isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL)
1451       : ARMISD::CALL_NOLINK;
1452   }
1453 
1454   std::vector<SDValue> Ops;
1455   Ops.push_back(Chain);
1456   Ops.push_back(Callee);
1457 
1458   // Add argument registers to the end of the list so that they are known live
1459   // into the call.
1460   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1461     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1462                                   RegsToPass[i].second.getValueType()));
1463 
1464   if (InFlag.getNode())
1465     Ops.push_back(InFlag);
1466 
1467   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1468   if (isTailCall)
1469     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1470 
1471   // Returns a chain and a flag for retval copy to use.
1472   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1473   InFlag = Chain.getValue(1);
1474 
1475   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1476                              DAG.getIntPtrConstant(0, true), InFlag);
1477   if (!Ins.empty())
1478     InFlag = Chain.getValue(1);
1479 
1480   // Handle result values, copying them out of physregs into vregs that we
1481   // return.
1482   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1483                          dl, DAG, InVals);
1484 }
1485 
1486 /// HandleByVal - Every parameter *after* a byval parameter is passed
1487 /// on the stack.  Confiscate all the parameter registers to insure
1488 /// this.
1489 void
1490 llvm::ARMTargetLowering::HandleByVal(CCState *State) const {
1491   static const unsigned RegList1[] = {
1492     ARM::R0, ARM::R1, ARM::R2, ARM::R3
1493   };
1494   do {} while (State->AllocateReg(RegList1, 4));
1495 }
1496 
1497 /// MatchingStackOffset - Return true if the given stack call argument is
1498 /// already available in the same position (relatively) of the caller's
1499 /// incoming argument stack.
1500 static
1501 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1502                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1503                          const ARMInstrInfo *TII) {
1504   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1505   int FI = INT_MAX;
1506   if (Arg.getOpcode() == ISD::CopyFromReg) {
1507     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1508     if (!TargetRegisterInfo::isVirtualRegister(VR))
1509       return false;
1510     MachineInstr *Def = MRI->getVRegDef(VR);
1511     if (!Def)
1512       return false;
1513     if (!Flags.isByVal()) {
1514       if (!TII->isLoadFromStackSlot(Def, FI))
1515         return false;
1516     } else {
1517       return false;
1518     }
1519   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1520     if (Flags.isByVal())
1521       // ByVal argument is passed in as a pointer but it's now being
1522       // dereferenced. e.g.
1523       // define @foo(%struct.X* %A) {
1524       //   tail call @bar(%struct.X* byval %A)
1525       // }
1526       return false;
1527     SDValue Ptr = Ld->getBasePtr();
1528     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1529     if (!FINode)
1530       return false;
1531     FI = FINode->getIndex();
1532   } else
1533     return false;
1534 
1535   assert(FI != INT_MAX);
1536   if (!MFI->isFixedObjectIndex(FI))
1537     return false;
1538   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1539 }
1540 
1541 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1542 /// for tail call optimization. Targets which want to do tail call
1543 /// optimization should implement this function.
1544 bool
1545 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1546                                                      CallingConv::ID CalleeCC,
1547                                                      bool isVarArg,
1548                                                      bool isCalleeStructRet,
1549                                                      bool isCallerStructRet,
1550                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1551                                     const SmallVectorImpl<SDValue> &OutVals,
1552                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1553                                                      SelectionDAG& DAG) const {
1554   const Function *CallerF = DAG.getMachineFunction().getFunction();
1555   CallingConv::ID CallerCC = CallerF->getCallingConv();
1556   bool CCMatch = CallerCC == CalleeCC;
1557 
1558   // Look for obvious safe cases to perform tail call optimization that do not
1559   // require ABI changes. This is what gcc calls sibcall.
1560 
1561   // Do not sibcall optimize vararg calls unless the call site is not passing
1562   // any arguments.
1563   if (isVarArg && !Outs.empty())
1564     return false;
1565 
1566   // Also avoid sibcall optimization if either caller or callee uses struct
1567   // return semantics.
1568   if (isCalleeStructRet || isCallerStructRet)
1569     return false;
1570 
1571   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1572   // emitEpilogue is not ready for them.
1573   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1574   // LR.  This means if we need to reload LR, it takes an extra instructions,
1575   // which outweighs the value of the tail call; but here we don't know yet
1576   // whether LR is going to be used.  Probably the right approach is to
1577   // generate the tail call here and turn it back into CALL/RET in
1578   // emitEpilogue if LR is used.
1579 
1580   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1581   // but we need to make sure there are enough registers; the only valid
1582   // registers are the 4 used for parameters.  We don't currently do this
1583   // case.
1584   if (Subtarget->isThumb1Only())
1585     return false;
1586 
1587   // If the calling conventions do not match, then we'd better make sure the
1588   // results are returned in the same way as what the caller expects.
1589   if (!CCMatch) {
1590     SmallVector<CCValAssign, 16> RVLocs1;
1591     CCState CCInfo1(CalleeCC, false, getTargetMachine(),
1592                     RVLocs1, *DAG.getContext());
1593     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1594 
1595     SmallVector<CCValAssign, 16> RVLocs2;
1596     CCState CCInfo2(CallerCC, false, getTargetMachine(),
1597                     RVLocs2, *DAG.getContext());
1598     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1599 
1600     if (RVLocs1.size() != RVLocs2.size())
1601       return false;
1602     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1603       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1604         return false;
1605       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1606         return false;
1607       if (RVLocs1[i].isRegLoc()) {
1608         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1609           return false;
1610       } else {
1611         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1612           return false;
1613       }
1614     }
1615   }
1616 
1617   // If the callee takes no arguments then go on to check the results of the
1618   // call.
1619   if (!Outs.empty()) {
1620     // Check if stack adjustment is needed. For now, do not do this if any
1621     // argument is passed on the stack.
1622     SmallVector<CCValAssign, 16> ArgLocs;
1623     CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
1624                    ArgLocs, *DAG.getContext());
1625     CCInfo.AnalyzeCallOperands(Outs,
1626                                CCAssignFnForNode(CalleeCC, false, isVarArg));
1627     if (CCInfo.getNextStackOffset()) {
1628       MachineFunction &MF = DAG.getMachineFunction();
1629 
1630       // Check if the arguments are already laid out in the right way as
1631       // the caller's fixed stack objects.
1632       MachineFrameInfo *MFI = MF.getFrameInfo();
1633       const MachineRegisterInfo *MRI = &MF.getRegInfo();
1634       const ARMInstrInfo *TII =
1635         ((ARMTargetMachine&)getTargetMachine()).getInstrInfo();
1636       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1637            i != e;
1638            ++i, ++realArgIdx) {
1639         CCValAssign &VA = ArgLocs[i];
1640         EVT RegVT = VA.getLocVT();
1641         SDValue Arg = OutVals[realArgIdx];
1642         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1643         if (VA.getLocInfo() == CCValAssign::Indirect)
1644           return false;
1645         if (VA.needsCustom()) {
1646           // f64 and vector types are split into multiple registers or
1647           // register/stack-slot combinations.  The types will not match
1648           // the registers; give up on memory f64 refs until we figure
1649           // out what to do about this.
1650           if (!VA.isRegLoc())
1651             return false;
1652           if (!ArgLocs[++i].isRegLoc())
1653             return false;
1654           if (RegVT == MVT::v2f64) {
1655             if (!ArgLocs[++i].isRegLoc())
1656               return false;
1657             if (!ArgLocs[++i].isRegLoc())
1658               return false;
1659           }
1660         } else if (!VA.isRegLoc()) {
1661           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1662                                    MFI, MRI, TII))
1663             return false;
1664         }
1665       }
1666     }
1667   }
1668 
1669   return true;
1670 }
1671 
1672 SDValue
1673 ARMTargetLowering::LowerReturn(SDValue Chain,
1674                                CallingConv::ID CallConv, bool isVarArg,
1675                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1676                                const SmallVectorImpl<SDValue> &OutVals,
1677                                DebugLoc dl, SelectionDAG &DAG) const {
1678 
1679   // CCValAssign - represent the assignment of the return value to a location.
1680   SmallVector<CCValAssign, 16> RVLocs;
1681 
1682   // CCState - Info about the registers and stack slots.
1683   CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
1684                  *DAG.getContext());
1685 
1686   // Analyze outgoing return values.
1687   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1688                                                isVarArg));
1689 
1690   // If this is the first return lowered for this function, add
1691   // the regs to the liveout set for the function.
1692   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1693     for (unsigned i = 0; i != RVLocs.size(); ++i)
1694       if (RVLocs[i].isRegLoc())
1695         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1696   }
1697 
1698   SDValue Flag;
1699 
1700   // Copy the result values into the output registers.
1701   for (unsigned i = 0, realRVLocIdx = 0;
1702        i != RVLocs.size();
1703        ++i, ++realRVLocIdx) {
1704     CCValAssign &VA = RVLocs[i];
1705     assert(VA.isRegLoc() && "Can only return in registers!");
1706 
1707     SDValue Arg = OutVals[realRVLocIdx];
1708 
1709     switch (VA.getLocInfo()) {
1710     default: llvm_unreachable("Unknown loc info!");
1711     case CCValAssign::Full: break;
1712     case CCValAssign::BCvt:
1713       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1714       break;
1715     }
1716 
1717     if (VA.needsCustom()) {
1718       if (VA.getLocVT() == MVT::v2f64) {
1719         // Extract the first half and return it in two registers.
1720         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1721                                    DAG.getConstant(0, MVT::i32));
1722         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
1723                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
1724 
1725         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1726         Flag = Chain.getValue(1);
1727         VA = RVLocs[++i]; // skip ahead to next loc
1728         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1729                                  HalfGPRs.getValue(1), Flag);
1730         Flag = Chain.getValue(1);
1731         VA = RVLocs[++i]; // skip ahead to next loc
1732 
1733         // Extract the 2nd half and fall through to handle it as an f64 value.
1734         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1735                           DAG.getConstant(1, MVT::i32));
1736       }
1737       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
1738       // available.
1739       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1740                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1741       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1742       Flag = Chain.getValue(1);
1743       VA = RVLocs[++i]; // skip ahead to next loc
1744       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1745                                Flag);
1746     } else
1747       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1748 
1749     // Guarantee that all emitted copies are
1750     // stuck together, avoiding something bad.
1751     Flag = Chain.getValue(1);
1752   }
1753 
1754   SDValue result;
1755   if (Flag.getNode())
1756     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
1757   else // Return Void
1758     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain);
1759 
1760   return result;
1761 }
1762 
1763 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N) const {
1764   if (N->getNumValues() != 1)
1765     return false;
1766   if (!N->hasNUsesOfValue(1, 0))
1767     return false;
1768 
1769   unsigned NumCopies = 0;
1770   SDNode* Copies[2];
1771   SDNode *Use = *N->use_begin();
1772   if (Use->getOpcode() == ISD::CopyToReg) {
1773     Copies[NumCopies++] = Use;
1774   } else if (Use->getOpcode() == ARMISD::VMOVRRD) {
1775     // f64 returned in a pair of GPRs.
1776     for (SDNode::use_iterator UI = Use->use_begin(), UE = Use->use_end();
1777          UI != UE; ++UI) {
1778       if (UI->getOpcode() != ISD::CopyToReg)
1779         return false;
1780       Copies[UI.getUse().getResNo()] = *UI;
1781       ++NumCopies;
1782     }
1783   } else if (Use->getOpcode() == ISD::BITCAST) {
1784     // f32 returned in a single GPR.
1785     if (!Use->hasNUsesOfValue(1, 0))
1786       return false;
1787     Use = *Use->use_begin();
1788     if (Use->getOpcode() != ISD::CopyToReg || !Use->hasNUsesOfValue(1, 0))
1789       return false;
1790     Copies[NumCopies++] = Use;
1791   } else {
1792     return false;
1793   }
1794 
1795   if (NumCopies != 1 && NumCopies != 2)
1796     return false;
1797 
1798   bool HasRet = false;
1799   for (unsigned i = 0; i < NumCopies; ++i) {
1800     SDNode *Copy = Copies[i];
1801     for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1802          UI != UE; ++UI) {
1803       if (UI->getOpcode() == ISD::CopyToReg) {
1804         SDNode *Use = *UI;
1805         if (Use == Copies[0] || Use == Copies[1])
1806           continue;
1807         return false;
1808       }
1809       if (UI->getOpcode() != ARMISD::RET_FLAG)
1810         return false;
1811       HasRet = true;
1812     }
1813   }
1814 
1815   return HasRet;
1816 }
1817 
1818 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1819   if (!EnableARMTailCalls)
1820     return false;
1821 
1822   if (!CI->isTailCall())
1823     return false;
1824 
1825   return !Subtarget->isThumb1Only();
1826 }
1827 
1828 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
1829 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
1830 // one of the above mentioned nodes. It has to be wrapped because otherwise
1831 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
1832 // be used to form addressing mode. These wrapped nodes will be selected
1833 // into MOVi.
1834 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
1835   EVT PtrVT = Op.getValueType();
1836   // FIXME there is no actual debug info here
1837   DebugLoc dl = Op.getDebugLoc();
1838   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1839   SDValue Res;
1840   if (CP->isMachineConstantPoolEntry())
1841     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
1842                                     CP->getAlignment());
1843   else
1844     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
1845                                     CP->getAlignment());
1846   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
1847 }
1848 
1849 unsigned ARMTargetLowering::getJumpTableEncoding() const {
1850   return MachineJumpTableInfo::EK_Inline;
1851 }
1852 
1853 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
1854                                              SelectionDAG &DAG) const {
1855   MachineFunction &MF = DAG.getMachineFunction();
1856   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1857   unsigned ARMPCLabelIndex = 0;
1858   DebugLoc DL = Op.getDebugLoc();
1859   EVT PtrVT = getPointerTy();
1860   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1861   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
1862   SDValue CPAddr;
1863   if (RelocM == Reloc::Static) {
1864     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
1865   } else {
1866     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
1867     ARMPCLabelIndex = AFI->createPICLabelUId();
1868     ARMConstantPoolValue *CPV = new ARMConstantPoolValue(BA, ARMPCLabelIndex,
1869                                                          ARMCP::CPBlockAddress,
1870                                                          PCAdj);
1871     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1872   }
1873   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
1874   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
1875                                MachinePointerInfo::getConstantPool(),
1876                                false, false, 0);
1877   if (RelocM == Reloc::Static)
1878     return Result;
1879   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1880   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
1881 }
1882 
1883 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
1884 SDValue
1885 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
1886                                                  SelectionDAG &DAG) const {
1887   DebugLoc dl = GA->getDebugLoc();
1888   EVT PtrVT = getPointerTy();
1889   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
1890   MachineFunction &MF = DAG.getMachineFunction();
1891   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1892   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1893   ARMConstantPoolValue *CPV =
1894     new ARMConstantPoolValue(GA->getGlobal(), ARMPCLabelIndex,
1895                              ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
1896   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1897   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
1898   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
1899                          MachinePointerInfo::getConstantPool(),
1900                          false, false, 0);
1901   SDValue Chain = Argument.getValue(1);
1902 
1903   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1904   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
1905 
1906   // call __tls_get_addr.
1907   ArgListTy Args;
1908   ArgListEntry Entry;
1909   Entry.Node = Argument;
1910   Entry.Ty = (const Type *) Type::getInt32Ty(*DAG.getContext());
1911   Args.push_back(Entry);
1912   // FIXME: is there useful debug info available here?
1913   std::pair<SDValue, SDValue> CallResult =
1914     LowerCallTo(Chain, (const Type *) Type::getInt32Ty(*DAG.getContext()),
1915                 false, false, false, false,
1916                 0, CallingConv::C, false, /*isReturnValueUsed=*/true,
1917                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
1918   return CallResult.first;
1919 }
1920 
1921 // Lower ISD::GlobalTLSAddress using the "initial exec" or
1922 // "local exec" model.
1923 SDValue
1924 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
1925                                         SelectionDAG &DAG) const {
1926   const GlobalValue *GV = GA->getGlobal();
1927   DebugLoc dl = GA->getDebugLoc();
1928   SDValue Offset;
1929   SDValue Chain = DAG.getEntryNode();
1930   EVT PtrVT = getPointerTy();
1931   // Get the Thread Pointer
1932   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
1933 
1934   if (GV->isDeclaration()) {
1935     MachineFunction &MF = DAG.getMachineFunction();
1936     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1937     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1938     // Initial exec model.
1939     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
1940     ARMConstantPoolValue *CPV =
1941       new ARMConstantPoolValue(GA->getGlobal(), ARMPCLabelIndex,
1942                                ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, true);
1943     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1944     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
1945     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
1946                          MachinePointerInfo::getConstantPool(),
1947                          false, false, 0);
1948     Chain = Offset.getValue(1);
1949 
1950     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1951     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
1952 
1953     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
1954                          MachinePointerInfo::getConstantPool(),
1955                          false, false, 0);
1956   } else {
1957     // local exec model
1958     ARMConstantPoolValue *CPV = new ARMConstantPoolValue(GV, ARMCP::TPOFF);
1959     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1960     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
1961     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
1962                          MachinePointerInfo::getConstantPool(),
1963                          false, false, 0);
1964   }
1965 
1966   // The address of the thread local variable is the add of the thread
1967   // pointer with the offset of the variable.
1968   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
1969 }
1970 
1971 SDValue
1972 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
1973   // TODO: implement the "local dynamic" model
1974   assert(Subtarget->isTargetELF() &&
1975          "TLS not implemented for non-ELF targets");
1976   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1977   // If the relocation model is PIC, use the "General Dynamic" TLS Model,
1978   // otherwise use the "Local Exec" TLS Model
1979   if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
1980     return LowerToTLSGeneralDynamicModel(GA, DAG);
1981   else
1982     return LowerToTLSExecModels(GA, DAG);
1983 }
1984 
1985 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
1986                                                  SelectionDAG &DAG) const {
1987   EVT PtrVT = getPointerTy();
1988   DebugLoc dl = Op.getDebugLoc();
1989   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1990   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
1991   if (RelocM == Reloc::PIC_) {
1992     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
1993     ARMConstantPoolValue *CPV =
1994       new ARMConstantPoolValue(GV, UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
1995     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1996     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1997     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
1998                                  CPAddr,
1999                                  MachinePointerInfo::getConstantPool(),
2000                                  false, false, 0);
2001     SDValue Chain = Result.getValue(1);
2002     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2003     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2004     if (!UseGOTOFF)
2005       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2006                            MachinePointerInfo::getGOT(), false, false, 0);
2007     return Result;
2008   }
2009 
2010   // If we have T2 ops, we can materialize the address directly via movt/movw
2011   // pair. This is always cheaper.
2012   if (Subtarget->useMovt()) {
2013     ++NumMovwMovt;
2014     // FIXME: Once remat is capable of dealing with instructions with register
2015     // operands, expand this into two nodes.
2016     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2017                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2018   } else {
2019     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2020     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2021     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2022                        MachinePointerInfo::getConstantPool(),
2023                        false, false, 0);
2024   }
2025 }
2026 
2027 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2028                                                     SelectionDAG &DAG) const {
2029   EVT PtrVT = getPointerTy();
2030   DebugLoc dl = Op.getDebugLoc();
2031   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2032   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2033   MachineFunction &MF = DAG.getMachineFunction();
2034   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2035 
2036   if (Subtarget->useMovt()) {
2037     ++NumMovwMovt;
2038     // FIXME: Once remat is capable of dealing with instructions with register
2039     // operands, expand this into two nodes.
2040     if (RelocM == Reloc::Static)
2041       return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2042                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2043 
2044     unsigned Wrapper = (RelocM == Reloc::PIC_)
2045       ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2046     SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2047                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2048     if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2049       Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2050                            MachinePointerInfo::getGOT(), false, false, 0);
2051     return Result;
2052   }
2053 
2054   unsigned ARMPCLabelIndex = 0;
2055   SDValue CPAddr;
2056   if (RelocM == Reloc::Static) {
2057     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2058   } else {
2059     ARMPCLabelIndex = AFI->createPICLabelUId();
2060     unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2061     ARMConstantPoolValue *CPV =
2062       new ARMConstantPoolValue(GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj);
2063     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2064   }
2065   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2066 
2067   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2068                                MachinePointerInfo::getConstantPool(),
2069                                false, false, 0);
2070   SDValue Chain = Result.getValue(1);
2071 
2072   if (RelocM == Reloc::PIC_) {
2073     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2074     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2075   }
2076 
2077   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2078     Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2079                          false, false, 0);
2080 
2081   return Result;
2082 }
2083 
2084 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2085                                                     SelectionDAG &DAG) const {
2086   assert(Subtarget->isTargetELF() &&
2087          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2088   MachineFunction &MF = DAG.getMachineFunction();
2089   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2090   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2091   EVT PtrVT = getPointerTy();
2092   DebugLoc dl = Op.getDebugLoc();
2093   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2094   ARMConstantPoolValue *CPV = new ARMConstantPoolValue(*DAG.getContext(),
2095                                                        "_GLOBAL_OFFSET_TABLE_",
2096                                                        ARMPCLabelIndex, PCAdj);
2097   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2098   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2099   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2100                                MachinePointerInfo::getConstantPool(),
2101                                false, false, 0);
2102   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2103   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2104 }
2105 
2106 SDValue
2107 ARMTargetLowering::LowerEH_SJLJ_DISPATCHSETUP(SDValue Op, SelectionDAG &DAG)
2108   const {
2109   DebugLoc dl = Op.getDebugLoc();
2110   return DAG.getNode(ARMISD::EH_SJLJ_DISPATCHSETUP, dl, MVT::Other,
2111                      Op.getOperand(0));
2112 }
2113 
2114 SDValue
2115 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2116   DebugLoc dl = Op.getDebugLoc();
2117   SDValue Val = DAG.getConstant(0, MVT::i32);
2118   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, MVT::i32, Op.getOperand(0),
2119                      Op.getOperand(1), Val);
2120 }
2121 
2122 SDValue
2123 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2124   DebugLoc dl = Op.getDebugLoc();
2125   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2126                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2127 }
2128 
2129 SDValue
2130 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2131                                           const ARMSubtarget *Subtarget) const {
2132   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2133   DebugLoc dl = Op.getDebugLoc();
2134   switch (IntNo) {
2135   default: return SDValue();    // Don't custom lower most intrinsics.
2136   case Intrinsic::arm_thread_pointer: {
2137     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2138     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2139   }
2140   case Intrinsic::eh_sjlj_lsda: {
2141     MachineFunction &MF = DAG.getMachineFunction();
2142     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2143     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2144     EVT PtrVT = getPointerTy();
2145     DebugLoc dl = Op.getDebugLoc();
2146     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2147     SDValue CPAddr;
2148     unsigned PCAdj = (RelocM != Reloc::PIC_)
2149       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2150     ARMConstantPoolValue *CPV =
2151       new ARMConstantPoolValue(MF.getFunction(), ARMPCLabelIndex,
2152                                ARMCP::CPLSDA, PCAdj);
2153     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2154     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2155     SDValue Result =
2156       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2157                   MachinePointerInfo::getConstantPool(),
2158                   false, false, 0);
2159 
2160     if (RelocM == Reloc::PIC_) {
2161       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2162       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2163     }
2164     return Result;
2165   }
2166   case Intrinsic::arm_neon_vmulls:
2167   case Intrinsic::arm_neon_vmullu: {
2168     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2169       ? ARMISD::VMULLs : ARMISD::VMULLu;
2170     return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2171                        Op.getOperand(1), Op.getOperand(2));
2172   }
2173   }
2174 }
2175 
2176 static SDValue LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG,
2177                                const ARMSubtarget *Subtarget) {
2178   DebugLoc dl = Op.getDebugLoc();
2179   if (!Subtarget->hasDataBarrier()) {
2180     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2181     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2182     // here.
2183     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2184            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2185     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2186                        DAG.getConstant(0, MVT::i32));
2187   }
2188 
2189   SDValue Op5 = Op.getOperand(5);
2190   bool isDeviceBarrier = cast<ConstantSDNode>(Op5)->getZExtValue() != 0;
2191   unsigned isLL = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2192   unsigned isLS = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2193   bool isOnlyStoreBarrier = (isLL == 0 && isLS == 0);
2194 
2195   ARM_MB::MemBOpt DMBOpt;
2196   if (isDeviceBarrier)
2197     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ST : ARM_MB::SY;
2198   else
2199     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ISHST : ARM_MB::ISH;
2200   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2201                      DAG.getConstant(DMBOpt, MVT::i32));
2202 }
2203 
2204 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2205                              const ARMSubtarget *Subtarget) {
2206   // ARM pre v5TE and Thumb1 does not have preload instructions.
2207   if (!(Subtarget->isThumb2() ||
2208         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2209     // Just preserve the chain.
2210     return Op.getOperand(0);
2211 
2212   DebugLoc dl = Op.getDebugLoc();
2213   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2214   if (!isRead &&
2215       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2216     // ARMv7 with MP extension has PLDW.
2217     return Op.getOperand(0);
2218 
2219   if (Subtarget->isThumb())
2220     // Invert the bits.
2221     isRead = ~isRead & 1;
2222   unsigned isData = Subtarget->isThumb() ? 0 : 1;
2223 
2224   // Currently there is no intrinsic that matches pli.
2225   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2226                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2227                      DAG.getConstant(isData, MVT::i32));
2228 }
2229 
2230 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2231   MachineFunction &MF = DAG.getMachineFunction();
2232   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2233 
2234   // vastart just stores the address of the VarArgsFrameIndex slot into the
2235   // memory location argument.
2236   DebugLoc dl = Op.getDebugLoc();
2237   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2238   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2239   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2240   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2241                       MachinePointerInfo(SV), false, false, 0);
2242 }
2243 
2244 SDValue
2245 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2246                                         SDValue &Root, SelectionDAG &DAG,
2247                                         DebugLoc dl) const {
2248   MachineFunction &MF = DAG.getMachineFunction();
2249   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2250 
2251   TargetRegisterClass *RC;
2252   if (AFI->isThumb1OnlyFunction())
2253     RC = ARM::tGPRRegisterClass;
2254   else
2255     RC = ARM::GPRRegisterClass;
2256 
2257   // Transform the arguments stored in physical registers into virtual ones.
2258   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2259   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2260 
2261   SDValue ArgValue2;
2262   if (NextVA.isMemLoc()) {
2263     MachineFrameInfo *MFI = MF.getFrameInfo();
2264     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2265 
2266     // Create load node to retrieve arguments from the stack.
2267     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2268     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2269                             MachinePointerInfo::getFixedStack(FI),
2270                             false, false, 0);
2271   } else {
2272     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2273     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2274   }
2275 
2276   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2277 }
2278 
2279 SDValue
2280 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2281                                         CallingConv::ID CallConv, bool isVarArg,
2282                                         const SmallVectorImpl<ISD::InputArg>
2283                                           &Ins,
2284                                         DebugLoc dl, SelectionDAG &DAG,
2285                                         SmallVectorImpl<SDValue> &InVals)
2286                                           const {
2287 
2288   MachineFunction &MF = DAG.getMachineFunction();
2289   MachineFrameInfo *MFI = MF.getFrameInfo();
2290 
2291   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2292 
2293   // Assign locations to all of the incoming arguments.
2294   SmallVector<CCValAssign, 16> ArgLocs;
2295   CCState CCInfo(CallConv, isVarArg, getTargetMachine(), ArgLocs,
2296                  *DAG.getContext());
2297   CCInfo.AnalyzeFormalArguments(Ins,
2298                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2299                                                   isVarArg));
2300 
2301   SmallVector<SDValue, 16> ArgValues;
2302   int lastInsIndex = -1;
2303 
2304   SDValue ArgValue;
2305   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2306     CCValAssign &VA = ArgLocs[i];
2307 
2308     // Arguments stored in registers.
2309     if (VA.isRegLoc()) {
2310       EVT RegVT = VA.getLocVT();
2311 
2312       if (VA.needsCustom()) {
2313         // f64 and vector types are split up into multiple registers or
2314         // combinations of registers and stack slots.
2315         if (VA.getLocVT() == MVT::v2f64) {
2316           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2317                                                    Chain, DAG, dl);
2318           VA = ArgLocs[++i]; // skip ahead to next loc
2319           SDValue ArgValue2;
2320           if (VA.isMemLoc()) {
2321             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2322             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2323             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2324                                     MachinePointerInfo::getFixedStack(FI),
2325                                     false, false, 0);
2326           } else {
2327             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2328                                              Chain, DAG, dl);
2329           }
2330           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2331           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2332                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2333           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2334                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2335         } else
2336           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2337 
2338       } else {
2339         TargetRegisterClass *RC;
2340 
2341         if (RegVT == MVT::f32)
2342           RC = ARM::SPRRegisterClass;
2343         else if (RegVT == MVT::f64)
2344           RC = ARM::DPRRegisterClass;
2345         else if (RegVT == MVT::v2f64)
2346           RC = ARM::QPRRegisterClass;
2347         else if (RegVT == MVT::i32)
2348           RC = (AFI->isThumb1OnlyFunction() ?
2349                 ARM::tGPRRegisterClass : ARM::GPRRegisterClass);
2350         else
2351           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2352 
2353         // Transform the arguments in physical registers into virtual ones.
2354         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2355         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2356       }
2357 
2358       // If this is an 8 or 16-bit value, it is really passed promoted
2359       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2360       // truncate to the right size.
2361       switch (VA.getLocInfo()) {
2362       default: llvm_unreachable("Unknown loc info!");
2363       case CCValAssign::Full: break;
2364       case CCValAssign::BCvt:
2365         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2366         break;
2367       case CCValAssign::SExt:
2368         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2369                                DAG.getValueType(VA.getValVT()));
2370         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2371         break;
2372       case CCValAssign::ZExt:
2373         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2374                                DAG.getValueType(VA.getValVT()));
2375         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2376         break;
2377       }
2378 
2379       InVals.push_back(ArgValue);
2380 
2381     } else { // VA.isRegLoc()
2382 
2383       // sanity check
2384       assert(VA.isMemLoc());
2385       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2386 
2387       int index = ArgLocs[i].getValNo();
2388 
2389       // Some Ins[] entries become multiple ArgLoc[] entries.
2390       // Process them only once.
2391       if (index != lastInsIndex)
2392         {
2393           ISD::ArgFlagsTy Flags = Ins[index].Flags;
2394           // FIXME: For now, all byval parameter objects are marked mutable. This can be
2395           // changed with more analysis.
2396           // In case of tail call optimization mark all arguments mutable. Since they
2397           // could be overwritten by lowering of arguments in case of a tail call.
2398           if (Flags.isByVal()) {
2399             unsigned Bytes = Flags.getByValSize();
2400             if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2401             int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), false);
2402             InVals.push_back(DAG.getFrameIndex(FI, getPointerTy()));
2403           } else {
2404             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2405                                             VA.getLocMemOffset(), true);
2406 
2407             // Create load nodes to retrieve arguments from the stack.
2408             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2409             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2410                                          MachinePointerInfo::getFixedStack(FI),
2411                                          false, false, 0));
2412           }
2413           lastInsIndex = index;
2414         }
2415     }
2416   }
2417 
2418   // varargs
2419   if (isVarArg) {
2420     static const unsigned GPRArgRegs[] = {
2421       ARM::R0, ARM::R1, ARM::R2, ARM::R3
2422     };
2423 
2424     unsigned NumGPRs = CCInfo.getFirstUnallocated
2425       (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2426 
2427     unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2428     unsigned VARegSize = (4 - NumGPRs) * 4;
2429     unsigned VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
2430     unsigned ArgOffset = CCInfo.getNextStackOffset();
2431     if (VARegSaveSize) {
2432       // If this function is vararg, store any remaining integer argument regs
2433       // to their spots on the stack so that they may be loaded by deferencing
2434       // the result of va_next.
2435       AFI->setVarArgsRegSaveSize(VARegSaveSize);
2436       AFI->setVarArgsFrameIndex(
2437         MFI->CreateFixedObject(VARegSaveSize,
2438                                ArgOffset + VARegSaveSize - VARegSize,
2439                                false));
2440       SDValue FIN = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(),
2441                                       getPointerTy());
2442 
2443       SmallVector<SDValue, 4> MemOps;
2444       for (; NumGPRs < 4; ++NumGPRs) {
2445         TargetRegisterClass *RC;
2446         if (AFI->isThumb1OnlyFunction())
2447           RC = ARM::tGPRRegisterClass;
2448         else
2449           RC = ARM::GPRRegisterClass;
2450 
2451         unsigned VReg = MF.addLiveIn(GPRArgRegs[NumGPRs], RC);
2452         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2453         SDValue Store =
2454           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2455                MachinePointerInfo::getFixedStack(AFI->getVarArgsFrameIndex()),
2456                        false, false, 0);
2457         MemOps.push_back(Store);
2458         FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2459                           DAG.getConstant(4, getPointerTy()));
2460       }
2461       if (!MemOps.empty())
2462         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2463                             &MemOps[0], MemOps.size());
2464     } else
2465       // This will point to the next argument passed via stack.
2466       AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(4, ArgOffset, true));
2467   }
2468 
2469   return Chain;
2470 }
2471 
2472 /// isFloatingPointZero - Return true if this is +0.0.
2473 static bool isFloatingPointZero(SDValue Op) {
2474   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2475     return CFP->getValueAPF().isPosZero();
2476   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2477     // Maybe this has already been legalized into the constant pool?
2478     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2479       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2480       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2481         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2482           return CFP->getValueAPF().isPosZero();
2483     }
2484   }
2485   return false;
2486 }
2487 
2488 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2489 /// the given operands.
2490 SDValue
2491 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2492                              SDValue &ARMcc, SelectionDAG &DAG,
2493                              DebugLoc dl) const {
2494   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2495     unsigned C = RHSC->getZExtValue();
2496     if (!isLegalICmpImmediate(C)) {
2497       // Constant does not fit, try adjusting it by one?
2498       switch (CC) {
2499       default: break;
2500       case ISD::SETLT:
2501       case ISD::SETGE:
2502         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2503           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2504           RHS = DAG.getConstant(C-1, MVT::i32);
2505         }
2506         break;
2507       case ISD::SETULT:
2508       case ISD::SETUGE:
2509         if (C != 0 && isLegalICmpImmediate(C-1)) {
2510           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2511           RHS = DAG.getConstant(C-1, MVT::i32);
2512         }
2513         break;
2514       case ISD::SETLE:
2515       case ISD::SETGT:
2516         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
2517           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2518           RHS = DAG.getConstant(C+1, MVT::i32);
2519         }
2520         break;
2521       case ISD::SETULE:
2522       case ISD::SETUGT:
2523         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
2524           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2525           RHS = DAG.getConstant(C+1, MVT::i32);
2526         }
2527         break;
2528       }
2529     }
2530   }
2531 
2532   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2533   ARMISD::NodeType CompareType;
2534   switch (CondCode) {
2535   default:
2536     CompareType = ARMISD::CMP;
2537     break;
2538   case ARMCC::EQ:
2539   case ARMCC::NE:
2540     // Uses only Z Flag
2541     CompareType = ARMISD::CMPZ;
2542     break;
2543   }
2544   ARMcc = DAG.getConstant(CondCode, MVT::i32);
2545   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
2546 }
2547 
2548 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
2549 SDValue
2550 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
2551                              DebugLoc dl) const {
2552   SDValue Cmp;
2553   if (!isFloatingPointZero(RHS))
2554     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
2555   else
2556     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
2557   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
2558 }
2559 
2560 /// duplicateCmp - Glue values can have only one use, so this function
2561 /// duplicates a comparison node.
2562 SDValue
2563 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
2564   unsigned Opc = Cmp.getOpcode();
2565   DebugLoc DL = Cmp.getDebugLoc();
2566   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
2567     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2568 
2569   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
2570   Cmp = Cmp.getOperand(0);
2571   Opc = Cmp.getOpcode();
2572   if (Opc == ARMISD::CMPFP)
2573     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2574   else {
2575     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
2576     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
2577   }
2578   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
2579 }
2580 
2581 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2582   SDValue Cond = Op.getOperand(0);
2583   SDValue SelectTrue = Op.getOperand(1);
2584   SDValue SelectFalse = Op.getOperand(2);
2585   DebugLoc dl = Op.getDebugLoc();
2586 
2587   // Convert:
2588   //
2589   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
2590   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
2591   //
2592   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
2593     const ConstantSDNode *CMOVTrue =
2594       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
2595     const ConstantSDNode *CMOVFalse =
2596       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2597 
2598     if (CMOVTrue && CMOVFalse) {
2599       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
2600       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
2601 
2602       SDValue True;
2603       SDValue False;
2604       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
2605         True = SelectTrue;
2606         False = SelectFalse;
2607       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
2608         True = SelectFalse;
2609         False = SelectTrue;
2610       }
2611 
2612       if (True.getNode() && False.getNode()) {
2613         EVT VT = Cond.getValueType();
2614         SDValue ARMcc = Cond.getOperand(2);
2615         SDValue CCR = Cond.getOperand(3);
2616         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
2617         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
2618       }
2619     }
2620   }
2621 
2622   return DAG.getSelectCC(dl, Cond,
2623                          DAG.getConstant(0, Cond.getValueType()),
2624                          SelectTrue, SelectFalse, ISD::SETNE);
2625 }
2626 
2627 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2628   EVT VT = Op.getValueType();
2629   SDValue LHS = Op.getOperand(0);
2630   SDValue RHS = Op.getOperand(1);
2631   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2632   SDValue TrueVal = Op.getOperand(2);
2633   SDValue FalseVal = Op.getOperand(3);
2634   DebugLoc dl = Op.getDebugLoc();
2635 
2636   if (LHS.getValueType() == MVT::i32) {
2637     SDValue ARMcc;
2638     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2639     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2640     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
2641   }
2642 
2643   ARMCC::CondCodes CondCode, CondCode2;
2644   FPCCToARMCC(CC, CondCode, CondCode2);
2645 
2646   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
2647   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
2648   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2649   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
2650                                ARMcc, CCR, Cmp);
2651   if (CondCode2 != ARMCC::AL) {
2652     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
2653     // FIXME: Needs another CMP because flag can have but one use.
2654     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
2655     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
2656                          Result, TrueVal, ARMcc2, CCR, Cmp2);
2657   }
2658   return Result;
2659 }
2660 
2661 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
2662 /// to morph to an integer compare sequence.
2663 static bool canChangeToInt(SDValue Op, bool &SeenZero,
2664                            const ARMSubtarget *Subtarget) {
2665   SDNode *N = Op.getNode();
2666   if (!N->hasOneUse())
2667     // Otherwise it requires moving the value from fp to integer registers.
2668     return false;
2669   if (!N->getNumValues())
2670     return false;
2671   EVT VT = Op.getValueType();
2672   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
2673     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
2674     // vmrs are very slow, e.g. cortex-a8.
2675     return false;
2676 
2677   if (isFloatingPointZero(Op)) {
2678     SeenZero = true;
2679     return true;
2680   }
2681   return ISD::isNormalLoad(N);
2682 }
2683 
2684 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
2685   if (isFloatingPointZero(Op))
2686     return DAG.getConstant(0, MVT::i32);
2687 
2688   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
2689     return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2690                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
2691                        Ld->isVolatile(), Ld->isNonTemporal(),
2692                        Ld->getAlignment());
2693 
2694   llvm_unreachable("Unknown VFP cmp argument!");
2695 }
2696 
2697 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
2698                            SDValue &RetVal1, SDValue &RetVal2) {
2699   if (isFloatingPointZero(Op)) {
2700     RetVal1 = DAG.getConstant(0, MVT::i32);
2701     RetVal2 = DAG.getConstant(0, MVT::i32);
2702     return;
2703   }
2704 
2705   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
2706     SDValue Ptr = Ld->getBasePtr();
2707     RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2708                           Ld->getChain(), Ptr,
2709                           Ld->getPointerInfo(),
2710                           Ld->isVolatile(), Ld->isNonTemporal(),
2711                           Ld->getAlignment());
2712 
2713     EVT PtrType = Ptr.getValueType();
2714     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
2715     SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
2716                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
2717     RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2718                           Ld->getChain(), NewPtr,
2719                           Ld->getPointerInfo().getWithOffset(4),
2720                           Ld->isVolatile(), Ld->isNonTemporal(),
2721                           NewAlign);
2722     return;
2723   }
2724 
2725   llvm_unreachable("Unknown VFP cmp argument!");
2726 }
2727 
2728 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
2729 /// f32 and even f64 comparisons to integer ones.
2730 SDValue
2731 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
2732   SDValue Chain = Op.getOperand(0);
2733   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2734   SDValue LHS = Op.getOperand(2);
2735   SDValue RHS = Op.getOperand(3);
2736   SDValue Dest = Op.getOperand(4);
2737   DebugLoc dl = Op.getDebugLoc();
2738 
2739   bool SeenZero = false;
2740   if (canChangeToInt(LHS, SeenZero, Subtarget) &&
2741       canChangeToInt(RHS, SeenZero, Subtarget) &&
2742       // If one of the operand is zero, it's safe to ignore the NaN case since
2743       // we only care about equality comparisons.
2744       (SeenZero || (DAG.isKnownNeverNaN(LHS) && DAG.isKnownNeverNaN(RHS)))) {
2745     // If unsafe fp math optimization is enabled and there are no other uses of
2746     // the CMP operands, and the condition code is EQ or NE, we can optimize it
2747     // to an integer comparison.
2748     if (CC == ISD::SETOEQ)
2749       CC = ISD::SETEQ;
2750     else if (CC == ISD::SETUNE)
2751       CC = ISD::SETNE;
2752 
2753     SDValue ARMcc;
2754     if (LHS.getValueType() == MVT::f32) {
2755       LHS = bitcastf32Toi32(LHS, DAG);
2756       RHS = bitcastf32Toi32(RHS, DAG);
2757       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2758       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2759       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
2760                          Chain, Dest, ARMcc, CCR, Cmp);
2761     }
2762 
2763     SDValue LHS1, LHS2;
2764     SDValue RHS1, RHS2;
2765     expandf64Toi32(LHS, DAG, LHS1, LHS2);
2766     expandf64Toi32(RHS, DAG, RHS1, RHS2);
2767     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2768     ARMcc = DAG.getConstant(CondCode, MVT::i32);
2769     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
2770     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
2771     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
2772   }
2773 
2774   return SDValue();
2775 }
2776 
2777 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
2778   SDValue Chain = Op.getOperand(0);
2779   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2780   SDValue LHS = Op.getOperand(2);
2781   SDValue RHS = Op.getOperand(3);
2782   SDValue Dest = Op.getOperand(4);
2783   DebugLoc dl = Op.getDebugLoc();
2784 
2785   if (LHS.getValueType() == MVT::i32) {
2786     SDValue ARMcc;
2787     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2788     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2789     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
2790                        Chain, Dest, ARMcc, CCR, Cmp);
2791   }
2792 
2793   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
2794 
2795   if (UnsafeFPMath &&
2796       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
2797        CC == ISD::SETNE || CC == ISD::SETUNE)) {
2798     SDValue Result = OptimizeVFPBrcond(Op, DAG);
2799     if (Result.getNode())
2800       return Result;
2801   }
2802 
2803   ARMCC::CondCodes CondCode, CondCode2;
2804   FPCCToARMCC(CC, CondCode, CondCode2);
2805 
2806   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
2807   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
2808   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2809   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
2810   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
2811   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
2812   if (CondCode2 != ARMCC::AL) {
2813     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
2814     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
2815     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
2816   }
2817   return Res;
2818 }
2819 
2820 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
2821   SDValue Chain = Op.getOperand(0);
2822   SDValue Table = Op.getOperand(1);
2823   SDValue Index = Op.getOperand(2);
2824   DebugLoc dl = Op.getDebugLoc();
2825 
2826   EVT PTy = getPointerTy();
2827   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
2828   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2829   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
2830   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
2831   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
2832   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
2833   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
2834   if (Subtarget->isThumb2()) {
2835     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
2836     // which does another jump to the destination. This also makes it easier
2837     // to translate it to TBB / TBH later.
2838     // FIXME: This might not work if the function is extremely large.
2839     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
2840                        Addr, Op.getOperand(2), JTI, UId);
2841   }
2842   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2843     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
2844                        MachinePointerInfo::getJumpTable(),
2845                        false, false, 0);
2846     Chain = Addr.getValue(1);
2847     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
2848     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
2849   } else {
2850     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
2851                        MachinePointerInfo::getJumpTable(), false, false, 0);
2852     Chain = Addr.getValue(1);
2853     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
2854   }
2855 }
2856 
2857 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
2858   DebugLoc dl = Op.getDebugLoc();
2859   unsigned Opc;
2860 
2861   switch (Op.getOpcode()) {
2862   default:
2863     assert(0 && "Invalid opcode!");
2864   case ISD::FP_TO_SINT:
2865     Opc = ARMISD::FTOSI;
2866     break;
2867   case ISD::FP_TO_UINT:
2868     Opc = ARMISD::FTOUI;
2869     break;
2870   }
2871   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
2872   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
2873 }
2874 
2875 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2876   EVT VT = Op.getValueType();
2877   DebugLoc dl = Op.getDebugLoc();
2878 
2879   EVT OperandVT = Op.getOperand(0).getValueType();
2880   assert(OperandVT == MVT::v4i16 && "Invalid type for custom lowering!");
2881   if (VT != MVT::v4f32)
2882     return DAG.UnrollVectorOp(Op.getNode());
2883 
2884   unsigned CastOpc;
2885   unsigned Opc;
2886   switch (Op.getOpcode()) {
2887   default:
2888     assert(0 && "Invalid opcode!");
2889   case ISD::SINT_TO_FP:
2890     CastOpc = ISD::SIGN_EXTEND;
2891     Opc = ISD::SINT_TO_FP;
2892     break;
2893   case ISD::UINT_TO_FP:
2894     CastOpc = ISD::ZERO_EXTEND;
2895     Opc = ISD::UINT_TO_FP;
2896     break;
2897   }
2898 
2899   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
2900   return DAG.getNode(Opc, dl, VT, Op);
2901 }
2902 
2903 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2904   EVT VT = Op.getValueType();
2905   if (VT.isVector())
2906     return LowerVectorINT_TO_FP(Op, DAG);
2907 
2908   DebugLoc dl = Op.getDebugLoc();
2909   unsigned Opc;
2910 
2911   switch (Op.getOpcode()) {
2912   default:
2913     assert(0 && "Invalid opcode!");
2914   case ISD::SINT_TO_FP:
2915     Opc = ARMISD::SITOF;
2916     break;
2917   case ISD::UINT_TO_FP:
2918     Opc = ARMISD::UITOF;
2919     break;
2920   }
2921 
2922   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
2923   return DAG.getNode(Opc, dl, VT, Op);
2924 }
2925 
2926 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
2927   // Implement fcopysign with a fabs and a conditional fneg.
2928   SDValue Tmp0 = Op.getOperand(0);
2929   SDValue Tmp1 = Op.getOperand(1);
2930   DebugLoc dl = Op.getDebugLoc();
2931   EVT VT = Op.getValueType();
2932   EVT SrcVT = Tmp1.getValueType();
2933   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
2934     Tmp0.getOpcode() == ARMISD::VMOVDRR;
2935   bool UseNEON = !InGPR && Subtarget->hasNEON();
2936 
2937   if (UseNEON) {
2938     // Use VBSL to copy the sign bit.
2939     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
2940     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
2941                                DAG.getTargetConstant(EncodedVal, MVT::i32));
2942     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
2943     if (VT == MVT::f64)
2944       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
2945                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
2946                          DAG.getConstant(32, MVT::i32));
2947     else /*if (VT == MVT::f32)*/
2948       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
2949     if (SrcVT == MVT::f32) {
2950       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
2951       if (VT == MVT::f64)
2952         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
2953                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
2954                            DAG.getConstant(32, MVT::i32));
2955     } else if (VT == MVT::f32)
2956       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
2957                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
2958                          DAG.getConstant(32, MVT::i32));
2959     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
2960     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
2961 
2962     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
2963                                             MVT::i32);
2964     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
2965     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
2966                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
2967 
2968     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
2969                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
2970                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
2971     if (VT == MVT::f32) {
2972       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
2973       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
2974                         DAG.getConstant(0, MVT::i32));
2975     } else {
2976       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
2977     }
2978 
2979     return Res;
2980   }
2981 
2982   // Bitcast operand 1 to i32.
2983   if (SrcVT == MVT::f64)
2984     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
2985                        &Tmp1, 1).getValue(1);
2986   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
2987 
2988   // Or in the signbit with integer operations.
2989   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
2990   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
2991   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
2992   if (VT == MVT::f32) {
2993     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
2994                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
2995     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
2996                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
2997   }
2998 
2999   // f64: Or the high part with signbit and then combine two parts.
3000   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3001                      &Tmp0, 1);
3002   SDValue Lo = Tmp0.getValue(0);
3003   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3004   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3005   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3006 }
3007 
3008 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3009   MachineFunction &MF = DAG.getMachineFunction();
3010   MachineFrameInfo *MFI = MF.getFrameInfo();
3011   MFI->setReturnAddressIsTaken(true);
3012 
3013   EVT VT = Op.getValueType();
3014   DebugLoc dl = Op.getDebugLoc();
3015   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3016   if (Depth) {
3017     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3018     SDValue Offset = DAG.getConstant(4, MVT::i32);
3019     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3020                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3021                        MachinePointerInfo(), false, false, 0);
3022   }
3023 
3024   // Return LR, which contains the return address. Mark it an implicit live-in.
3025   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3026   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3027 }
3028 
3029 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3030   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3031   MFI->setFrameAddressIsTaken(true);
3032 
3033   EVT VT = Op.getValueType();
3034   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
3035   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3036   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3037     ? ARM::R7 : ARM::R11;
3038   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3039   while (Depth--)
3040     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3041                             MachinePointerInfo(),
3042                             false, false, 0);
3043   return FrameAddr;
3044 }
3045 
3046 /// ExpandBITCAST - If the target supports VFP, this function is called to
3047 /// expand a bit convert where either the source or destination type is i64 to
3048 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3049 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3050 /// vectors), since the legalizer won't know what to do with that.
3051 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3052   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3053   DebugLoc dl = N->getDebugLoc();
3054   SDValue Op = N->getOperand(0);
3055 
3056   // This function is only supposed to be called for i64 types, either as the
3057   // source or destination of the bit convert.
3058   EVT SrcVT = Op.getValueType();
3059   EVT DstVT = N->getValueType(0);
3060   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3061          "ExpandBITCAST called for non-i64 type");
3062 
3063   // Turn i64->f64 into VMOVDRR.
3064   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3065     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3066                              DAG.getConstant(0, MVT::i32));
3067     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3068                              DAG.getConstant(1, MVT::i32));
3069     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3070                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3071   }
3072 
3073   // Turn f64->i64 into VMOVRRD.
3074   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3075     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3076                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3077     // Merge the pieces into a single i64 value.
3078     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3079   }
3080 
3081   return SDValue();
3082 }
3083 
3084 /// getZeroVector - Returns a vector of specified type with all zero elements.
3085 /// Zero vectors are used to represent vector negation and in those cases
3086 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3087 /// not support i64 elements, so sometimes the zero vectors will need to be
3088 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3089 /// zero vector.
3090 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3091   assert(VT.isVector() && "Expected a vector type");
3092   // The canonical modified immediate encoding of a zero vector is....0!
3093   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3094   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3095   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3096   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3097 }
3098 
3099 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3100 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3101 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3102                                                 SelectionDAG &DAG) const {
3103   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3104   EVT VT = Op.getValueType();
3105   unsigned VTBits = VT.getSizeInBits();
3106   DebugLoc dl = Op.getDebugLoc();
3107   SDValue ShOpLo = Op.getOperand(0);
3108   SDValue ShOpHi = Op.getOperand(1);
3109   SDValue ShAmt  = Op.getOperand(2);
3110   SDValue ARMcc;
3111   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3112 
3113   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3114 
3115   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3116                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3117   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3118   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3119                                    DAG.getConstant(VTBits, MVT::i32));
3120   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3121   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3122   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3123 
3124   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3125   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3126                           ARMcc, DAG, dl);
3127   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3128   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3129                            CCR, Cmp);
3130 
3131   SDValue Ops[2] = { Lo, Hi };
3132   return DAG.getMergeValues(Ops, 2, dl);
3133 }
3134 
3135 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3136 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3137 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3138                                                SelectionDAG &DAG) const {
3139   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3140   EVT VT = Op.getValueType();
3141   unsigned VTBits = VT.getSizeInBits();
3142   DebugLoc dl = Op.getDebugLoc();
3143   SDValue ShOpLo = Op.getOperand(0);
3144   SDValue ShOpHi = Op.getOperand(1);
3145   SDValue ShAmt  = Op.getOperand(2);
3146   SDValue ARMcc;
3147 
3148   assert(Op.getOpcode() == ISD::SHL_PARTS);
3149   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3150                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3151   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3152   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3153                                    DAG.getConstant(VTBits, MVT::i32));
3154   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3155   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3156 
3157   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3158   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3159   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3160                           ARMcc, DAG, dl);
3161   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3162   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3163                            CCR, Cmp);
3164 
3165   SDValue Ops[2] = { Lo, Hi };
3166   return DAG.getMergeValues(Ops, 2, dl);
3167 }
3168 
3169 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3170                                             SelectionDAG &DAG) const {
3171   // The rounding mode is in bits 23:22 of the FPSCR.
3172   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3173   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3174   // so that the shift + and get folded into a bitfield extract.
3175   DebugLoc dl = Op.getDebugLoc();
3176   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3177                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3178                                               MVT::i32));
3179   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3180                                   DAG.getConstant(1U << 22, MVT::i32));
3181   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3182                               DAG.getConstant(22, MVT::i32));
3183   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3184                      DAG.getConstant(3, MVT::i32));
3185 }
3186 
3187 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3188                          const ARMSubtarget *ST) {
3189   EVT VT = N->getValueType(0);
3190   DebugLoc dl = N->getDebugLoc();
3191 
3192   if (!ST->hasV6T2Ops())
3193     return SDValue();
3194 
3195   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3196   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3197 }
3198 
3199 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3200                           const ARMSubtarget *ST) {
3201   EVT VT = N->getValueType(0);
3202   DebugLoc dl = N->getDebugLoc();
3203 
3204   if (!VT.isVector())
3205     return SDValue();
3206 
3207   // Lower vector shifts on NEON to use VSHL.
3208   assert(ST->hasNEON() && "unexpected vector shift");
3209 
3210   // Left shifts translate directly to the vshiftu intrinsic.
3211   if (N->getOpcode() == ISD::SHL)
3212     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3213                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3214                        N->getOperand(0), N->getOperand(1));
3215 
3216   assert((N->getOpcode() == ISD::SRA ||
3217           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3218 
3219   // NEON uses the same intrinsics for both left and right shifts.  For
3220   // right shifts, the shift amounts are negative, so negate the vector of
3221   // shift amounts.
3222   EVT ShiftVT = N->getOperand(1).getValueType();
3223   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3224                                      getZeroVector(ShiftVT, DAG, dl),
3225                                      N->getOperand(1));
3226   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3227                              Intrinsic::arm_neon_vshifts :
3228                              Intrinsic::arm_neon_vshiftu);
3229   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3230                      DAG.getConstant(vshiftInt, MVT::i32),
3231                      N->getOperand(0), NegatedCount);
3232 }
3233 
3234 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3235                                 const ARMSubtarget *ST) {
3236   EVT VT = N->getValueType(0);
3237   DebugLoc dl = N->getDebugLoc();
3238 
3239   // We can get here for a node like i32 = ISD::SHL i32, i64
3240   if (VT != MVT::i64)
3241     return SDValue();
3242 
3243   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3244          "Unknown shift to lower!");
3245 
3246   // We only lower SRA, SRL of 1 here, all others use generic lowering.
3247   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3248       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3249     return SDValue();
3250 
3251   // If we are in thumb mode, we don't have RRX.
3252   if (ST->isThumb1Only()) return SDValue();
3253 
3254   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
3255   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3256                            DAG.getConstant(0, MVT::i32));
3257   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3258                            DAG.getConstant(1, MVT::i32));
3259 
3260   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3261   // captures the result into a carry flag.
3262   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3263   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3264 
3265   // The low part is an ARMISD::RRX operand, which shifts the carry in.
3266   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3267 
3268   // Merge the pieces into a single i64 value.
3269  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3270 }
3271 
3272 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3273   SDValue TmpOp0, TmpOp1;
3274   bool Invert = false;
3275   bool Swap = false;
3276   unsigned Opc = 0;
3277 
3278   SDValue Op0 = Op.getOperand(0);
3279   SDValue Op1 = Op.getOperand(1);
3280   SDValue CC = Op.getOperand(2);
3281   EVT VT = Op.getValueType();
3282   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3283   DebugLoc dl = Op.getDebugLoc();
3284 
3285   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3286     switch (SetCCOpcode) {
3287     default: llvm_unreachable("Illegal FP comparison"); break;
3288     case ISD::SETUNE:
3289     case ISD::SETNE:  Invert = true; // Fallthrough
3290     case ISD::SETOEQ:
3291     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3292     case ISD::SETOLT:
3293     case ISD::SETLT: Swap = true; // Fallthrough
3294     case ISD::SETOGT:
3295     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3296     case ISD::SETOLE:
3297     case ISD::SETLE:  Swap = true; // Fallthrough
3298     case ISD::SETOGE:
3299     case ISD::SETGE: Opc = ARMISD::VCGE; break;
3300     case ISD::SETUGE: Swap = true; // Fallthrough
3301     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3302     case ISD::SETUGT: Swap = true; // Fallthrough
3303     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3304     case ISD::SETUEQ: Invert = true; // Fallthrough
3305     case ISD::SETONE:
3306       // Expand this to (OLT | OGT).
3307       TmpOp0 = Op0;
3308       TmpOp1 = Op1;
3309       Opc = ISD::OR;
3310       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3311       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3312       break;
3313     case ISD::SETUO: Invert = true; // Fallthrough
3314     case ISD::SETO:
3315       // Expand this to (OLT | OGE).
3316       TmpOp0 = Op0;
3317       TmpOp1 = Op1;
3318       Opc = ISD::OR;
3319       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3320       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3321       break;
3322     }
3323   } else {
3324     // Integer comparisons.
3325     switch (SetCCOpcode) {
3326     default: llvm_unreachable("Illegal integer comparison"); break;
3327     case ISD::SETNE:  Invert = true;
3328     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3329     case ISD::SETLT:  Swap = true;
3330     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3331     case ISD::SETLE:  Swap = true;
3332     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
3333     case ISD::SETULT: Swap = true;
3334     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
3335     case ISD::SETULE: Swap = true;
3336     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
3337     }
3338 
3339     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
3340     if (Opc == ARMISD::VCEQ) {
3341 
3342       SDValue AndOp;
3343       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3344         AndOp = Op0;
3345       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
3346         AndOp = Op1;
3347 
3348       // Ignore bitconvert.
3349       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
3350         AndOp = AndOp.getOperand(0);
3351 
3352       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
3353         Opc = ARMISD::VTST;
3354         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
3355         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
3356         Invert = !Invert;
3357       }
3358     }
3359   }
3360 
3361   if (Swap)
3362     std::swap(Op0, Op1);
3363 
3364   // If one of the operands is a constant vector zero, attempt to fold the
3365   // comparison to a specialized compare-against-zero form.
3366   SDValue SingleOp;
3367   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3368     SingleOp = Op0;
3369   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
3370     if (Opc == ARMISD::VCGE)
3371       Opc = ARMISD::VCLEZ;
3372     else if (Opc == ARMISD::VCGT)
3373       Opc = ARMISD::VCLTZ;
3374     SingleOp = Op1;
3375   }
3376 
3377   SDValue Result;
3378   if (SingleOp.getNode()) {
3379     switch (Opc) {
3380     case ARMISD::VCEQ:
3381       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
3382     case ARMISD::VCGE:
3383       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
3384     case ARMISD::VCLEZ:
3385       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
3386     case ARMISD::VCGT:
3387       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
3388     case ARMISD::VCLTZ:
3389       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
3390     default:
3391       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3392     }
3393   } else {
3394      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3395   }
3396 
3397   if (Invert)
3398     Result = DAG.getNOT(dl, Result, VT);
3399 
3400   return Result;
3401 }
3402 
3403 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
3404 /// valid vector constant for a NEON instruction with a "modified immediate"
3405 /// operand (e.g., VMOV).  If so, return the encoded value.
3406 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
3407                                  unsigned SplatBitSize, SelectionDAG &DAG,
3408                                  EVT &VT, bool is128Bits, NEONModImmType type) {
3409   unsigned OpCmode, Imm;
3410 
3411   // SplatBitSize is set to the smallest size that splats the vector, so a
3412   // zero vector will always have SplatBitSize == 8.  However, NEON modified
3413   // immediate instructions others than VMOV do not support the 8-bit encoding
3414   // of a zero vector, and the default encoding of zero is supposed to be the
3415   // 32-bit version.
3416   if (SplatBits == 0)
3417     SplatBitSize = 32;
3418 
3419   switch (SplatBitSize) {
3420   case 8:
3421     if (type != VMOVModImm)
3422       return SDValue();
3423     // Any 1-byte value is OK.  Op=0, Cmode=1110.
3424     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
3425     OpCmode = 0xe;
3426     Imm = SplatBits;
3427     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
3428     break;
3429 
3430   case 16:
3431     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
3432     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3433     if ((SplatBits & ~0xff) == 0) {
3434       // Value = 0x00nn: Op=x, Cmode=100x.
3435       OpCmode = 0x8;
3436       Imm = SplatBits;
3437       break;
3438     }
3439     if ((SplatBits & ~0xff00) == 0) {
3440       // Value = 0xnn00: Op=x, Cmode=101x.
3441       OpCmode = 0xa;
3442       Imm = SplatBits >> 8;
3443       break;
3444     }
3445     return SDValue();
3446 
3447   case 32:
3448     // NEON's 32-bit VMOV supports splat values where:
3449     // * only one byte is nonzero, or
3450     // * the least significant byte is 0xff and the second byte is nonzero, or
3451     // * the least significant 2 bytes are 0xff and the third is nonzero.
3452     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3453     if ((SplatBits & ~0xff) == 0) {
3454       // Value = 0x000000nn: Op=x, Cmode=000x.
3455       OpCmode = 0;
3456       Imm = SplatBits;
3457       break;
3458     }
3459     if ((SplatBits & ~0xff00) == 0) {
3460       // Value = 0x0000nn00: Op=x, Cmode=001x.
3461       OpCmode = 0x2;
3462       Imm = SplatBits >> 8;
3463       break;
3464     }
3465     if ((SplatBits & ~0xff0000) == 0) {
3466       // Value = 0x00nn0000: Op=x, Cmode=010x.
3467       OpCmode = 0x4;
3468       Imm = SplatBits >> 16;
3469       break;
3470     }
3471     if ((SplatBits & ~0xff000000) == 0) {
3472       // Value = 0xnn000000: Op=x, Cmode=011x.
3473       OpCmode = 0x6;
3474       Imm = SplatBits >> 24;
3475       break;
3476     }
3477 
3478     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
3479     if (type == OtherModImm) return SDValue();
3480 
3481     if ((SplatBits & ~0xffff) == 0 &&
3482         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
3483       // Value = 0x0000nnff: Op=x, Cmode=1100.
3484       OpCmode = 0xc;
3485       Imm = SplatBits >> 8;
3486       SplatBits |= 0xff;
3487       break;
3488     }
3489 
3490     if ((SplatBits & ~0xffffff) == 0 &&
3491         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
3492       // Value = 0x00nnffff: Op=x, Cmode=1101.
3493       OpCmode = 0xd;
3494       Imm = SplatBits >> 16;
3495       SplatBits |= 0xffff;
3496       break;
3497     }
3498 
3499     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
3500     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
3501     // VMOV.I32.  A (very) minor optimization would be to replicate the value
3502     // and fall through here to test for a valid 64-bit splat.  But, then the
3503     // caller would also need to check and handle the change in size.
3504     return SDValue();
3505 
3506   case 64: {
3507     if (type != VMOVModImm)
3508       return SDValue();
3509     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
3510     uint64_t BitMask = 0xff;
3511     uint64_t Val = 0;
3512     unsigned ImmMask = 1;
3513     Imm = 0;
3514     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
3515       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
3516         Val |= BitMask;
3517         Imm |= ImmMask;
3518       } else if ((SplatBits & BitMask) != 0) {
3519         return SDValue();
3520       }
3521       BitMask <<= 8;
3522       ImmMask <<= 1;
3523     }
3524     // Op=1, Cmode=1110.
3525     OpCmode = 0x1e;
3526     SplatBits = Val;
3527     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
3528     break;
3529   }
3530 
3531   default:
3532     llvm_unreachable("unexpected size for isNEONModifiedImm");
3533     return SDValue();
3534   }
3535 
3536   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
3537   return DAG.getTargetConstant(EncodedVal, MVT::i32);
3538 }
3539 
3540 static bool isVEXTMask(const SmallVectorImpl<int> &M, EVT VT,
3541                        bool &ReverseVEXT, unsigned &Imm) {
3542   unsigned NumElts = VT.getVectorNumElements();
3543   ReverseVEXT = false;
3544 
3545   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
3546   if (M[0] < 0)
3547     return false;
3548 
3549   Imm = M[0];
3550 
3551   // If this is a VEXT shuffle, the immediate value is the index of the first
3552   // element.  The other shuffle indices must be the successive elements after
3553   // the first one.
3554   unsigned ExpectedElt = Imm;
3555   for (unsigned i = 1; i < NumElts; ++i) {
3556     // Increment the expected index.  If it wraps around, it may still be
3557     // a VEXT but the source vectors must be swapped.
3558     ExpectedElt += 1;
3559     if (ExpectedElt == NumElts * 2) {
3560       ExpectedElt = 0;
3561       ReverseVEXT = true;
3562     }
3563 
3564     if (M[i] < 0) continue; // ignore UNDEF indices
3565     if (ExpectedElt != static_cast<unsigned>(M[i]))
3566       return false;
3567   }
3568 
3569   // Adjust the index value if the source operands will be swapped.
3570   if (ReverseVEXT)
3571     Imm -= NumElts;
3572 
3573   return true;
3574 }
3575 
3576 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
3577 /// instruction with the specified blocksize.  (The order of the elements
3578 /// within each block of the vector is reversed.)
3579 static bool isVREVMask(const SmallVectorImpl<int> &M, EVT VT,
3580                        unsigned BlockSize) {
3581   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
3582          "Only possible block sizes for VREV are: 16, 32, 64");
3583 
3584   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3585   if (EltSz == 64)
3586     return false;
3587 
3588   unsigned NumElts = VT.getVectorNumElements();
3589   unsigned BlockElts = M[0] + 1;
3590   // If the first shuffle index is UNDEF, be optimistic.
3591   if (M[0] < 0)
3592     BlockElts = BlockSize / EltSz;
3593 
3594   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
3595     return false;
3596 
3597   for (unsigned i = 0; i < NumElts; ++i) {
3598     if (M[i] < 0) continue; // ignore UNDEF indices
3599     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
3600       return false;
3601   }
3602 
3603   return true;
3604 }
3605 
3606 static bool isVTBLMask(const SmallVectorImpl<int> &M, EVT VT) {
3607   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
3608   // range, then 0 is placed into the resulting vector. So pretty much any mask
3609   // of 8 elements can work here.
3610   return VT == MVT::v8i8 && M.size() == 8;
3611 }
3612 
3613 static bool isVTRNMask(const SmallVectorImpl<int> &M, EVT VT,
3614                        unsigned &WhichResult) {
3615   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3616   if (EltSz == 64)
3617     return false;
3618 
3619   unsigned NumElts = VT.getVectorNumElements();
3620   WhichResult = (M[0] == 0 ? 0 : 1);
3621   for (unsigned i = 0; i < NumElts; i += 2) {
3622     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3623         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
3624       return false;
3625   }
3626   return true;
3627 }
3628 
3629 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
3630 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
3631 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
3632 static bool isVTRN_v_undef_Mask(const SmallVectorImpl<int> &M, EVT VT,
3633                                 unsigned &WhichResult) {
3634   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3635   if (EltSz == 64)
3636     return false;
3637 
3638   unsigned NumElts = VT.getVectorNumElements();
3639   WhichResult = (M[0] == 0 ? 0 : 1);
3640   for (unsigned i = 0; i < NumElts; i += 2) {
3641     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3642         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
3643       return false;
3644   }
3645   return true;
3646 }
3647 
3648 static bool isVUZPMask(const SmallVectorImpl<int> &M, EVT VT,
3649                        unsigned &WhichResult) {
3650   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3651   if (EltSz == 64)
3652     return false;
3653 
3654   unsigned NumElts = VT.getVectorNumElements();
3655   WhichResult = (M[0] == 0 ? 0 : 1);
3656   for (unsigned i = 0; i != NumElts; ++i) {
3657     if (M[i] < 0) continue; // ignore UNDEF indices
3658     if ((unsigned) M[i] != 2 * i + WhichResult)
3659       return false;
3660   }
3661 
3662   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
3663   if (VT.is64BitVector() && EltSz == 32)
3664     return false;
3665 
3666   return true;
3667 }
3668 
3669 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
3670 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
3671 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
3672 static bool isVUZP_v_undef_Mask(const SmallVectorImpl<int> &M, EVT VT,
3673                                 unsigned &WhichResult) {
3674   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3675   if (EltSz == 64)
3676     return false;
3677 
3678   unsigned Half = VT.getVectorNumElements() / 2;
3679   WhichResult = (M[0] == 0 ? 0 : 1);
3680   for (unsigned j = 0; j != 2; ++j) {
3681     unsigned Idx = WhichResult;
3682     for (unsigned i = 0; i != Half; ++i) {
3683       int MIdx = M[i + j * Half];
3684       if (MIdx >= 0 && (unsigned) MIdx != Idx)
3685         return false;
3686       Idx += 2;
3687     }
3688   }
3689 
3690   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
3691   if (VT.is64BitVector() && EltSz == 32)
3692     return false;
3693 
3694   return true;
3695 }
3696 
3697 static bool isVZIPMask(const SmallVectorImpl<int> &M, EVT VT,
3698                        unsigned &WhichResult) {
3699   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3700   if (EltSz == 64)
3701     return false;
3702 
3703   unsigned NumElts = VT.getVectorNumElements();
3704   WhichResult = (M[0] == 0 ? 0 : 1);
3705   unsigned Idx = WhichResult * NumElts / 2;
3706   for (unsigned i = 0; i != NumElts; i += 2) {
3707     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
3708         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
3709       return false;
3710     Idx += 1;
3711   }
3712 
3713   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
3714   if (VT.is64BitVector() && EltSz == 32)
3715     return false;
3716 
3717   return true;
3718 }
3719 
3720 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
3721 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
3722 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
3723 static bool isVZIP_v_undef_Mask(const SmallVectorImpl<int> &M, EVT VT,
3724                                 unsigned &WhichResult) {
3725   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3726   if (EltSz == 64)
3727     return false;
3728 
3729   unsigned NumElts = VT.getVectorNumElements();
3730   WhichResult = (M[0] == 0 ? 0 : 1);
3731   unsigned Idx = WhichResult * NumElts / 2;
3732   for (unsigned i = 0; i != NumElts; i += 2) {
3733     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
3734         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
3735       return false;
3736     Idx += 1;
3737   }
3738 
3739   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
3740   if (VT.is64BitVector() && EltSz == 32)
3741     return false;
3742 
3743   return true;
3744 }
3745 
3746 // If N is an integer constant that can be moved into a register in one
3747 // instruction, return an SDValue of such a constant (will become a MOV
3748 // instruction).  Otherwise return null.
3749 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
3750                                      const ARMSubtarget *ST, DebugLoc dl) {
3751   uint64_t Val;
3752   if (!isa<ConstantSDNode>(N))
3753     return SDValue();
3754   Val = cast<ConstantSDNode>(N)->getZExtValue();
3755 
3756   if (ST->isThumb1Only()) {
3757     if (Val <= 255 || ~Val <= 255)
3758       return DAG.getConstant(Val, MVT::i32);
3759   } else {
3760     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
3761       return DAG.getConstant(Val, MVT::i32);
3762   }
3763   return SDValue();
3764 }
3765 
3766 // If this is a case we can't handle, return null and let the default
3767 // expansion code take care of it.
3768 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
3769                                              const ARMSubtarget *ST) const {
3770   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
3771   DebugLoc dl = Op.getDebugLoc();
3772   EVT VT = Op.getValueType();
3773 
3774   APInt SplatBits, SplatUndef;
3775   unsigned SplatBitSize;
3776   bool HasAnyUndefs;
3777   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
3778     if (SplatBitSize <= 64) {
3779       // Check if an immediate VMOV works.
3780       EVT VmovVT;
3781       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
3782                                       SplatUndef.getZExtValue(), SplatBitSize,
3783                                       DAG, VmovVT, VT.is128BitVector(),
3784                                       VMOVModImm);
3785       if (Val.getNode()) {
3786         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
3787         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3788       }
3789 
3790       // Try an immediate VMVN.
3791       uint64_t NegatedImm = (SplatBits.getZExtValue() ^
3792                              ((1LL << SplatBitSize) - 1));
3793       Val = isNEONModifiedImm(NegatedImm,
3794                                       SplatUndef.getZExtValue(), SplatBitSize,
3795                                       DAG, VmovVT, VT.is128BitVector(),
3796                                       VMVNModImm);
3797       if (Val.getNode()) {
3798         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
3799         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3800       }
3801     }
3802   }
3803 
3804   // Scan through the operands to see if only one value is used.
3805   unsigned NumElts = VT.getVectorNumElements();
3806   bool isOnlyLowElement = true;
3807   bool usesOnlyOneValue = true;
3808   bool isConstant = true;
3809   SDValue Value;
3810   for (unsigned i = 0; i < NumElts; ++i) {
3811     SDValue V = Op.getOperand(i);
3812     if (V.getOpcode() == ISD::UNDEF)
3813       continue;
3814     if (i > 0)
3815       isOnlyLowElement = false;
3816     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
3817       isConstant = false;
3818 
3819     if (!Value.getNode())
3820       Value = V;
3821     else if (V != Value)
3822       usesOnlyOneValue = false;
3823   }
3824 
3825   if (!Value.getNode())
3826     return DAG.getUNDEF(VT);
3827 
3828   if (isOnlyLowElement)
3829     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
3830 
3831   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3832 
3833   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
3834   // i32 and try again.
3835   if (usesOnlyOneValue && EltSize <= 32) {
3836     if (!isConstant)
3837       return DAG.getNode(ARMISD::VDUP, dl, VT, Value);
3838     if (VT.getVectorElementType().isFloatingPoint()) {
3839       SmallVector<SDValue, 8> Ops;
3840       for (unsigned i = 0; i < NumElts; ++i)
3841         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
3842                                   Op.getOperand(i)));
3843       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
3844       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
3845       Val = LowerBUILD_VECTOR(Val, DAG, ST);
3846       if (Val.getNode())
3847         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
3848     }
3849     SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
3850     if (Val.getNode())
3851       return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
3852   }
3853 
3854   // If all elements are constants and the case above didn't get hit, fall back
3855   // to the default expansion, which will generate a load from the constant
3856   // pool.
3857   if (isConstant)
3858     return SDValue();
3859 
3860   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
3861   if (NumElts >= 4) {
3862     SDValue shuffle = ReconstructShuffle(Op, DAG);
3863     if (shuffle != SDValue())
3864       return shuffle;
3865   }
3866 
3867   // Vectors with 32- or 64-bit elements can be built by directly assigning
3868   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
3869   // will be legalized.
3870   if (EltSize >= 32) {
3871     // Do the expansion with floating-point types, since that is what the VFP
3872     // registers are defined to use, and since i64 is not legal.
3873     EVT EltVT = EVT::getFloatingPointVT(EltSize);
3874     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
3875     SmallVector<SDValue, 8> Ops;
3876     for (unsigned i = 0; i < NumElts; ++i)
3877       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
3878     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
3879     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
3880   }
3881 
3882   return SDValue();
3883 }
3884 
3885 // Gather data to see if the operation can be modelled as a
3886 // shuffle in combination with VEXTs.
3887 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
3888                                               SelectionDAG &DAG) const {
3889   DebugLoc dl = Op.getDebugLoc();
3890   EVT VT = Op.getValueType();
3891   unsigned NumElts = VT.getVectorNumElements();
3892 
3893   SmallVector<SDValue, 2> SourceVecs;
3894   SmallVector<unsigned, 2> MinElts;
3895   SmallVector<unsigned, 2> MaxElts;
3896 
3897   for (unsigned i = 0; i < NumElts; ++i) {
3898     SDValue V = Op.getOperand(i);
3899     if (V.getOpcode() == ISD::UNDEF)
3900       continue;
3901     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
3902       // A shuffle can only come from building a vector from various
3903       // elements of other vectors.
3904       return SDValue();
3905     }
3906 
3907     // Record this extraction against the appropriate vector if possible...
3908     SDValue SourceVec = V.getOperand(0);
3909     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
3910     bool FoundSource = false;
3911     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
3912       if (SourceVecs[j] == SourceVec) {
3913         if (MinElts[j] > EltNo)
3914           MinElts[j] = EltNo;
3915         if (MaxElts[j] < EltNo)
3916           MaxElts[j] = EltNo;
3917         FoundSource = true;
3918         break;
3919       }
3920     }
3921 
3922     // Or record a new source if not...
3923     if (!FoundSource) {
3924       SourceVecs.push_back(SourceVec);
3925       MinElts.push_back(EltNo);
3926       MaxElts.push_back(EltNo);
3927     }
3928   }
3929 
3930   // Currently only do something sane when at most two source vectors
3931   // involved.
3932   if (SourceVecs.size() > 2)
3933     return SDValue();
3934 
3935   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
3936   int VEXTOffsets[2] = {0, 0};
3937 
3938   // This loop extracts the usage patterns of the source vectors
3939   // and prepares appropriate SDValues for a shuffle if possible.
3940   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
3941     if (SourceVecs[i].getValueType() == VT) {
3942       // No VEXT necessary
3943       ShuffleSrcs[i] = SourceVecs[i];
3944       VEXTOffsets[i] = 0;
3945       continue;
3946     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
3947       // It probably isn't worth padding out a smaller vector just to
3948       // break it down again in a shuffle.
3949       return SDValue();
3950     }
3951 
3952     // Since only 64-bit and 128-bit vectors are legal on ARM and
3953     // we've eliminated the other cases...
3954     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
3955            "unexpected vector sizes in ReconstructShuffle");
3956 
3957     if (MaxElts[i] - MinElts[i] >= NumElts) {
3958       // Span too large for a VEXT to cope
3959       return SDValue();
3960     }
3961 
3962     if (MinElts[i] >= NumElts) {
3963       // The extraction can just take the second half
3964       VEXTOffsets[i] = NumElts;
3965       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
3966                                    SourceVecs[i],
3967                                    DAG.getIntPtrConstant(NumElts));
3968     } else if (MaxElts[i] < NumElts) {
3969       // The extraction can just take the first half
3970       VEXTOffsets[i] = 0;
3971       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
3972                                    SourceVecs[i],
3973                                    DAG.getIntPtrConstant(0));
3974     } else {
3975       // An actual VEXT is needed
3976       VEXTOffsets[i] = MinElts[i];
3977       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
3978                                      SourceVecs[i],
3979                                      DAG.getIntPtrConstant(0));
3980       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
3981                                      SourceVecs[i],
3982                                      DAG.getIntPtrConstant(NumElts));
3983       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
3984                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
3985     }
3986   }
3987 
3988   SmallVector<int, 8> Mask;
3989 
3990   for (unsigned i = 0; i < NumElts; ++i) {
3991     SDValue Entry = Op.getOperand(i);
3992     if (Entry.getOpcode() == ISD::UNDEF) {
3993       Mask.push_back(-1);
3994       continue;
3995     }
3996 
3997     SDValue ExtractVec = Entry.getOperand(0);
3998     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
3999                                           .getOperand(1))->getSExtValue();
4000     if (ExtractVec == SourceVecs[0]) {
4001       Mask.push_back(ExtractElt - VEXTOffsets[0]);
4002     } else {
4003       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4004     }
4005   }
4006 
4007   // Final check before we try to produce nonsense...
4008   if (isShuffleMaskLegal(Mask, VT))
4009     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4010                                 &Mask[0]);
4011 
4012   return SDValue();
4013 }
4014 
4015 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4016 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4017 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4018 /// are assumed to be legal.
4019 bool
4020 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4021                                       EVT VT) const {
4022   if (VT.getVectorNumElements() == 4 &&
4023       (VT.is128BitVector() || VT.is64BitVector())) {
4024     unsigned PFIndexes[4];
4025     for (unsigned i = 0; i != 4; ++i) {
4026       if (M[i] < 0)
4027         PFIndexes[i] = 8;
4028       else
4029         PFIndexes[i] = M[i];
4030     }
4031 
4032     // Compute the index in the perfect shuffle table.
4033     unsigned PFTableIndex =
4034       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4035     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4036     unsigned Cost = (PFEntry >> 30);
4037 
4038     if (Cost <= 4)
4039       return true;
4040   }
4041 
4042   bool ReverseVEXT;
4043   unsigned Imm, WhichResult;
4044 
4045   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4046   return (EltSize >= 32 ||
4047           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4048           isVREVMask(M, VT, 64) ||
4049           isVREVMask(M, VT, 32) ||
4050           isVREVMask(M, VT, 16) ||
4051           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4052           isVTBLMask(M, VT) ||
4053           isVTRNMask(M, VT, WhichResult) ||
4054           isVUZPMask(M, VT, WhichResult) ||
4055           isVZIPMask(M, VT, WhichResult) ||
4056           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4057           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4058           isVZIP_v_undef_Mask(M, VT, WhichResult));
4059 }
4060 
4061 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4062 /// the specified operations to build the shuffle.
4063 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4064                                       SDValue RHS, SelectionDAG &DAG,
4065                                       DebugLoc dl) {
4066   unsigned OpNum = (PFEntry >> 26) & 0x0F;
4067   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4068   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
4069 
4070   enum {
4071     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4072     OP_VREV,
4073     OP_VDUP0,
4074     OP_VDUP1,
4075     OP_VDUP2,
4076     OP_VDUP3,
4077     OP_VEXT1,
4078     OP_VEXT2,
4079     OP_VEXT3,
4080     OP_VUZPL, // VUZP, left result
4081     OP_VUZPR, // VUZP, right result
4082     OP_VZIPL, // VZIP, left result
4083     OP_VZIPR, // VZIP, right result
4084     OP_VTRNL, // VTRN, left result
4085     OP_VTRNR  // VTRN, right result
4086   };
4087 
4088   if (OpNum == OP_COPY) {
4089     if (LHSID == (1*9+2)*9+3) return LHS;
4090     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4091     return RHS;
4092   }
4093 
4094   SDValue OpLHS, OpRHS;
4095   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4096   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4097   EVT VT = OpLHS.getValueType();
4098 
4099   switch (OpNum) {
4100   default: llvm_unreachable("Unknown shuffle opcode!");
4101   case OP_VREV:
4102     return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4103   case OP_VDUP0:
4104   case OP_VDUP1:
4105   case OP_VDUP2:
4106   case OP_VDUP3:
4107     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4108                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4109   case OP_VEXT1:
4110   case OP_VEXT2:
4111   case OP_VEXT3:
4112     return DAG.getNode(ARMISD::VEXT, dl, VT,
4113                        OpLHS, OpRHS,
4114                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4115   case OP_VUZPL:
4116   case OP_VUZPR:
4117     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4118                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4119   case OP_VZIPL:
4120   case OP_VZIPR:
4121     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4122                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4123   case OP_VTRNL:
4124   case OP_VTRNR:
4125     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4126                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4127   }
4128 }
4129 
4130 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4131                                        SmallVectorImpl<int> &ShuffleMask,
4132                                        SelectionDAG &DAG) {
4133   // Check to see if we can use the VTBL instruction.
4134   SDValue V1 = Op.getOperand(0);
4135   SDValue V2 = Op.getOperand(1);
4136   DebugLoc DL = Op.getDebugLoc();
4137 
4138   SmallVector<SDValue, 8> VTBLMask;
4139   for (SmallVectorImpl<int>::iterator
4140          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
4141     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
4142 
4143   if (V2.getNode()->getOpcode() == ISD::UNDEF)
4144     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
4145                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4146                                    &VTBLMask[0], 8));
4147 
4148   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
4149                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4150                                  &VTBLMask[0], 8));
4151 }
4152 
4153 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4154   SDValue V1 = Op.getOperand(0);
4155   SDValue V2 = Op.getOperand(1);
4156   DebugLoc dl = Op.getDebugLoc();
4157   EVT VT = Op.getValueType();
4158   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4159   SmallVector<int, 8> ShuffleMask;
4160 
4161   // Convert shuffles that are directly supported on NEON to target-specific
4162   // DAG nodes, instead of keeping them as shuffles and matching them again
4163   // during code selection.  This is more efficient and avoids the possibility
4164   // of inconsistencies between legalization and selection.
4165   // FIXME: floating-point vectors should be canonicalized to integer vectors
4166   // of the same time so that they get CSEd properly.
4167   SVN->getMask(ShuffleMask);
4168 
4169   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4170   if (EltSize <= 32) {
4171     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4172       int Lane = SVN->getSplatIndex();
4173       // If this is undef splat, generate it via "just" vdup, if possible.
4174       if (Lane == -1) Lane = 0;
4175 
4176       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4177         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4178       }
4179       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
4180                          DAG.getConstant(Lane, MVT::i32));
4181     }
4182 
4183     bool ReverseVEXT;
4184     unsigned Imm;
4185     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
4186       if (ReverseVEXT)
4187         std::swap(V1, V2);
4188       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
4189                          DAG.getConstant(Imm, MVT::i32));
4190     }
4191 
4192     if (isVREVMask(ShuffleMask, VT, 64))
4193       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
4194     if (isVREVMask(ShuffleMask, VT, 32))
4195       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
4196     if (isVREVMask(ShuffleMask, VT, 16))
4197       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
4198 
4199     // Check for Neon shuffles that modify both input vectors in place.
4200     // If both results are used, i.e., if there are two shuffles with the same
4201     // source operands and with masks corresponding to both results of one of
4202     // these operations, DAG memoization will ensure that a single node is
4203     // used for both shuffles.
4204     unsigned WhichResult;
4205     if (isVTRNMask(ShuffleMask, VT, WhichResult))
4206       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4207                          V1, V2).getValue(WhichResult);
4208     if (isVUZPMask(ShuffleMask, VT, WhichResult))
4209       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4210                          V1, V2).getValue(WhichResult);
4211     if (isVZIPMask(ShuffleMask, VT, WhichResult))
4212       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4213                          V1, V2).getValue(WhichResult);
4214 
4215     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
4216       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4217                          V1, V1).getValue(WhichResult);
4218     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4219       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4220                          V1, V1).getValue(WhichResult);
4221     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4222       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4223                          V1, V1).getValue(WhichResult);
4224   }
4225 
4226   // If the shuffle is not directly supported and it has 4 elements, use
4227   // the PerfectShuffle-generated table to synthesize it from other shuffles.
4228   unsigned NumElts = VT.getVectorNumElements();
4229   if (NumElts == 4) {
4230     unsigned PFIndexes[4];
4231     for (unsigned i = 0; i != 4; ++i) {
4232       if (ShuffleMask[i] < 0)
4233         PFIndexes[i] = 8;
4234       else
4235         PFIndexes[i] = ShuffleMask[i];
4236     }
4237 
4238     // Compute the index in the perfect shuffle table.
4239     unsigned PFTableIndex =
4240       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4241     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4242     unsigned Cost = (PFEntry >> 30);
4243 
4244     if (Cost <= 4)
4245       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4246   }
4247 
4248   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
4249   if (EltSize >= 32) {
4250     // Do the expansion with floating-point types, since that is what the VFP
4251     // registers are defined to use, and since i64 is not legal.
4252     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4253     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4254     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
4255     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
4256     SmallVector<SDValue, 8> Ops;
4257     for (unsigned i = 0; i < NumElts; ++i) {
4258       if (ShuffleMask[i] < 0)
4259         Ops.push_back(DAG.getUNDEF(EltVT));
4260       else
4261         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
4262                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
4263                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
4264                                                   MVT::i32)));
4265     }
4266     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4267     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4268   }
4269 
4270   if (VT == MVT::v8i8) {
4271     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
4272     if (NewOp.getNode())
4273       return NewOp;
4274   }
4275 
4276   return SDValue();
4277 }
4278 
4279 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4280   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
4281   SDValue Lane = Op.getOperand(1);
4282   if (!isa<ConstantSDNode>(Lane))
4283     return SDValue();
4284 
4285   SDValue Vec = Op.getOperand(0);
4286   if (Op.getValueType() == MVT::i32 &&
4287       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
4288     DebugLoc dl = Op.getDebugLoc();
4289     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
4290   }
4291 
4292   return Op;
4293 }
4294 
4295 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
4296   // The only time a CONCAT_VECTORS operation can have legal types is when
4297   // two 64-bit vectors are concatenated to a 128-bit vector.
4298   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
4299          "unexpected CONCAT_VECTORS");
4300   DebugLoc dl = Op.getDebugLoc();
4301   SDValue Val = DAG.getUNDEF(MVT::v2f64);
4302   SDValue Op0 = Op.getOperand(0);
4303   SDValue Op1 = Op.getOperand(1);
4304   if (Op0.getOpcode() != ISD::UNDEF)
4305     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4306                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
4307                       DAG.getIntPtrConstant(0));
4308   if (Op1.getOpcode() != ISD::UNDEF)
4309     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4310                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
4311                       DAG.getIntPtrConstant(1));
4312   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
4313 }
4314 
4315 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
4316 /// element has been zero/sign-extended, depending on the isSigned parameter,
4317 /// from an integer type half its size.
4318 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
4319                                    bool isSigned) {
4320   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
4321   EVT VT = N->getValueType(0);
4322   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
4323     SDNode *BVN = N->getOperand(0).getNode();
4324     if (BVN->getValueType(0) != MVT::v4i32 ||
4325         BVN->getOpcode() != ISD::BUILD_VECTOR)
4326       return false;
4327     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4328     unsigned HiElt = 1 - LoElt;
4329     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
4330     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
4331     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
4332     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
4333     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
4334       return false;
4335     if (isSigned) {
4336       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
4337           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
4338         return true;
4339     } else {
4340       if (Hi0->isNullValue() && Hi1->isNullValue())
4341         return true;
4342     }
4343     return false;
4344   }
4345 
4346   if (N->getOpcode() != ISD::BUILD_VECTOR)
4347     return false;
4348 
4349   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
4350     SDNode *Elt = N->getOperand(i).getNode();
4351     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
4352       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4353       unsigned HalfSize = EltSize / 2;
4354       if (isSigned) {
4355         int64_t SExtVal = C->getSExtValue();
4356         if ((SExtVal >> HalfSize) != (SExtVal >> EltSize))
4357           return false;
4358       } else {
4359         if ((C->getZExtValue() >> HalfSize) != 0)
4360           return false;
4361       }
4362       continue;
4363     }
4364     return false;
4365   }
4366 
4367   return true;
4368 }
4369 
4370 /// isSignExtended - Check if a node is a vector value that is sign-extended
4371 /// or a constant BUILD_VECTOR with sign-extended elements.
4372 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
4373   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
4374     return true;
4375   if (isExtendedBUILD_VECTOR(N, DAG, true))
4376     return true;
4377   return false;
4378 }
4379 
4380 /// isZeroExtended - Check if a node is a vector value that is zero-extended
4381 /// or a constant BUILD_VECTOR with zero-extended elements.
4382 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
4383   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
4384     return true;
4385   if (isExtendedBUILD_VECTOR(N, DAG, false))
4386     return true;
4387   return false;
4388 }
4389 
4390 /// SkipExtension - For a node that is a SIGN_EXTEND, ZERO_EXTEND, extending
4391 /// load, or BUILD_VECTOR with extended elements, return the unextended value.
4392 static SDValue SkipExtension(SDNode *N, SelectionDAG &DAG) {
4393   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
4394     return N->getOperand(0);
4395   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
4396     return DAG.getLoad(LD->getMemoryVT(), N->getDebugLoc(), LD->getChain(),
4397                        LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
4398                        LD->isNonTemporal(), LD->getAlignment());
4399   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
4400   // have been legalized as a BITCAST from v4i32.
4401   if (N->getOpcode() == ISD::BITCAST) {
4402     SDNode *BVN = N->getOperand(0).getNode();
4403     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
4404            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
4405     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4406     return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
4407                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
4408   }
4409   // Construct a new BUILD_VECTOR with elements truncated to half the size.
4410   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
4411   EVT VT = N->getValueType(0);
4412   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
4413   unsigned NumElts = VT.getVectorNumElements();
4414   MVT TruncVT = MVT::getIntegerVT(EltSize);
4415   SmallVector<SDValue, 8> Ops;
4416   for (unsigned i = 0; i != NumElts; ++i) {
4417     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
4418     const APInt &CInt = C->getAPIntValue();
4419     Ops.push_back(DAG.getConstant(CInt.trunc(EltSize), TruncVT));
4420   }
4421   return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
4422                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
4423 }
4424 
4425 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
4426   unsigned Opcode = N->getOpcode();
4427   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4428     SDNode *N0 = N->getOperand(0).getNode();
4429     SDNode *N1 = N->getOperand(1).getNode();
4430     return N0->hasOneUse() && N1->hasOneUse() &&
4431       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
4432   }
4433   return false;
4434 }
4435 
4436 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
4437   unsigned Opcode = N->getOpcode();
4438   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4439     SDNode *N0 = N->getOperand(0).getNode();
4440     SDNode *N1 = N->getOperand(1).getNode();
4441     return N0->hasOneUse() && N1->hasOneUse() &&
4442       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
4443   }
4444   return false;
4445 }
4446 
4447 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
4448   // Multiplications are only custom-lowered for 128-bit vectors so that
4449   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
4450   EVT VT = Op.getValueType();
4451   assert(VT.is128BitVector() && "unexpected type for custom-lowering ISD::MUL");
4452   SDNode *N0 = Op.getOperand(0).getNode();
4453   SDNode *N1 = Op.getOperand(1).getNode();
4454   unsigned NewOpc = 0;
4455   bool isMLA = false;
4456   bool isN0SExt = isSignExtended(N0, DAG);
4457   bool isN1SExt = isSignExtended(N1, DAG);
4458   if (isN0SExt && isN1SExt)
4459     NewOpc = ARMISD::VMULLs;
4460   else {
4461     bool isN0ZExt = isZeroExtended(N0, DAG);
4462     bool isN1ZExt = isZeroExtended(N1, DAG);
4463     if (isN0ZExt && isN1ZExt)
4464       NewOpc = ARMISD::VMULLu;
4465     else if (isN1SExt || isN1ZExt) {
4466       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
4467       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
4468       if (isN1SExt && isAddSubSExt(N0, DAG)) {
4469         NewOpc = ARMISD::VMULLs;
4470         isMLA = true;
4471       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
4472         NewOpc = ARMISD::VMULLu;
4473         isMLA = true;
4474       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
4475         std::swap(N0, N1);
4476         NewOpc = ARMISD::VMULLu;
4477         isMLA = true;
4478       }
4479     }
4480 
4481     if (!NewOpc) {
4482       if (VT == MVT::v2i64)
4483         // Fall through to expand this.  It is not legal.
4484         return SDValue();
4485       else
4486         // Other vector multiplications are legal.
4487         return Op;
4488     }
4489   }
4490 
4491   // Legalize to a VMULL instruction.
4492   DebugLoc DL = Op.getDebugLoc();
4493   SDValue Op0;
4494   SDValue Op1 = SkipExtension(N1, DAG);
4495   if (!isMLA) {
4496     Op0 = SkipExtension(N0, DAG);
4497     assert(Op0.getValueType().is64BitVector() &&
4498            Op1.getValueType().is64BitVector() &&
4499            "unexpected types for extended operands to VMULL");
4500     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
4501   }
4502 
4503   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
4504   // isel lowering to take advantage of no-stall back to back vmul + vmla.
4505   //   vmull q0, d4, d6
4506   //   vmlal q0, d5, d6
4507   // is faster than
4508   //   vaddl q0, d4, d5
4509   //   vmovl q1, d6
4510   //   vmul  q0, q0, q1
4511   SDValue N00 = SkipExtension(N0->getOperand(0).getNode(), DAG);
4512   SDValue N01 = SkipExtension(N0->getOperand(1).getNode(), DAG);
4513   EVT Op1VT = Op1.getValueType();
4514   return DAG.getNode(N0->getOpcode(), DL, VT,
4515                      DAG.getNode(NewOpc, DL, VT,
4516                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
4517                      DAG.getNode(NewOpc, DL, VT,
4518                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
4519 }
4520 
4521 static SDValue
4522 LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
4523   // Convert to float
4524   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
4525   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
4526   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
4527   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
4528   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
4529   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
4530   // Get reciprocal estimate.
4531   // float4 recip = vrecpeq_f32(yf);
4532   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4533                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
4534   // Because char has a smaller range than uchar, we can actually get away
4535   // without any newton steps.  This requires that we use a weird bias
4536   // of 0xb000, however (again, this has been exhaustively tested).
4537   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
4538   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
4539   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
4540   Y = DAG.getConstant(0xb000, MVT::i32);
4541   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
4542   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
4543   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
4544   // Convert back to short.
4545   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
4546   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
4547   return X;
4548 }
4549 
4550 static SDValue
4551 LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
4552   SDValue N2;
4553   // Convert to float.
4554   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
4555   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
4556   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
4557   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
4558   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
4559   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
4560 
4561   // Use reciprocal estimate and one refinement step.
4562   // float4 recip = vrecpeq_f32(yf);
4563   // recip *= vrecpsq_f32(yf, recip);
4564   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4565                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
4566   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4567                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
4568                    N1, N2);
4569   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
4570   // Because short has a smaller range than ushort, we can actually get away
4571   // with only a single newton step.  This requires that we use a weird bias
4572   // of 89, however (again, this has been exhaustively tested).
4573   // float4 result = as_float4(as_int4(xf*recip) + 89);
4574   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
4575   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
4576   N1 = DAG.getConstant(89, MVT::i32);
4577   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
4578   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
4579   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
4580   // Convert back to integer and return.
4581   // return vmovn_s32(vcvt_s32_f32(result));
4582   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
4583   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
4584   return N0;
4585 }
4586 
4587 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
4588   EVT VT = Op.getValueType();
4589   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
4590          "unexpected type for custom-lowering ISD::SDIV");
4591 
4592   DebugLoc dl = Op.getDebugLoc();
4593   SDValue N0 = Op.getOperand(0);
4594   SDValue N1 = Op.getOperand(1);
4595   SDValue N2, N3;
4596 
4597   if (VT == MVT::v8i8) {
4598     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
4599     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
4600 
4601     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
4602                      DAG.getIntPtrConstant(4));
4603     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
4604                      DAG.getIntPtrConstant(4));
4605     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
4606                      DAG.getIntPtrConstant(0));
4607     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
4608                      DAG.getIntPtrConstant(0));
4609 
4610     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
4611     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
4612 
4613     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
4614     N0 = LowerCONCAT_VECTORS(N0, DAG);
4615 
4616     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
4617     return N0;
4618   }
4619   return LowerSDIV_v4i16(N0, N1, dl, DAG);
4620 }
4621 
4622 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
4623   EVT VT = Op.getValueType();
4624   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
4625          "unexpected type for custom-lowering ISD::UDIV");
4626 
4627   DebugLoc dl = Op.getDebugLoc();
4628   SDValue N0 = Op.getOperand(0);
4629   SDValue N1 = Op.getOperand(1);
4630   SDValue N2, N3;
4631 
4632   if (VT == MVT::v8i8) {
4633     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
4634     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
4635 
4636     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
4637                      DAG.getIntPtrConstant(4));
4638     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
4639                      DAG.getIntPtrConstant(4));
4640     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
4641                      DAG.getIntPtrConstant(0));
4642     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
4643                      DAG.getIntPtrConstant(0));
4644 
4645     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
4646     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
4647 
4648     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
4649     N0 = LowerCONCAT_VECTORS(N0, DAG);
4650 
4651     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
4652                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
4653                      N0);
4654     return N0;
4655   }
4656 
4657   // v4i16 sdiv ... Convert to float.
4658   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
4659   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
4660   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
4661   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
4662   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
4663   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
4664 
4665   // Use reciprocal estimate and two refinement steps.
4666   // float4 recip = vrecpeq_f32(yf);
4667   // recip *= vrecpsq_f32(yf, recip);
4668   // recip *= vrecpsq_f32(yf, recip);
4669   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4670                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
4671   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4672                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
4673                    N1, N2);
4674   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
4675   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4676                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
4677                    N1, N2);
4678   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
4679   // Simply multiplying by the reciprocal estimate can leave us a few ulps
4680   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
4681   // and that it will never cause us to return an answer too large).
4682   // float4 result = as_float4(as_int4(xf*recip) + 89);
4683   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
4684   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
4685   N1 = DAG.getConstant(2, MVT::i32);
4686   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
4687   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
4688   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
4689   // Convert back to integer and return.
4690   // return vmovn_u32(vcvt_s32_f32(result));
4691   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
4692   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
4693   return N0;
4694 }
4695 
4696 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4697   switch (Op.getOpcode()) {
4698   default: llvm_unreachable("Don't know how to custom lower this!");
4699   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
4700   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
4701   case ISD::GlobalAddress:
4702     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
4703       LowerGlobalAddressELF(Op, DAG);
4704   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
4705   case ISD::SELECT:        return LowerSELECT(Op, DAG);
4706   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
4707   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
4708   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
4709   case ISD::VASTART:       return LowerVASTART(Op, DAG);
4710   case ISD::MEMBARRIER:    return LowerMEMBARRIER(Op, DAG, Subtarget);
4711   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
4712   case ISD::SINT_TO_FP:
4713   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
4714   case ISD::FP_TO_SINT:
4715   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
4716   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
4717   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
4718   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
4719   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
4720   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
4721   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
4722   case ISD::EH_SJLJ_DISPATCHSETUP: return LowerEH_SJLJ_DISPATCHSETUP(Op, DAG);
4723   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
4724                                                                Subtarget);
4725   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
4726   case ISD::SHL:
4727   case ISD::SRL:
4728   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
4729   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
4730   case ISD::SRL_PARTS:
4731   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
4732   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
4733   case ISD::VSETCC:        return LowerVSETCC(Op, DAG);
4734   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
4735   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
4736   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
4737   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
4738   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
4739   case ISD::MUL:           return LowerMUL(Op, DAG);
4740   case ISD::SDIV:          return LowerSDIV(Op, DAG);
4741   case ISD::UDIV:          return LowerUDIV(Op, DAG);
4742   }
4743   return SDValue();
4744 }
4745 
4746 /// ReplaceNodeResults - Replace the results of node with an illegal result
4747 /// type with new values built out of custom code.
4748 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
4749                                            SmallVectorImpl<SDValue>&Results,
4750                                            SelectionDAG &DAG) const {
4751   SDValue Res;
4752   switch (N->getOpcode()) {
4753   default:
4754     llvm_unreachable("Don't know how to custom expand this!");
4755     break;
4756   case ISD::BITCAST:
4757     Res = ExpandBITCAST(N, DAG);
4758     break;
4759   case ISD::SRL:
4760   case ISD::SRA:
4761     Res = Expand64BitShift(N, DAG, Subtarget);
4762     break;
4763   }
4764   if (Res.getNode())
4765     Results.push_back(Res);
4766 }
4767 
4768 //===----------------------------------------------------------------------===//
4769 //                           ARM Scheduler Hooks
4770 //===----------------------------------------------------------------------===//
4771 
4772 MachineBasicBlock *
4773 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
4774                                      MachineBasicBlock *BB,
4775                                      unsigned Size) const {
4776   unsigned dest    = MI->getOperand(0).getReg();
4777   unsigned ptr     = MI->getOperand(1).getReg();
4778   unsigned oldval  = MI->getOperand(2).getReg();
4779   unsigned newval  = MI->getOperand(3).getReg();
4780   unsigned scratch = BB->getParent()->getRegInfo()
4781     .createVirtualRegister(ARM::GPRRegisterClass);
4782   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
4783   DebugLoc dl = MI->getDebugLoc();
4784   bool isThumb2 = Subtarget->isThumb2();
4785 
4786   unsigned ldrOpc, strOpc;
4787   switch (Size) {
4788   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
4789   case 1:
4790     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
4791     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
4792     break;
4793   case 2:
4794     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
4795     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
4796     break;
4797   case 4:
4798     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
4799     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
4800     break;
4801   }
4802 
4803   MachineFunction *MF = BB->getParent();
4804   const BasicBlock *LLVM_BB = BB->getBasicBlock();
4805   MachineFunction::iterator It = BB;
4806   ++It; // insert the new blocks after the current block
4807 
4808   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
4809   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
4810   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
4811   MF->insert(It, loop1MBB);
4812   MF->insert(It, loop2MBB);
4813   MF->insert(It, exitMBB);
4814 
4815   // Transfer the remainder of BB and its successor edges to exitMBB.
4816   exitMBB->splice(exitMBB->begin(), BB,
4817                   llvm::next(MachineBasicBlock::iterator(MI)),
4818                   BB->end());
4819   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
4820 
4821   //  thisMBB:
4822   //   ...
4823   //   fallthrough --> loop1MBB
4824   BB->addSuccessor(loop1MBB);
4825 
4826   // loop1MBB:
4827   //   ldrex dest, [ptr]
4828   //   cmp dest, oldval
4829   //   bne exitMBB
4830   BB = loop1MBB;
4831   AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr));
4832   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
4833                  .addReg(dest).addReg(oldval));
4834   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
4835     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
4836   BB->addSuccessor(loop2MBB);
4837   BB->addSuccessor(exitMBB);
4838 
4839   // loop2MBB:
4840   //   strex scratch, newval, [ptr]
4841   //   cmp scratch, #0
4842   //   bne loop1MBB
4843   BB = loop2MBB;
4844   AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval)
4845                  .addReg(ptr));
4846   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
4847                  .addReg(scratch).addImm(0));
4848   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
4849     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
4850   BB->addSuccessor(loop1MBB);
4851   BB->addSuccessor(exitMBB);
4852 
4853   //  exitMBB:
4854   //   ...
4855   BB = exitMBB;
4856 
4857   MI->eraseFromParent();   // The instruction is gone now.
4858 
4859   return BB;
4860 }
4861 
4862 MachineBasicBlock *
4863 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
4864                                     unsigned Size, unsigned BinOpcode) const {
4865   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
4866   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
4867 
4868   const BasicBlock *LLVM_BB = BB->getBasicBlock();
4869   MachineFunction *MF = BB->getParent();
4870   MachineFunction::iterator It = BB;
4871   ++It;
4872 
4873   unsigned dest = MI->getOperand(0).getReg();
4874   unsigned ptr = MI->getOperand(1).getReg();
4875   unsigned incr = MI->getOperand(2).getReg();
4876   DebugLoc dl = MI->getDebugLoc();
4877 
4878   bool isThumb2 = Subtarget->isThumb2();
4879   unsigned ldrOpc, strOpc;
4880   switch (Size) {
4881   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
4882   case 1:
4883     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
4884     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
4885     break;
4886   case 2:
4887     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
4888     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
4889     break;
4890   case 4:
4891     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
4892     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
4893     break;
4894   }
4895 
4896   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
4897   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
4898   MF->insert(It, loopMBB);
4899   MF->insert(It, exitMBB);
4900 
4901   // Transfer the remainder of BB and its successor edges to exitMBB.
4902   exitMBB->splice(exitMBB->begin(), BB,
4903                   llvm::next(MachineBasicBlock::iterator(MI)),
4904                   BB->end());
4905   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
4906 
4907   MachineRegisterInfo &RegInfo = MF->getRegInfo();
4908   unsigned scratch = RegInfo.createVirtualRegister(ARM::GPRRegisterClass);
4909   unsigned scratch2 = (!BinOpcode) ? incr :
4910     RegInfo.createVirtualRegister(ARM::GPRRegisterClass);
4911 
4912   //  thisMBB:
4913   //   ...
4914   //   fallthrough --> loopMBB
4915   BB->addSuccessor(loopMBB);
4916 
4917   //  loopMBB:
4918   //   ldrex dest, ptr
4919   //   <binop> scratch2, dest, incr
4920   //   strex scratch, scratch2, ptr
4921   //   cmp scratch, #0
4922   //   bne- loopMBB
4923   //   fallthrough --> exitMBB
4924   BB = loopMBB;
4925   AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr));
4926   if (BinOpcode) {
4927     // operand order needs to go the other way for NAND
4928     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
4929       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
4930                      addReg(incr).addReg(dest)).addReg(0);
4931     else
4932       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
4933                      addReg(dest).addReg(incr)).addReg(0);
4934   }
4935 
4936   AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2)
4937                  .addReg(ptr));
4938   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
4939                  .addReg(scratch).addImm(0));
4940   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
4941     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
4942 
4943   BB->addSuccessor(loopMBB);
4944   BB->addSuccessor(exitMBB);
4945 
4946   //  exitMBB:
4947   //   ...
4948   BB = exitMBB;
4949 
4950   MI->eraseFromParent();   // The instruction is gone now.
4951 
4952   return BB;
4953 }
4954 
4955 static
4956 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
4957   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
4958        E = MBB->succ_end(); I != E; ++I)
4959     if (*I != Succ)
4960       return *I;
4961   llvm_unreachable("Expecting a BB with two successors!");
4962 }
4963 
4964 MachineBasicBlock *
4965 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
4966                                                MachineBasicBlock *BB) const {
4967   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
4968   DebugLoc dl = MI->getDebugLoc();
4969   bool isThumb2 = Subtarget->isThumb2();
4970   switch (MI->getOpcode()) {
4971   default:
4972     MI->dump();
4973     llvm_unreachable("Unexpected instr type to insert");
4974 
4975   case ARM::ATOMIC_LOAD_ADD_I8:
4976      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
4977   case ARM::ATOMIC_LOAD_ADD_I16:
4978      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
4979   case ARM::ATOMIC_LOAD_ADD_I32:
4980      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
4981 
4982   case ARM::ATOMIC_LOAD_AND_I8:
4983      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
4984   case ARM::ATOMIC_LOAD_AND_I16:
4985      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
4986   case ARM::ATOMIC_LOAD_AND_I32:
4987      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
4988 
4989   case ARM::ATOMIC_LOAD_OR_I8:
4990      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
4991   case ARM::ATOMIC_LOAD_OR_I16:
4992      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
4993   case ARM::ATOMIC_LOAD_OR_I32:
4994      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
4995 
4996   case ARM::ATOMIC_LOAD_XOR_I8:
4997      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
4998   case ARM::ATOMIC_LOAD_XOR_I16:
4999      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
5000   case ARM::ATOMIC_LOAD_XOR_I32:
5001      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
5002 
5003   case ARM::ATOMIC_LOAD_NAND_I8:
5004      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
5005   case ARM::ATOMIC_LOAD_NAND_I16:
5006      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
5007   case ARM::ATOMIC_LOAD_NAND_I32:
5008      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
5009 
5010   case ARM::ATOMIC_LOAD_SUB_I8:
5011      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
5012   case ARM::ATOMIC_LOAD_SUB_I16:
5013      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
5014   case ARM::ATOMIC_LOAD_SUB_I32:
5015      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
5016 
5017   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
5018   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
5019   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
5020 
5021   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
5022   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
5023   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
5024 
5025   case ARM::ADCSSri:
5026   case ARM::ADCSSrr:
5027   case ARM::ADCSSrs:
5028   case ARM::SBCSSri:
5029   case ARM::SBCSSrr:
5030   case ARM::SBCSSrs:
5031   case ARM::RSBSri:
5032   case ARM::RSBSrr:
5033   case ARM::RSBSrs:
5034   case ARM::RSCSri:
5035   case ARM::RSCSrs: {
5036     unsigned OldOpc = MI->getOpcode();
5037     unsigned Opc = 0;
5038     switch (OldOpc) {
5039       case ARM::ADCSSrr:
5040         Opc = ARM::ADCrr;
5041         break;
5042       case ARM::ADCSSri:
5043         Opc = ARM::ADCri;
5044         break;
5045       case ARM::ADCSSrs:
5046         Opc = ARM::ADCrs;
5047         break;
5048       case ARM::SBCSSrr:
5049         Opc = ARM::SBCrr;
5050         break;
5051       case ARM::SBCSSri:
5052         Opc = ARM::SBCri;
5053         break;
5054       case ARM::SBCSSrs:
5055         Opc = ARM::SBCrs;
5056         break;
5057       case ARM::RSBSri:
5058         Opc = ARM::RSBri;
5059         break;
5060       case ARM::RSBSrr:
5061         Opc = ARM::RSBrr;
5062         break;
5063       case ARM::RSBSrs:
5064         Opc = ARM::RSBrs;
5065         break;
5066       case ARM::RSCSri:
5067         Opc = ARM::RSCri;
5068         break;
5069       case ARM::RSCSrs:
5070         Opc = ARM::RSCrs;
5071         break;
5072       default:
5073         llvm_unreachable("Unknown opcode?");
5074     }
5075 
5076     MachineInstrBuilder MIB =
5077       BuildMI(*BB, MI, MI->getDebugLoc(), TII->get(Opc));
5078     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
5079       MIB.addOperand(MI->getOperand(i));
5080     AddDefaultPred(MIB);
5081     MIB.addReg(ARM::CPSR, RegState::Define); // S bit
5082     MI->eraseFromParent();
5083     return BB;
5084   }
5085 
5086 
5087   case ARM::tMOVCCr_pseudo: {
5088     // To "insert" a SELECT_CC instruction, we actually have to insert the
5089     // diamond control-flow pattern.  The incoming instruction knows the
5090     // destination vreg to set, the condition code register to branch on, the
5091     // true/false values to select between, and a branch opcode to use.
5092     const BasicBlock *LLVM_BB = BB->getBasicBlock();
5093     MachineFunction::iterator It = BB;
5094     ++It;
5095 
5096     //  thisMBB:
5097     //  ...
5098     //   TrueVal = ...
5099     //   cmpTY ccX, r1, r2
5100     //   bCC copy1MBB
5101     //   fallthrough --> copy0MBB
5102     MachineBasicBlock *thisMBB  = BB;
5103     MachineFunction *F = BB->getParent();
5104     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
5105     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
5106     F->insert(It, copy0MBB);
5107     F->insert(It, sinkMBB);
5108 
5109     // Transfer the remainder of BB and its successor edges to sinkMBB.
5110     sinkMBB->splice(sinkMBB->begin(), BB,
5111                     llvm::next(MachineBasicBlock::iterator(MI)),
5112                     BB->end());
5113     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
5114 
5115     BB->addSuccessor(copy0MBB);
5116     BB->addSuccessor(sinkMBB);
5117 
5118     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
5119       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
5120 
5121     //  copy0MBB:
5122     //   %FalseValue = ...
5123     //   # fallthrough to sinkMBB
5124     BB = copy0MBB;
5125 
5126     // Update machine-CFG edges
5127     BB->addSuccessor(sinkMBB);
5128 
5129     //  sinkMBB:
5130     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
5131     //  ...
5132     BB = sinkMBB;
5133     BuildMI(*BB, BB->begin(), dl,
5134             TII->get(ARM::PHI), MI->getOperand(0).getReg())
5135       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
5136       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
5137 
5138     MI->eraseFromParent();   // The pseudo instruction is gone now.
5139     return BB;
5140   }
5141 
5142   case ARM::BCCi64:
5143   case ARM::BCCZi64: {
5144     // If there is an unconditional branch to the other successor, remove it.
5145     BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
5146 
5147     // Compare both parts that make up the double comparison separately for
5148     // equality.
5149     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
5150 
5151     unsigned LHS1 = MI->getOperand(1).getReg();
5152     unsigned LHS2 = MI->getOperand(2).getReg();
5153     if (RHSisZero) {
5154       AddDefaultPred(BuildMI(BB, dl,
5155                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5156                      .addReg(LHS1).addImm(0));
5157       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5158         .addReg(LHS2).addImm(0)
5159         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
5160     } else {
5161       unsigned RHS1 = MI->getOperand(3).getReg();
5162       unsigned RHS2 = MI->getOperand(4).getReg();
5163       AddDefaultPred(BuildMI(BB, dl,
5164                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5165                      .addReg(LHS1).addReg(RHS1));
5166       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5167         .addReg(LHS2).addReg(RHS2)
5168         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
5169     }
5170 
5171     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
5172     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
5173     if (MI->getOperand(0).getImm() == ARMCC::NE)
5174       std::swap(destMBB, exitMBB);
5175 
5176     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5177       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
5178     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2B : ARM::B))
5179       .addMBB(exitMBB);
5180 
5181     MI->eraseFromParent();   // The pseudo instruction is gone now.
5182     return BB;
5183   }
5184   }
5185 }
5186 
5187 //===----------------------------------------------------------------------===//
5188 //                           ARM Optimization Hooks
5189 //===----------------------------------------------------------------------===//
5190 
5191 static
5192 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
5193                             TargetLowering::DAGCombinerInfo &DCI) {
5194   SelectionDAG &DAG = DCI.DAG;
5195   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5196   EVT VT = N->getValueType(0);
5197   unsigned Opc = N->getOpcode();
5198   bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
5199   SDValue LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
5200   SDValue RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
5201   ISD::CondCode CC = ISD::SETCC_INVALID;
5202 
5203   if (isSlctCC) {
5204     CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
5205   } else {
5206     SDValue CCOp = Slct.getOperand(0);
5207     if (CCOp.getOpcode() == ISD::SETCC)
5208       CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
5209   }
5210 
5211   bool DoXform = false;
5212   bool InvCC = false;
5213   assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
5214           "Bad input!");
5215 
5216   if (LHS.getOpcode() == ISD::Constant &&
5217       cast<ConstantSDNode>(LHS)->isNullValue()) {
5218     DoXform = true;
5219   } else if (CC != ISD::SETCC_INVALID &&
5220              RHS.getOpcode() == ISD::Constant &&
5221              cast<ConstantSDNode>(RHS)->isNullValue()) {
5222     std::swap(LHS, RHS);
5223     SDValue Op0 = Slct.getOperand(0);
5224     EVT OpVT = isSlctCC ? Op0.getValueType() :
5225                           Op0.getOperand(0).getValueType();
5226     bool isInt = OpVT.isInteger();
5227     CC = ISD::getSetCCInverse(CC, isInt);
5228 
5229     if (!TLI.isCondCodeLegal(CC, OpVT))
5230       return SDValue();         // Inverse operator isn't legal.
5231 
5232     DoXform = true;
5233     InvCC = true;
5234   }
5235 
5236   if (DoXform) {
5237     SDValue Result = DAG.getNode(Opc, RHS.getDebugLoc(), VT, OtherOp, RHS);
5238     if (isSlctCC)
5239       return DAG.getSelectCC(N->getDebugLoc(), OtherOp, Result,
5240                              Slct.getOperand(0), Slct.getOperand(1), CC);
5241     SDValue CCOp = Slct.getOperand(0);
5242     if (InvCC)
5243       CCOp = DAG.getSetCC(Slct.getDebugLoc(), CCOp.getValueType(),
5244                           CCOp.getOperand(0), CCOp.getOperand(1), CC);
5245     return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
5246                        CCOp, OtherOp, Result);
5247   }
5248   return SDValue();
5249 }
5250 
5251 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
5252 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
5253 /// called with the default operands, and if that fails, with commuted
5254 /// operands.
5255 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
5256                                          TargetLowering::DAGCombinerInfo &DCI) {
5257   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
5258   if (N0.getOpcode() == ISD::SELECT && N0.getNode()->hasOneUse()) {
5259     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
5260     if (Result.getNode()) return Result;
5261   }
5262   return SDValue();
5263 }
5264 
5265 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
5266 ///
5267 static SDValue PerformADDCombine(SDNode *N,
5268                                  TargetLowering::DAGCombinerInfo &DCI) {
5269   SDValue N0 = N->getOperand(0);
5270   SDValue N1 = N->getOperand(1);
5271 
5272   // First try with the default operand order.
5273   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI);
5274   if (Result.getNode())
5275     return Result;
5276 
5277   // If that didn't work, try again with the operands commuted.
5278   return PerformADDCombineWithOperands(N, N1, N0, DCI);
5279 }
5280 
5281 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
5282 ///
5283 static SDValue PerformSUBCombine(SDNode *N,
5284                                  TargetLowering::DAGCombinerInfo &DCI) {
5285   SDValue N0 = N->getOperand(0);
5286   SDValue N1 = N->getOperand(1);
5287 
5288   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
5289   if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
5290     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
5291     if (Result.getNode()) return Result;
5292   }
5293 
5294   return SDValue();
5295 }
5296 
5297 /// PerformVMULCombine
5298 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
5299 /// special multiplier accumulator forwarding.
5300 ///   vmul d3, d0, d2
5301 ///   vmla d3, d1, d2
5302 /// is faster than
5303 ///   vadd d3, d0, d1
5304 ///   vmul d3, d3, d2
5305 static SDValue PerformVMULCombine(SDNode *N,
5306                                   TargetLowering::DAGCombinerInfo &DCI,
5307                                   const ARMSubtarget *Subtarget) {
5308   if (!Subtarget->hasVMLxForwarding())
5309     return SDValue();
5310 
5311   SelectionDAG &DAG = DCI.DAG;
5312   SDValue N0 = N->getOperand(0);
5313   SDValue N1 = N->getOperand(1);
5314   unsigned Opcode = N0.getOpcode();
5315   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
5316       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
5317     Opcode = N0.getOpcode();
5318     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
5319         Opcode != ISD::FADD && Opcode != ISD::FSUB)
5320       return SDValue();
5321     std::swap(N0, N1);
5322   }
5323 
5324   EVT VT = N->getValueType(0);
5325   DebugLoc DL = N->getDebugLoc();
5326   SDValue N00 = N0->getOperand(0);
5327   SDValue N01 = N0->getOperand(1);
5328   return DAG.getNode(Opcode, DL, VT,
5329                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
5330                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
5331 }
5332 
5333 static SDValue PerformMULCombine(SDNode *N,
5334                                  TargetLowering::DAGCombinerInfo &DCI,
5335                                  const ARMSubtarget *Subtarget) {
5336   SelectionDAG &DAG = DCI.DAG;
5337 
5338   if (Subtarget->isThumb1Only())
5339     return SDValue();
5340 
5341   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
5342     return SDValue();
5343 
5344   EVT VT = N->getValueType(0);
5345   if (VT.is64BitVector() || VT.is128BitVector())
5346     return PerformVMULCombine(N, DCI, Subtarget);
5347   if (VT != MVT::i32)
5348     return SDValue();
5349 
5350   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
5351   if (!C)
5352     return SDValue();
5353 
5354   uint64_t MulAmt = C->getZExtValue();
5355   unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
5356   ShiftAmt = ShiftAmt & (32 - 1);
5357   SDValue V = N->getOperand(0);
5358   DebugLoc DL = N->getDebugLoc();
5359 
5360   SDValue Res;
5361   MulAmt >>= ShiftAmt;
5362   if (isPowerOf2_32(MulAmt - 1)) {
5363     // (mul x, 2^N + 1) => (add (shl x, N), x)
5364     Res = DAG.getNode(ISD::ADD, DL, VT,
5365                       V, DAG.getNode(ISD::SHL, DL, VT,
5366                                      V, DAG.getConstant(Log2_32(MulAmt-1),
5367                                                         MVT::i32)));
5368   } else if (isPowerOf2_32(MulAmt + 1)) {
5369     // (mul x, 2^N - 1) => (sub (shl x, N), x)
5370     Res = DAG.getNode(ISD::SUB, DL, VT,
5371                       DAG.getNode(ISD::SHL, DL, VT,
5372                                   V, DAG.getConstant(Log2_32(MulAmt+1),
5373                                                      MVT::i32)),
5374                                                      V);
5375   } else
5376     return SDValue();
5377 
5378   if (ShiftAmt != 0)
5379     Res = DAG.getNode(ISD::SHL, DL, VT, Res,
5380                       DAG.getConstant(ShiftAmt, MVT::i32));
5381 
5382   // Do not add new nodes to DAG combiner worklist.
5383   DCI.CombineTo(N, Res, false);
5384   return SDValue();
5385 }
5386 
5387 static SDValue PerformANDCombine(SDNode *N,
5388                                 TargetLowering::DAGCombinerInfo &DCI) {
5389 
5390   // Attempt to use immediate-form VBIC
5391   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
5392   DebugLoc dl = N->getDebugLoc();
5393   EVT VT = N->getValueType(0);
5394   SelectionDAG &DAG = DCI.DAG;
5395 
5396   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
5397     return SDValue();
5398 
5399   APInt SplatBits, SplatUndef;
5400   unsigned SplatBitSize;
5401   bool HasAnyUndefs;
5402   if (BVN &&
5403       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5404     if (SplatBitSize <= 64) {
5405       EVT VbicVT;
5406       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
5407                                       SplatUndef.getZExtValue(), SplatBitSize,
5408                                       DAG, VbicVT, VT.is128BitVector(),
5409                                       OtherModImm);
5410       if (Val.getNode()) {
5411         SDValue Input =
5412           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
5413         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
5414         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
5415       }
5416     }
5417   }
5418 
5419   return SDValue();
5420 }
5421 
5422 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
5423 static SDValue PerformORCombine(SDNode *N,
5424                                 TargetLowering::DAGCombinerInfo &DCI,
5425                                 const ARMSubtarget *Subtarget) {
5426   // Attempt to use immediate-form VORR
5427   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
5428   DebugLoc dl = N->getDebugLoc();
5429   EVT VT = N->getValueType(0);
5430   SelectionDAG &DAG = DCI.DAG;
5431 
5432   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
5433     return SDValue();
5434 
5435   APInt SplatBits, SplatUndef;
5436   unsigned SplatBitSize;
5437   bool HasAnyUndefs;
5438   if (BVN && Subtarget->hasNEON() &&
5439       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5440     if (SplatBitSize <= 64) {
5441       EVT VorrVT;
5442       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5443                                       SplatUndef.getZExtValue(), SplatBitSize,
5444                                       DAG, VorrVT, VT.is128BitVector(),
5445                                       OtherModImm);
5446       if (Val.getNode()) {
5447         SDValue Input =
5448           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
5449         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
5450         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
5451       }
5452     }
5453   }
5454 
5455   SDValue N0 = N->getOperand(0);
5456   if (N0.getOpcode() != ISD::AND)
5457     return SDValue();
5458   SDValue N1 = N->getOperand(1);
5459 
5460   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
5461   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
5462       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
5463     APInt SplatUndef;
5464     unsigned SplatBitSize;
5465     bool HasAnyUndefs;
5466 
5467     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
5468     APInt SplatBits0;
5469     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
5470                                   HasAnyUndefs) && !HasAnyUndefs) {
5471       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
5472       APInt SplatBits1;
5473       if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
5474                                     HasAnyUndefs) && !HasAnyUndefs &&
5475           SplatBits0 == ~SplatBits1) {
5476         // Canonicalize the vector type to make instruction selection simpler.
5477         EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
5478         SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
5479                                      N0->getOperand(1), N0->getOperand(0),
5480                                      N1->getOperand(0));
5481         return DAG.getNode(ISD::BITCAST, dl, VT, Result);
5482       }
5483     }
5484   }
5485 
5486   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
5487   // reasonable.
5488 
5489   // BFI is only available on V6T2+
5490   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
5491     return SDValue();
5492 
5493   DebugLoc DL = N->getDebugLoc();
5494   // 1) or (and A, mask), val => ARMbfi A, val, mask
5495   //      iff (val & mask) == val
5496   //
5497   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
5498   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
5499   //          && mask == ~mask2
5500   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
5501   //          && ~mask == mask2
5502   //  (i.e., copy a bitfield value into another bitfield of the same width)
5503 
5504   if (VT != MVT::i32)
5505     return SDValue();
5506 
5507   SDValue N00 = N0.getOperand(0);
5508 
5509   // The value and the mask need to be constants so we can verify this is
5510   // actually a bitfield set. If the mask is 0xffff, we can do better
5511   // via a movt instruction, so don't use BFI in that case.
5512   SDValue MaskOp = N0.getOperand(1);
5513   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
5514   if (!MaskC)
5515     return SDValue();
5516   unsigned Mask = MaskC->getZExtValue();
5517   if (Mask == 0xffff)
5518     return SDValue();
5519   SDValue Res;
5520   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
5521   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
5522   if (N1C) {
5523     unsigned Val = N1C->getZExtValue();
5524     if ((Val & ~Mask) != Val)
5525       return SDValue();
5526 
5527     if (ARM::isBitFieldInvertedMask(Mask)) {
5528       Val >>= CountTrailingZeros_32(~Mask);
5529 
5530       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
5531                         DAG.getConstant(Val, MVT::i32),
5532                         DAG.getConstant(Mask, MVT::i32));
5533 
5534       // Do not add new nodes to DAG combiner worklist.
5535       DCI.CombineTo(N, Res, false);
5536       return SDValue();
5537     }
5538   } else if (N1.getOpcode() == ISD::AND) {
5539     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
5540     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
5541     if (!N11C)
5542       return SDValue();
5543     unsigned Mask2 = N11C->getZExtValue();
5544 
5545     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
5546     // as is to match.
5547     if (ARM::isBitFieldInvertedMask(Mask) &&
5548         (Mask == ~Mask2)) {
5549       // The pack halfword instruction works better for masks that fit it,
5550       // so use that when it's available.
5551       if (Subtarget->hasT2ExtractPack() &&
5552           (Mask == 0xffff || Mask == 0xffff0000))
5553         return SDValue();
5554       // 2a
5555       unsigned amt = CountTrailingZeros_32(Mask2);
5556       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
5557                         DAG.getConstant(amt, MVT::i32));
5558       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
5559                         DAG.getConstant(Mask, MVT::i32));
5560       // Do not add new nodes to DAG combiner worklist.
5561       DCI.CombineTo(N, Res, false);
5562       return SDValue();
5563     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
5564                (~Mask == Mask2)) {
5565       // The pack halfword instruction works better for masks that fit it,
5566       // so use that when it's available.
5567       if (Subtarget->hasT2ExtractPack() &&
5568           (Mask2 == 0xffff || Mask2 == 0xffff0000))
5569         return SDValue();
5570       // 2b
5571       unsigned lsb = CountTrailingZeros_32(Mask);
5572       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
5573                         DAG.getConstant(lsb, MVT::i32));
5574       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
5575                         DAG.getConstant(Mask2, MVT::i32));
5576       // Do not add new nodes to DAG combiner worklist.
5577       DCI.CombineTo(N, Res, false);
5578       return SDValue();
5579     }
5580   }
5581 
5582   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
5583       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
5584       ARM::isBitFieldInvertedMask(~Mask)) {
5585     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
5586     // where lsb(mask) == #shamt and masked bits of B are known zero.
5587     SDValue ShAmt = N00.getOperand(1);
5588     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5589     unsigned LSB = CountTrailingZeros_32(Mask);
5590     if (ShAmtC != LSB)
5591       return SDValue();
5592 
5593     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
5594                       DAG.getConstant(~Mask, MVT::i32));
5595 
5596     // Do not add new nodes to DAG combiner worklist.
5597     DCI.CombineTo(N, Res, false);
5598   }
5599 
5600   return SDValue();
5601 }
5602 
5603 /// PerformBFICombine - (bfi A, (and B, C1), C2) -> (bfi A, B, C2) iff
5604 /// C1 & C2 == C1.
5605 static SDValue PerformBFICombine(SDNode *N,
5606                                  TargetLowering::DAGCombinerInfo &DCI) {
5607   SDValue N1 = N->getOperand(1);
5608   if (N1.getOpcode() == ISD::AND) {
5609     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
5610     if (!N11C)
5611       return SDValue();
5612     unsigned Mask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
5613     unsigned Mask2 = N11C->getZExtValue();
5614     if ((Mask & Mask2) == Mask2)
5615       return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
5616                              N->getOperand(0), N1.getOperand(0),
5617                              N->getOperand(2));
5618   }
5619   return SDValue();
5620 }
5621 
5622 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
5623 /// ARMISD::VMOVRRD.
5624 static SDValue PerformVMOVRRDCombine(SDNode *N,
5625                                      TargetLowering::DAGCombinerInfo &DCI) {
5626   // vmovrrd(vmovdrr x, y) -> x,y
5627   SDValue InDouble = N->getOperand(0);
5628   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
5629     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
5630 
5631   // vmovrrd(load f64) -> (load i32), (load i32)
5632   SDNode *InNode = InDouble.getNode();
5633   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
5634       InNode->getValueType(0) == MVT::f64 &&
5635       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
5636       !cast<LoadSDNode>(InNode)->isVolatile()) {
5637     // TODO: Should this be done for non-FrameIndex operands?
5638     LoadSDNode *LD = cast<LoadSDNode>(InNode);
5639 
5640     SelectionDAG &DAG = DCI.DAG;
5641     DebugLoc DL = LD->getDebugLoc();
5642     SDValue BasePtr = LD->getBasePtr();
5643     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
5644                                  LD->getPointerInfo(), LD->isVolatile(),
5645                                  LD->isNonTemporal(), LD->getAlignment());
5646 
5647     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
5648                                     DAG.getConstant(4, MVT::i32));
5649     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
5650                                  LD->getPointerInfo(), LD->isVolatile(),
5651                                  LD->isNonTemporal(),
5652                                  std::min(4U, LD->getAlignment() / 2));
5653 
5654     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
5655     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
5656     DCI.RemoveFromWorklist(LD);
5657     DAG.DeleteNode(LD);
5658     return Result;
5659   }
5660 
5661   return SDValue();
5662 }
5663 
5664 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
5665 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
5666 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
5667   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
5668   SDValue Op0 = N->getOperand(0);
5669   SDValue Op1 = N->getOperand(1);
5670   if (Op0.getOpcode() == ISD::BITCAST)
5671     Op0 = Op0.getOperand(0);
5672   if (Op1.getOpcode() == ISD::BITCAST)
5673     Op1 = Op1.getOperand(0);
5674   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
5675       Op0.getNode() == Op1.getNode() &&
5676       Op0.getResNo() == 0 && Op1.getResNo() == 1)
5677     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
5678                        N->getValueType(0), Op0.getOperand(0));
5679   return SDValue();
5680 }
5681 
5682 /// PerformSTORECombine - Target-specific dag combine xforms for
5683 /// ISD::STORE.
5684 static SDValue PerformSTORECombine(SDNode *N,
5685                                    TargetLowering::DAGCombinerInfo &DCI) {
5686   // Bitcast an i64 store extracted from a vector to f64.
5687   // Otherwise, the i64 value will be legalized to a pair of i32 values.
5688   StoreSDNode *St = cast<StoreSDNode>(N);
5689   SDValue StVal = St->getValue();
5690   if (!ISD::isNormalStore(St) || St->isVolatile())
5691     return SDValue();
5692 
5693   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
5694       StVal.getNode()->hasOneUse() && !St->isVolatile()) {
5695     SelectionDAG  &DAG = DCI.DAG;
5696     DebugLoc DL = St->getDebugLoc();
5697     SDValue BasePtr = St->getBasePtr();
5698     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
5699                                   StVal.getNode()->getOperand(0), BasePtr,
5700                                   St->getPointerInfo(), St->isVolatile(),
5701                                   St->isNonTemporal(), St->getAlignment());
5702 
5703     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
5704                                     DAG.getConstant(4, MVT::i32));
5705     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
5706                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
5707                         St->isNonTemporal(),
5708                         std::min(4U, St->getAlignment() / 2));
5709   }
5710 
5711   if (StVal.getValueType() != MVT::i64 ||
5712       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5713     return SDValue();
5714 
5715   SelectionDAG &DAG = DCI.DAG;
5716   DebugLoc dl = StVal.getDebugLoc();
5717   SDValue IntVec = StVal.getOperand(0);
5718   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
5719                                  IntVec.getValueType().getVectorNumElements());
5720   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
5721   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5722                                Vec, StVal.getOperand(1));
5723   dl = N->getDebugLoc();
5724   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
5725   // Make the DAGCombiner fold the bitcasts.
5726   DCI.AddToWorklist(Vec.getNode());
5727   DCI.AddToWorklist(ExtElt.getNode());
5728   DCI.AddToWorklist(V.getNode());
5729   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
5730                       St->getPointerInfo(), St->isVolatile(),
5731                       St->isNonTemporal(), St->getAlignment(),
5732                       St->getTBAAInfo());
5733 }
5734 
5735 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
5736 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
5737 /// i64 vector to have f64 elements, since the value can then be loaded
5738 /// directly into a VFP register.
5739 static bool hasNormalLoadOperand(SDNode *N) {
5740   unsigned NumElts = N->getValueType(0).getVectorNumElements();
5741   for (unsigned i = 0; i < NumElts; ++i) {
5742     SDNode *Elt = N->getOperand(i).getNode();
5743     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
5744       return true;
5745   }
5746   return false;
5747 }
5748 
5749 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
5750 /// ISD::BUILD_VECTOR.
5751 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
5752                                           TargetLowering::DAGCombinerInfo &DCI){
5753   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
5754   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
5755   // into a pair of GPRs, which is fine when the value is used as a scalar,
5756   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
5757   SelectionDAG &DAG = DCI.DAG;
5758   if (N->getNumOperands() == 2) {
5759     SDValue RV = PerformVMOVDRRCombine(N, DAG);
5760     if (RV.getNode())
5761       return RV;
5762   }
5763 
5764   // Load i64 elements as f64 values so that type legalization does not split
5765   // them up into i32 values.
5766   EVT VT = N->getValueType(0);
5767   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
5768     return SDValue();
5769   DebugLoc dl = N->getDebugLoc();
5770   SmallVector<SDValue, 8> Ops;
5771   unsigned NumElts = VT.getVectorNumElements();
5772   for (unsigned i = 0; i < NumElts; ++i) {
5773     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
5774     Ops.push_back(V);
5775     // Make the DAGCombiner fold the bitcast.
5776     DCI.AddToWorklist(V.getNode());
5777   }
5778   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
5779   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
5780   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
5781 }
5782 
5783 /// PerformInsertEltCombine - Target-specific dag combine xforms for
5784 /// ISD::INSERT_VECTOR_ELT.
5785 static SDValue PerformInsertEltCombine(SDNode *N,
5786                                        TargetLowering::DAGCombinerInfo &DCI) {
5787   // Bitcast an i64 load inserted into a vector to f64.
5788   // Otherwise, the i64 value will be legalized to a pair of i32 values.
5789   EVT VT = N->getValueType(0);
5790   SDNode *Elt = N->getOperand(1).getNode();
5791   if (VT.getVectorElementType() != MVT::i64 ||
5792       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
5793     return SDValue();
5794 
5795   SelectionDAG &DAG = DCI.DAG;
5796   DebugLoc dl = N->getDebugLoc();
5797   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
5798                                  VT.getVectorNumElements());
5799   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
5800   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
5801   // Make the DAGCombiner fold the bitcasts.
5802   DCI.AddToWorklist(Vec.getNode());
5803   DCI.AddToWorklist(V.getNode());
5804   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
5805                                Vec, V, N->getOperand(2));
5806   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
5807 }
5808 
5809 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
5810 /// ISD::VECTOR_SHUFFLE.
5811 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
5812   // The LLVM shufflevector instruction does not require the shuffle mask
5813   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
5814   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
5815   // operands do not match the mask length, they are extended by concatenating
5816   // them with undef vectors.  That is probably the right thing for other
5817   // targets, but for NEON it is better to concatenate two double-register
5818   // size vector operands into a single quad-register size vector.  Do that
5819   // transformation here:
5820   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
5821   //   shuffle(concat(v1, v2), undef)
5822   SDValue Op0 = N->getOperand(0);
5823   SDValue Op1 = N->getOperand(1);
5824   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
5825       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
5826       Op0.getNumOperands() != 2 ||
5827       Op1.getNumOperands() != 2)
5828     return SDValue();
5829   SDValue Concat0Op1 = Op0.getOperand(1);
5830   SDValue Concat1Op1 = Op1.getOperand(1);
5831   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
5832       Concat1Op1.getOpcode() != ISD::UNDEF)
5833     return SDValue();
5834   // Skip the transformation if any of the types are illegal.
5835   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5836   EVT VT = N->getValueType(0);
5837   if (!TLI.isTypeLegal(VT) ||
5838       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
5839       !TLI.isTypeLegal(Concat1Op1.getValueType()))
5840     return SDValue();
5841 
5842   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
5843                                   Op0.getOperand(0), Op1.getOperand(0));
5844   // Translate the shuffle mask.
5845   SmallVector<int, 16> NewMask;
5846   unsigned NumElts = VT.getVectorNumElements();
5847   unsigned HalfElts = NumElts/2;
5848   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
5849   for (unsigned n = 0; n < NumElts; ++n) {
5850     int MaskElt = SVN->getMaskElt(n);
5851     int NewElt = -1;
5852     if (MaskElt < (int)HalfElts)
5853       NewElt = MaskElt;
5854     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
5855       NewElt = HalfElts + MaskElt - NumElts;
5856     NewMask.push_back(NewElt);
5857   }
5858   return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
5859                               DAG.getUNDEF(VT), NewMask.data());
5860 }
5861 
5862 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
5863 /// NEON load/store intrinsics to merge base address updates.
5864 static SDValue CombineBaseUpdate(SDNode *N,
5865                                  TargetLowering::DAGCombinerInfo &DCI) {
5866   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
5867     return SDValue();
5868 
5869   SelectionDAG &DAG = DCI.DAG;
5870   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
5871                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
5872   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
5873   SDValue Addr = N->getOperand(AddrOpIdx);
5874 
5875   // Search for a use of the address operand that is an increment.
5876   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
5877          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
5878     SDNode *User = *UI;
5879     if (User->getOpcode() != ISD::ADD ||
5880         UI.getUse().getResNo() != Addr.getResNo())
5881       continue;
5882 
5883     // Check that the add is independent of the load/store.  Otherwise, folding
5884     // it would create a cycle.
5885     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
5886       continue;
5887 
5888     // Find the new opcode for the updating load/store.
5889     bool isLoad = true;
5890     bool isLaneOp = false;
5891     unsigned NewOpc = 0;
5892     unsigned NumVecs = 0;
5893     if (isIntrinsic) {
5894       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
5895       switch (IntNo) {
5896       default: assert(0 && "unexpected intrinsic for Neon base update");
5897       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
5898         NumVecs = 1; break;
5899       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
5900         NumVecs = 2; break;
5901       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
5902         NumVecs = 3; break;
5903       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
5904         NumVecs = 4; break;
5905       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
5906         NumVecs = 2; isLaneOp = true; break;
5907       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
5908         NumVecs = 3; isLaneOp = true; break;
5909       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
5910         NumVecs = 4; isLaneOp = true; break;
5911       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
5912         NumVecs = 1; isLoad = false; break;
5913       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
5914         NumVecs = 2; isLoad = false; break;
5915       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
5916         NumVecs = 3; isLoad = false; break;
5917       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
5918         NumVecs = 4; isLoad = false; break;
5919       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
5920         NumVecs = 2; isLoad = false; isLaneOp = true; break;
5921       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
5922         NumVecs = 3; isLoad = false; isLaneOp = true; break;
5923       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
5924         NumVecs = 4; isLoad = false; isLaneOp = true; break;
5925       }
5926     } else {
5927       isLaneOp = true;
5928       switch (N->getOpcode()) {
5929       default: assert(0 && "unexpected opcode for Neon base update");
5930       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
5931       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
5932       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
5933       }
5934     }
5935 
5936     // Find the size of memory referenced by the load/store.
5937     EVT VecTy;
5938     if (isLoad)
5939       VecTy = N->getValueType(0);
5940     else
5941       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
5942     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
5943     if (isLaneOp)
5944       NumBytes /= VecTy.getVectorNumElements();
5945 
5946     // If the increment is a constant, it must match the memory ref size.
5947     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
5948     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
5949       uint64_t IncVal = CInc->getZExtValue();
5950       if (IncVal != NumBytes)
5951         continue;
5952     } else if (NumBytes >= 3 * 16) {
5953       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
5954       // separate instructions that make it harder to use a non-constant update.
5955       continue;
5956     }
5957 
5958     // Create the new updating load/store node.
5959     EVT Tys[6];
5960     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
5961     unsigned n;
5962     for (n = 0; n < NumResultVecs; ++n)
5963       Tys[n] = VecTy;
5964     Tys[n++] = MVT::i32;
5965     Tys[n] = MVT::Other;
5966     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
5967     SmallVector<SDValue, 8> Ops;
5968     Ops.push_back(N->getOperand(0)); // incoming chain
5969     Ops.push_back(N->getOperand(AddrOpIdx));
5970     Ops.push_back(Inc);
5971     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
5972       Ops.push_back(N->getOperand(i));
5973     }
5974     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
5975     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
5976                                            Ops.data(), Ops.size(),
5977                                            MemInt->getMemoryVT(),
5978                                            MemInt->getMemOperand());
5979 
5980     // Update the uses.
5981     std::vector<SDValue> NewResults;
5982     for (unsigned i = 0; i < NumResultVecs; ++i) {
5983       NewResults.push_back(SDValue(UpdN.getNode(), i));
5984     }
5985     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
5986     DCI.CombineTo(N, NewResults);
5987     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
5988 
5989     break;
5990   }
5991   return SDValue();
5992 }
5993 
5994 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
5995 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
5996 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
5997 /// return true.
5998 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
5999   SelectionDAG &DAG = DCI.DAG;
6000   EVT VT = N->getValueType(0);
6001   // vldN-dup instructions only support 64-bit vectors for N > 1.
6002   if (!VT.is64BitVector())
6003     return false;
6004 
6005   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
6006   SDNode *VLD = N->getOperand(0).getNode();
6007   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
6008     return false;
6009   unsigned NumVecs = 0;
6010   unsigned NewOpc = 0;
6011   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
6012   if (IntNo == Intrinsic::arm_neon_vld2lane) {
6013     NumVecs = 2;
6014     NewOpc = ARMISD::VLD2DUP;
6015   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
6016     NumVecs = 3;
6017     NewOpc = ARMISD::VLD3DUP;
6018   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
6019     NumVecs = 4;
6020     NewOpc = ARMISD::VLD4DUP;
6021   } else {
6022     return false;
6023   }
6024 
6025   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
6026   // numbers match the load.
6027   unsigned VLDLaneNo =
6028     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
6029   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
6030        UI != UE; ++UI) {
6031     // Ignore uses of the chain result.
6032     if (UI.getUse().getResNo() == NumVecs)
6033       continue;
6034     SDNode *User = *UI;
6035     if (User->getOpcode() != ARMISD::VDUPLANE ||
6036         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
6037       return false;
6038   }
6039 
6040   // Create the vldN-dup node.
6041   EVT Tys[5];
6042   unsigned n;
6043   for (n = 0; n < NumVecs; ++n)
6044     Tys[n] = VT;
6045   Tys[n] = MVT::Other;
6046   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
6047   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
6048   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
6049   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
6050                                            Ops, 2, VLDMemInt->getMemoryVT(),
6051                                            VLDMemInt->getMemOperand());
6052 
6053   // Update the uses.
6054   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
6055        UI != UE; ++UI) {
6056     unsigned ResNo = UI.getUse().getResNo();
6057     // Ignore uses of the chain result.
6058     if (ResNo == NumVecs)
6059       continue;
6060     SDNode *User = *UI;
6061     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
6062   }
6063 
6064   // Now the vldN-lane intrinsic is dead except for its chain result.
6065   // Update uses of the chain.
6066   std::vector<SDValue> VLDDupResults;
6067   for (unsigned n = 0; n < NumVecs; ++n)
6068     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
6069   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
6070   DCI.CombineTo(VLD, VLDDupResults);
6071 
6072   return true;
6073 }
6074 
6075 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
6076 /// ARMISD::VDUPLANE.
6077 static SDValue PerformVDUPLANECombine(SDNode *N,
6078                                       TargetLowering::DAGCombinerInfo &DCI) {
6079   SDValue Op = N->getOperand(0);
6080 
6081   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
6082   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
6083   if (CombineVLDDUP(N, DCI))
6084     return SDValue(N, 0);
6085 
6086   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
6087   // redundant.  Ignore bit_converts for now; element sizes are checked below.
6088   while (Op.getOpcode() == ISD::BITCAST)
6089     Op = Op.getOperand(0);
6090   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
6091     return SDValue();
6092 
6093   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
6094   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
6095   // The canonical VMOV for a zero vector uses a 32-bit element size.
6096   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6097   unsigned EltBits;
6098   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
6099     EltSize = 8;
6100   EVT VT = N->getValueType(0);
6101   if (EltSize > VT.getVectorElementType().getSizeInBits())
6102     return SDValue();
6103 
6104   return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
6105 }
6106 
6107 /// getVShiftImm - Check if this is a valid build_vector for the immediate
6108 /// operand of a vector shift operation, where all the elements of the
6109 /// build_vector must have the same constant integer value.
6110 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6111   // Ignore bit_converts.
6112   while (Op.getOpcode() == ISD::BITCAST)
6113     Op = Op.getOperand(0);
6114   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6115   APInt SplatBits, SplatUndef;
6116   unsigned SplatBitSize;
6117   bool HasAnyUndefs;
6118   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6119                                       HasAnyUndefs, ElementBits) ||
6120       SplatBitSize > ElementBits)
6121     return false;
6122   Cnt = SplatBits.getSExtValue();
6123   return true;
6124 }
6125 
6126 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6127 /// operand of a vector shift left operation.  That value must be in the range:
6128 ///   0 <= Value < ElementBits for a left shift; or
6129 ///   0 <= Value <= ElementBits for a long left shift.
6130 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6131   assert(VT.isVector() && "vector shift count is not a vector type");
6132   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
6133   if (! getVShiftImm(Op, ElementBits, Cnt))
6134     return false;
6135   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
6136 }
6137 
6138 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6139 /// operand of a vector shift right operation.  For a shift opcode, the value
6140 /// is positive, but for an intrinsic the value count must be negative. The
6141 /// absolute value must be in the range:
6142 ///   1 <= |Value| <= ElementBits for a right shift; or
6143 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
6144 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
6145                          int64_t &Cnt) {
6146   assert(VT.isVector() && "vector shift count is not a vector type");
6147   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
6148   if (! getVShiftImm(Op, ElementBits, Cnt))
6149     return false;
6150   if (isIntrinsic)
6151     Cnt = -Cnt;
6152   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
6153 }
6154 
6155 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
6156 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
6157   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6158   switch (IntNo) {
6159   default:
6160     // Don't do anything for most intrinsics.
6161     break;
6162 
6163   // Vector shifts: check for immediate versions and lower them.
6164   // Note: This is done during DAG combining instead of DAG legalizing because
6165   // the build_vectors for 64-bit vector element shift counts are generally
6166   // not legal, and it is hard to see their values after they get legalized to
6167   // loads from a constant pool.
6168   case Intrinsic::arm_neon_vshifts:
6169   case Intrinsic::arm_neon_vshiftu:
6170   case Intrinsic::arm_neon_vshiftls:
6171   case Intrinsic::arm_neon_vshiftlu:
6172   case Intrinsic::arm_neon_vshiftn:
6173   case Intrinsic::arm_neon_vrshifts:
6174   case Intrinsic::arm_neon_vrshiftu:
6175   case Intrinsic::arm_neon_vrshiftn:
6176   case Intrinsic::arm_neon_vqshifts:
6177   case Intrinsic::arm_neon_vqshiftu:
6178   case Intrinsic::arm_neon_vqshiftsu:
6179   case Intrinsic::arm_neon_vqshiftns:
6180   case Intrinsic::arm_neon_vqshiftnu:
6181   case Intrinsic::arm_neon_vqshiftnsu:
6182   case Intrinsic::arm_neon_vqrshiftns:
6183   case Intrinsic::arm_neon_vqrshiftnu:
6184   case Intrinsic::arm_neon_vqrshiftnsu: {
6185     EVT VT = N->getOperand(1).getValueType();
6186     int64_t Cnt;
6187     unsigned VShiftOpc = 0;
6188 
6189     switch (IntNo) {
6190     case Intrinsic::arm_neon_vshifts:
6191     case Intrinsic::arm_neon_vshiftu:
6192       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
6193         VShiftOpc = ARMISD::VSHL;
6194         break;
6195       }
6196       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
6197         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
6198                      ARMISD::VSHRs : ARMISD::VSHRu);
6199         break;
6200       }
6201       return SDValue();
6202 
6203     case Intrinsic::arm_neon_vshiftls:
6204     case Intrinsic::arm_neon_vshiftlu:
6205       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
6206         break;
6207       llvm_unreachable("invalid shift count for vshll intrinsic");
6208 
6209     case Intrinsic::arm_neon_vrshifts:
6210     case Intrinsic::arm_neon_vrshiftu:
6211       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
6212         break;
6213       return SDValue();
6214 
6215     case Intrinsic::arm_neon_vqshifts:
6216     case Intrinsic::arm_neon_vqshiftu:
6217       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
6218         break;
6219       return SDValue();
6220 
6221     case Intrinsic::arm_neon_vqshiftsu:
6222       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
6223         break;
6224       llvm_unreachable("invalid shift count for vqshlu intrinsic");
6225 
6226     case Intrinsic::arm_neon_vshiftn:
6227     case Intrinsic::arm_neon_vrshiftn:
6228     case Intrinsic::arm_neon_vqshiftns:
6229     case Intrinsic::arm_neon_vqshiftnu:
6230     case Intrinsic::arm_neon_vqshiftnsu:
6231     case Intrinsic::arm_neon_vqrshiftns:
6232     case Intrinsic::arm_neon_vqrshiftnu:
6233     case Intrinsic::arm_neon_vqrshiftnsu:
6234       // Narrowing shifts require an immediate right shift.
6235       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
6236         break;
6237       llvm_unreachable("invalid shift count for narrowing vector shift "
6238                        "intrinsic");
6239 
6240     default:
6241       llvm_unreachable("unhandled vector shift");
6242     }
6243 
6244     switch (IntNo) {
6245     case Intrinsic::arm_neon_vshifts:
6246     case Intrinsic::arm_neon_vshiftu:
6247       // Opcode already set above.
6248       break;
6249     case Intrinsic::arm_neon_vshiftls:
6250     case Intrinsic::arm_neon_vshiftlu:
6251       if (Cnt == VT.getVectorElementType().getSizeInBits())
6252         VShiftOpc = ARMISD::VSHLLi;
6253       else
6254         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
6255                      ARMISD::VSHLLs : ARMISD::VSHLLu);
6256       break;
6257     case Intrinsic::arm_neon_vshiftn:
6258       VShiftOpc = ARMISD::VSHRN; break;
6259     case Intrinsic::arm_neon_vrshifts:
6260       VShiftOpc = ARMISD::VRSHRs; break;
6261     case Intrinsic::arm_neon_vrshiftu:
6262       VShiftOpc = ARMISD::VRSHRu; break;
6263     case Intrinsic::arm_neon_vrshiftn:
6264       VShiftOpc = ARMISD::VRSHRN; break;
6265     case Intrinsic::arm_neon_vqshifts:
6266       VShiftOpc = ARMISD::VQSHLs; break;
6267     case Intrinsic::arm_neon_vqshiftu:
6268       VShiftOpc = ARMISD::VQSHLu; break;
6269     case Intrinsic::arm_neon_vqshiftsu:
6270       VShiftOpc = ARMISD::VQSHLsu; break;
6271     case Intrinsic::arm_neon_vqshiftns:
6272       VShiftOpc = ARMISD::VQSHRNs; break;
6273     case Intrinsic::arm_neon_vqshiftnu:
6274       VShiftOpc = ARMISD::VQSHRNu; break;
6275     case Intrinsic::arm_neon_vqshiftnsu:
6276       VShiftOpc = ARMISD::VQSHRNsu; break;
6277     case Intrinsic::arm_neon_vqrshiftns:
6278       VShiftOpc = ARMISD::VQRSHRNs; break;
6279     case Intrinsic::arm_neon_vqrshiftnu:
6280       VShiftOpc = ARMISD::VQRSHRNu; break;
6281     case Intrinsic::arm_neon_vqrshiftnsu:
6282       VShiftOpc = ARMISD::VQRSHRNsu; break;
6283     }
6284 
6285     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
6286                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
6287   }
6288 
6289   case Intrinsic::arm_neon_vshiftins: {
6290     EVT VT = N->getOperand(1).getValueType();
6291     int64_t Cnt;
6292     unsigned VShiftOpc = 0;
6293 
6294     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
6295       VShiftOpc = ARMISD::VSLI;
6296     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
6297       VShiftOpc = ARMISD::VSRI;
6298     else {
6299       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
6300     }
6301 
6302     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
6303                        N->getOperand(1), N->getOperand(2),
6304                        DAG.getConstant(Cnt, MVT::i32));
6305   }
6306 
6307   case Intrinsic::arm_neon_vqrshifts:
6308   case Intrinsic::arm_neon_vqrshiftu:
6309     // No immediate versions of these to check for.
6310     break;
6311   }
6312 
6313   return SDValue();
6314 }
6315 
6316 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
6317 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
6318 /// combining instead of DAG legalizing because the build_vectors for 64-bit
6319 /// vector element shift counts are generally not legal, and it is hard to see
6320 /// their values after they get legalized to loads from a constant pool.
6321 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
6322                                    const ARMSubtarget *ST) {
6323   EVT VT = N->getValueType(0);
6324 
6325   // Nothing to be done for scalar shifts.
6326   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6327   if (!VT.isVector() || !TLI.isTypeLegal(VT))
6328     return SDValue();
6329 
6330   assert(ST->hasNEON() && "unexpected vector shift");
6331   int64_t Cnt;
6332 
6333   switch (N->getOpcode()) {
6334   default: llvm_unreachable("unexpected shift opcode");
6335 
6336   case ISD::SHL:
6337     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
6338       return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
6339                          DAG.getConstant(Cnt, MVT::i32));
6340     break;
6341 
6342   case ISD::SRA:
6343   case ISD::SRL:
6344     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
6345       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
6346                             ARMISD::VSHRs : ARMISD::VSHRu);
6347       return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
6348                          DAG.getConstant(Cnt, MVT::i32));
6349     }
6350   }
6351   return SDValue();
6352 }
6353 
6354 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
6355 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
6356 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
6357                                     const ARMSubtarget *ST) {
6358   SDValue N0 = N->getOperand(0);
6359 
6360   // Check for sign- and zero-extensions of vector extract operations of 8-
6361   // and 16-bit vector elements.  NEON supports these directly.  They are
6362   // handled during DAG combining because type legalization will promote them
6363   // to 32-bit types and it is messy to recognize the operations after that.
6364   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
6365     SDValue Vec = N0.getOperand(0);
6366     SDValue Lane = N0.getOperand(1);
6367     EVT VT = N->getValueType(0);
6368     EVT EltVT = N0.getValueType();
6369     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6370 
6371     if (VT == MVT::i32 &&
6372         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
6373         TLI.isTypeLegal(Vec.getValueType()) &&
6374         isa<ConstantSDNode>(Lane)) {
6375 
6376       unsigned Opc = 0;
6377       switch (N->getOpcode()) {
6378       default: llvm_unreachable("unexpected opcode");
6379       case ISD::SIGN_EXTEND:
6380         Opc = ARMISD::VGETLANEs;
6381         break;
6382       case ISD::ZERO_EXTEND:
6383       case ISD::ANY_EXTEND:
6384         Opc = ARMISD::VGETLANEu;
6385         break;
6386       }
6387       return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
6388     }
6389   }
6390 
6391   return SDValue();
6392 }
6393 
6394 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
6395 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
6396 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
6397                                        const ARMSubtarget *ST) {
6398   // If the target supports NEON, try to use vmax/vmin instructions for f32
6399   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
6400   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
6401   // a NaN; only do the transformation when it matches that behavior.
6402 
6403   // For now only do this when using NEON for FP operations; if using VFP, it
6404   // is not obvious that the benefit outweighs the cost of switching to the
6405   // NEON pipeline.
6406   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
6407       N->getValueType(0) != MVT::f32)
6408     return SDValue();
6409 
6410   SDValue CondLHS = N->getOperand(0);
6411   SDValue CondRHS = N->getOperand(1);
6412   SDValue LHS = N->getOperand(2);
6413   SDValue RHS = N->getOperand(3);
6414   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
6415 
6416   unsigned Opcode = 0;
6417   bool IsReversed;
6418   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
6419     IsReversed = false; // x CC y ? x : y
6420   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
6421     IsReversed = true ; // x CC y ? y : x
6422   } else {
6423     return SDValue();
6424   }
6425 
6426   bool IsUnordered;
6427   switch (CC) {
6428   default: break;
6429   case ISD::SETOLT:
6430   case ISD::SETOLE:
6431   case ISD::SETLT:
6432   case ISD::SETLE:
6433   case ISD::SETULT:
6434   case ISD::SETULE:
6435     // If LHS is NaN, an ordered comparison will be false and the result will
6436     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
6437     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
6438     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
6439     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
6440       break;
6441     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
6442     // will return -0, so vmin can only be used for unsafe math or if one of
6443     // the operands is known to be nonzero.
6444     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
6445         !UnsafeFPMath &&
6446         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
6447       break;
6448     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
6449     break;
6450 
6451   case ISD::SETOGT:
6452   case ISD::SETOGE:
6453   case ISD::SETGT:
6454   case ISD::SETGE:
6455   case ISD::SETUGT:
6456   case ISD::SETUGE:
6457     // If LHS is NaN, an ordered comparison will be false and the result will
6458     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
6459     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
6460     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
6461     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
6462       break;
6463     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
6464     // will return +0, so vmax can only be used for unsafe math or if one of
6465     // the operands is known to be nonzero.
6466     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
6467         !UnsafeFPMath &&
6468         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
6469       break;
6470     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
6471     break;
6472   }
6473 
6474   if (!Opcode)
6475     return SDValue();
6476   return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
6477 }
6478 
6479 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
6480                                              DAGCombinerInfo &DCI) const {
6481   switch (N->getOpcode()) {
6482   default: break;
6483   case ISD::ADD:        return PerformADDCombine(N, DCI);
6484   case ISD::SUB:        return PerformSUBCombine(N, DCI);
6485   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
6486   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
6487   case ISD::AND:        return PerformANDCombine(N, DCI);
6488   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
6489   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
6490   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
6491   case ISD::STORE:      return PerformSTORECombine(N, DCI);
6492   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
6493   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
6494   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
6495   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
6496   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
6497   case ISD::SHL:
6498   case ISD::SRA:
6499   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
6500   case ISD::SIGN_EXTEND:
6501   case ISD::ZERO_EXTEND:
6502   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
6503   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
6504   case ARMISD::VLD2DUP:
6505   case ARMISD::VLD3DUP:
6506   case ARMISD::VLD4DUP:
6507     return CombineBaseUpdate(N, DCI);
6508   case ISD::INTRINSIC_VOID:
6509   case ISD::INTRINSIC_W_CHAIN:
6510     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
6511     case Intrinsic::arm_neon_vld1:
6512     case Intrinsic::arm_neon_vld2:
6513     case Intrinsic::arm_neon_vld3:
6514     case Intrinsic::arm_neon_vld4:
6515     case Intrinsic::arm_neon_vld2lane:
6516     case Intrinsic::arm_neon_vld3lane:
6517     case Intrinsic::arm_neon_vld4lane:
6518     case Intrinsic::arm_neon_vst1:
6519     case Intrinsic::arm_neon_vst2:
6520     case Intrinsic::arm_neon_vst3:
6521     case Intrinsic::arm_neon_vst4:
6522     case Intrinsic::arm_neon_vst2lane:
6523     case Intrinsic::arm_neon_vst3lane:
6524     case Intrinsic::arm_neon_vst4lane:
6525       return CombineBaseUpdate(N, DCI);
6526     default: break;
6527     }
6528     break;
6529   }
6530   return SDValue();
6531 }
6532 
6533 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
6534                                                           EVT VT) const {
6535   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
6536 }
6537 
6538 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
6539   if (!Subtarget->allowsUnalignedMem())
6540     return false;
6541 
6542   switch (VT.getSimpleVT().SimpleTy) {
6543   default:
6544     return false;
6545   case MVT::i8:
6546   case MVT::i16:
6547   case MVT::i32:
6548     return true;
6549   // FIXME: VLD1 etc with standard alignment is legal.
6550   }
6551 }
6552 
6553 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
6554   if (V < 0)
6555     return false;
6556 
6557   unsigned Scale = 1;
6558   switch (VT.getSimpleVT().SimpleTy) {
6559   default: return false;
6560   case MVT::i1:
6561   case MVT::i8:
6562     // Scale == 1;
6563     break;
6564   case MVT::i16:
6565     // Scale == 2;
6566     Scale = 2;
6567     break;
6568   case MVT::i32:
6569     // Scale == 4;
6570     Scale = 4;
6571     break;
6572   }
6573 
6574   if ((V & (Scale - 1)) != 0)
6575     return false;
6576   V /= Scale;
6577   return V == (V & ((1LL << 5) - 1));
6578 }
6579 
6580 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
6581                                       const ARMSubtarget *Subtarget) {
6582   bool isNeg = false;
6583   if (V < 0) {
6584     isNeg = true;
6585     V = - V;
6586   }
6587 
6588   switch (VT.getSimpleVT().SimpleTy) {
6589   default: return false;
6590   case MVT::i1:
6591   case MVT::i8:
6592   case MVT::i16:
6593   case MVT::i32:
6594     // + imm12 or - imm8
6595     if (isNeg)
6596       return V == (V & ((1LL << 8) - 1));
6597     return V == (V & ((1LL << 12) - 1));
6598   case MVT::f32:
6599   case MVT::f64:
6600     // Same as ARM mode. FIXME: NEON?
6601     if (!Subtarget->hasVFP2())
6602       return false;
6603     if ((V & 3) != 0)
6604       return false;
6605     V >>= 2;
6606     return V == (V & ((1LL << 8) - 1));
6607   }
6608 }
6609 
6610 /// isLegalAddressImmediate - Return true if the integer value can be used
6611 /// as the offset of the target addressing mode for load / store of the
6612 /// given type.
6613 static bool isLegalAddressImmediate(int64_t V, EVT VT,
6614                                     const ARMSubtarget *Subtarget) {
6615   if (V == 0)
6616     return true;
6617 
6618   if (!VT.isSimple())
6619     return false;
6620 
6621   if (Subtarget->isThumb1Only())
6622     return isLegalT1AddressImmediate(V, VT);
6623   else if (Subtarget->isThumb2())
6624     return isLegalT2AddressImmediate(V, VT, Subtarget);
6625 
6626   // ARM mode.
6627   if (V < 0)
6628     V = - V;
6629   switch (VT.getSimpleVT().SimpleTy) {
6630   default: return false;
6631   case MVT::i1:
6632   case MVT::i8:
6633   case MVT::i32:
6634     // +- imm12
6635     return V == (V & ((1LL << 12) - 1));
6636   case MVT::i16:
6637     // +- imm8
6638     return V == (V & ((1LL << 8) - 1));
6639   case MVT::f32:
6640   case MVT::f64:
6641     if (!Subtarget->hasVFP2()) // FIXME: NEON?
6642       return false;
6643     if ((V & 3) != 0)
6644       return false;
6645     V >>= 2;
6646     return V == (V & ((1LL << 8) - 1));
6647   }
6648 }
6649 
6650 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
6651                                                       EVT VT) const {
6652   int Scale = AM.Scale;
6653   if (Scale < 0)
6654     return false;
6655 
6656   switch (VT.getSimpleVT().SimpleTy) {
6657   default: return false;
6658   case MVT::i1:
6659   case MVT::i8:
6660   case MVT::i16:
6661   case MVT::i32:
6662     if (Scale == 1)
6663       return true;
6664     // r + r << imm
6665     Scale = Scale & ~1;
6666     return Scale == 2 || Scale == 4 || Scale == 8;
6667   case MVT::i64:
6668     // r + r
6669     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
6670       return true;
6671     return false;
6672   case MVT::isVoid:
6673     // Note, we allow "void" uses (basically, uses that aren't loads or
6674     // stores), because arm allows folding a scale into many arithmetic
6675     // operations.  This should be made more precise and revisited later.
6676 
6677     // Allow r << imm, but the imm has to be a multiple of two.
6678     if (Scale & 1) return false;
6679     return isPowerOf2_32(Scale);
6680   }
6681 }
6682 
6683 /// isLegalAddressingMode - Return true if the addressing mode represented
6684 /// by AM is legal for this target, for a load/store of the specified type.
6685 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
6686                                               const Type *Ty) const {
6687   EVT VT = getValueType(Ty, true);
6688   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
6689     return false;
6690 
6691   // Can never fold addr of global into load/store.
6692   if (AM.BaseGV)
6693     return false;
6694 
6695   switch (AM.Scale) {
6696   case 0:  // no scale reg, must be "r+i" or "r", or "i".
6697     break;
6698   case 1:
6699     if (Subtarget->isThumb1Only())
6700       return false;
6701     // FALL THROUGH.
6702   default:
6703     // ARM doesn't support any R+R*scale+imm addr modes.
6704     if (AM.BaseOffs)
6705       return false;
6706 
6707     if (!VT.isSimple())
6708       return false;
6709 
6710     if (Subtarget->isThumb2())
6711       return isLegalT2ScaledAddressingMode(AM, VT);
6712 
6713     int Scale = AM.Scale;
6714     switch (VT.getSimpleVT().SimpleTy) {
6715     default: return false;
6716     case MVT::i1:
6717     case MVT::i8:
6718     case MVT::i32:
6719       if (Scale < 0) Scale = -Scale;
6720       if (Scale == 1)
6721         return true;
6722       // r + r << imm
6723       return isPowerOf2_32(Scale & ~1);
6724     case MVT::i16:
6725     case MVT::i64:
6726       // r + r
6727       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
6728         return true;
6729       return false;
6730 
6731     case MVT::isVoid:
6732       // Note, we allow "void" uses (basically, uses that aren't loads or
6733       // stores), because arm allows folding a scale into many arithmetic
6734       // operations.  This should be made more precise and revisited later.
6735 
6736       // Allow r << imm, but the imm has to be a multiple of two.
6737       if (Scale & 1) return false;
6738       return isPowerOf2_32(Scale);
6739     }
6740     break;
6741   }
6742   return true;
6743 }
6744 
6745 /// isLegalICmpImmediate - Return true if the specified immediate is legal
6746 /// icmp immediate, that is the target has icmp instructions which can compare
6747 /// a register against the immediate without having to materialize the
6748 /// immediate into a register.
6749 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
6750   if (!Subtarget->isThumb())
6751     return ARM_AM::getSOImmVal(Imm) != -1;
6752   if (Subtarget->isThumb2())
6753     return ARM_AM::getT2SOImmVal(Imm) != -1;
6754   return Imm >= 0 && Imm <= 255;
6755 }
6756 
6757 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
6758                                       bool isSEXTLoad, SDValue &Base,
6759                                       SDValue &Offset, bool &isInc,
6760                                       SelectionDAG &DAG) {
6761   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
6762     return false;
6763 
6764   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
6765     // AddressingMode 3
6766     Base = Ptr->getOperand(0);
6767     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
6768       int RHSC = (int)RHS->getZExtValue();
6769       if (RHSC < 0 && RHSC > -256) {
6770         assert(Ptr->getOpcode() == ISD::ADD);
6771         isInc = false;
6772         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
6773         return true;
6774       }
6775     }
6776     isInc = (Ptr->getOpcode() == ISD::ADD);
6777     Offset = Ptr->getOperand(1);
6778     return true;
6779   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
6780     // AddressingMode 2
6781     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
6782       int RHSC = (int)RHS->getZExtValue();
6783       if (RHSC < 0 && RHSC > -0x1000) {
6784         assert(Ptr->getOpcode() == ISD::ADD);
6785         isInc = false;
6786         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
6787         Base = Ptr->getOperand(0);
6788         return true;
6789       }
6790     }
6791 
6792     if (Ptr->getOpcode() == ISD::ADD) {
6793       isInc = true;
6794       ARM_AM::ShiftOpc ShOpcVal= ARM_AM::getShiftOpcForNode(Ptr->getOperand(0));
6795       if (ShOpcVal != ARM_AM::no_shift) {
6796         Base = Ptr->getOperand(1);
6797         Offset = Ptr->getOperand(0);
6798       } else {
6799         Base = Ptr->getOperand(0);
6800         Offset = Ptr->getOperand(1);
6801       }
6802       return true;
6803     }
6804 
6805     isInc = (Ptr->getOpcode() == ISD::ADD);
6806     Base = Ptr->getOperand(0);
6807     Offset = Ptr->getOperand(1);
6808     return true;
6809   }
6810 
6811   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
6812   return false;
6813 }
6814 
6815 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
6816                                      bool isSEXTLoad, SDValue &Base,
6817                                      SDValue &Offset, bool &isInc,
6818                                      SelectionDAG &DAG) {
6819   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
6820     return false;
6821 
6822   Base = Ptr->getOperand(0);
6823   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
6824     int RHSC = (int)RHS->getZExtValue();
6825     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
6826       assert(Ptr->getOpcode() == ISD::ADD);
6827       isInc = false;
6828       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
6829       return true;
6830     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
6831       isInc = Ptr->getOpcode() == ISD::ADD;
6832       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
6833       return true;
6834     }
6835   }
6836 
6837   return false;
6838 }
6839 
6840 /// getPreIndexedAddressParts - returns true by value, base pointer and
6841 /// offset pointer and addressing mode by reference if the node's address
6842 /// can be legally represented as pre-indexed load / store address.
6843 bool
6844 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
6845                                              SDValue &Offset,
6846                                              ISD::MemIndexedMode &AM,
6847                                              SelectionDAG &DAG) const {
6848   if (Subtarget->isThumb1Only())
6849     return false;
6850 
6851   EVT VT;
6852   SDValue Ptr;
6853   bool isSEXTLoad = false;
6854   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
6855     Ptr = LD->getBasePtr();
6856     VT  = LD->getMemoryVT();
6857     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
6858   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
6859     Ptr = ST->getBasePtr();
6860     VT  = ST->getMemoryVT();
6861   } else
6862     return false;
6863 
6864   bool isInc;
6865   bool isLegal = false;
6866   if (Subtarget->isThumb2())
6867     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
6868                                        Offset, isInc, DAG);
6869   else
6870     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
6871                                         Offset, isInc, DAG);
6872   if (!isLegal)
6873     return false;
6874 
6875   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
6876   return true;
6877 }
6878 
6879 /// getPostIndexedAddressParts - returns true by value, base pointer and
6880 /// offset pointer and addressing mode by reference if this node can be
6881 /// combined with a load / store to form a post-indexed load / store.
6882 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
6883                                                    SDValue &Base,
6884                                                    SDValue &Offset,
6885                                                    ISD::MemIndexedMode &AM,
6886                                                    SelectionDAG &DAG) const {
6887   if (Subtarget->isThumb1Only())
6888     return false;
6889 
6890   EVT VT;
6891   SDValue Ptr;
6892   bool isSEXTLoad = false;
6893   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
6894     VT  = LD->getMemoryVT();
6895     Ptr = LD->getBasePtr();
6896     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
6897   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
6898     VT  = ST->getMemoryVT();
6899     Ptr = ST->getBasePtr();
6900   } else
6901     return false;
6902 
6903   bool isInc;
6904   bool isLegal = false;
6905   if (Subtarget->isThumb2())
6906     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
6907                                        isInc, DAG);
6908   else
6909     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
6910                                         isInc, DAG);
6911   if (!isLegal)
6912     return false;
6913 
6914   if (Ptr != Base) {
6915     // Swap base ptr and offset to catch more post-index load / store when
6916     // it's legal. In Thumb2 mode, offset must be an immediate.
6917     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
6918         !Subtarget->isThumb2())
6919       std::swap(Base, Offset);
6920 
6921     // Post-indexed load / store update the base pointer.
6922     if (Ptr != Base)
6923       return false;
6924   }
6925 
6926   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
6927   return true;
6928 }
6929 
6930 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
6931                                                        const APInt &Mask,
6932                                                        APInt &KnownZero,
6933                                                        APInt &KnownOne,
6934                                                        const SelectionDAG &DAG,
6935                                                        unsigned Depth) const {
6936   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);
6937   switch (Op.getOpcode()) {
6938   default: break;
6939   case ARMISD::CMOV: {
6940     // Bits are known zero/one if known on the LHS and RHS.
6941     DAG.ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
6942     if (KnownZero == 0 && KnownOne == 0) return;
6943 
6944     APInt KnownZeroRHS, KnownOneRHS;
6945     DAG.ComputeMaskedBits(Op.getOperand(1), Mask,
6946                           KnownZeroRHS, KnownOneRHS, Depth+1);
6947     KnownZero &= KnownZeroRHS;
6948     KnownOne  &= KnownOneRHS;
6949     return;
6950   }
6951   }
6952 }
6953 
6954 //===----------------------------------------------------------------------===//
6955 //                           ARM Inline Assembly Support
6956 //===----------------------------------------------------------------------===//
6957 
6958 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
6959   // Looking for "rev" which is V6+.
6960   if (!Subtarget->hasV6Ops())
6961     return false;
6962 
6963   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
6964   std::string AsmStr = IA->getAsmString();
6965   SmallVector<StringRef, 4> AsmPieces;
6966   SplitString(AsmStr, AsmPieces, ";\n");
6967 
6968   switch (AsmPieces.size()) {
6969   default: return false;
6970   case 1:
6971     AsmStr = AsmPieces[0];
6972     AsmPieces.clear();
6973     SplitString(AsmStr, AsmPieces, " \t,");
6974 
6975     // rev $0, $1
6976     if (AsmPieces.size() == 3 &&
6977         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
6978         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
6979       const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
6980       if (Ty && Ty->getBitWidth() == 32)
6981         return IntrinsicLowering::LowerToByteSwap(CI);
6982     }
6983     break;
6984   }
6985 
6986   return false;
6987 }
6988 
6989 /// getConstraintType - Given a constraint letter, return the type of
6990 /// constraint it is for this target.
6991 ARMTargetLowering::ConstraintType
6992 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
6993   if (Constraint.size() == 1) {
6994     switch (Constraint[0]) {
6995     default:  break;
6996     case 'l': return C_RegisterClass;
6997     case 'w': return C_RegisterClass;
6998     }
6999   }
7000   return TargetLowering::getConstraintType(Constraint);
7001 }
7002 
7003 /// Examine constraint type and operand type and determine a weight value.
7004 /// This object must already have been set up with the operand type
7005 /// and the current alternative constraint selected.
7006 TargetLowering::ConstraintWeight
7007 ARMTargetLowering::getSingleConstraintMatchWeight(
7008     AsmOperandInfo &info, const char *constraint) const {
7009   ConstraintWeight weight = CW_Invalid;
7010   Value *CallOperandVal = info.CallOperandVal;
7011     // If we don't have a value, we can't do a match,
7012     // but allow it at the lowest weight.
7013   if (CallOperandVal == NULL)
7014     return CW_Default;
7015   const Type *type = CallOperandVal->getType();
7016   // Look at the constraint type.
7017   switch (*constraint) {
7018   default:
7019     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
7020     break;
7021   case 'l':
7022     if (type->isIntegerTy()) {
7023       if (Subtarget->isThumb())
7024         weight = CW_SpecificReg;
7025       else
7026         weight = CW_Register;
7027     }
7028     break;
7029   case 'w':
7030     if (type->isFloatingPointTy())
7031       weight = CW_Register;
7032     break;
7033   }
7034   return weight;
7035 }
7036 
7037 std::pair<unsigned, const TargetRegisterClass*>
7038 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
7039                                                 EVT VT) const {
7040   if (Constraint.size() == 1) {
7041     // GCC ARM Constraint Letters
7042     switch (Constraint[0]) {
7043     case 'l':
7044       if (Subtarget->isThumb())
7045         return std::make_pair(0U, ARM::tGPRRegisterClass);
7046       else
7047         return std::make_pair(0U, ARM::GPRRegisterClass);
7048     case 'r':
7049       return std::make_pair(0U, ARM::GPRRegisterClass);
7050     case 'w':
7051       if (VT == MVT::f32)
7052         return std::make_pair(0U, ARM::SPRRegisterClass);
7053       if (VT.getSizeInBits() == 64)
7054         return std::make_pair(0U, ARM::DPRRegisterClass);
7055       if (VT.getSizeInBits() == 128)
7056         return std::make_pair(0U, ARM::QPRRegisterClass);
7057       break;
7058     }
7059   }
7060   if (StringRef("{cc}").equals_lower(Constraint))
7061     return std::make_pair(unsigned(ARM::CPSR), ARM::CCRRegisterClass);
7062 
7063   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
7064 }
7065 
7066 std::vector<unsigned> ARMTargetLowering::
7067 getRegClassForInlineAsmConstraint(const std::string &Constraint,
7068                                   EVT VT) const {
7069   if (Constraint.size() != 1)
7070     return std::vector<unsigned>();
7071 
7072   switch (Constraint[0]) {      // GCC ARM Constraint Letters
7073   default: break;
7074   case 'l':
7075     return make_vector<unsigned>(ARM::R0, ARM::R1, ARM::R2, ARM::R3,
7076                                  ARM::R4, ARM::R5, ARM::R6, ARM::R7,
7077                                  0);
7078   case 'r':
7079     return make_vector<unsigned>(ARM::R0, ARM::R1, ARM::R2, ARM::R3,
7080                                  ARM::R4, ARM::R5, ARM::R6, ARM::R7,
7081                                  ARM::R8, ARM::R9, ARM::R10, ARM::R11,
7082                                  ARM::R12, ARM::LR, 0);
7083   case 'w':
7084     if (VT == MVT::f32)
7085       return make_vector<unsigned>(ARM::S0, ARM::S1, ARM::S2, ARM::S3,
7086                                    ARM::S4, ARM::S5, ARM::S6, ARM::S7,
7087                                    ARM::S8, ARM::S9, ARM::S10, ARM::S11,
7088                                    ARM::S12,ARM::S13,ARM::S14,ARM::S15,
7089                                    ARM::S16,ARM::S17,ARM::S18,ARM::S19,
7090                                    ARM::S20,ARM::S21,ARM::S22,ARM::S23,
7091                                    ARM::S24,ARM::S25,ARM::S26,ARM::S27,
7092                                    ARM::S28,ARM::S29,ARM::S30,ARM::S31, 0);
7093     if (VT.getSizeInBits() == 64)
7094       return make_vector<unsigned>(ARM::D0, ARM::D1, ARM::D2, ARM::D3,
7095                                    ARM::D4, ARM::D5, ARM::D6, ARM::D7,
7096                                    ARM::D8, ARM::D9, ARM::D10,ARM::D11,
7097                                    ARM::D12,ARM::D13,ARM::D14,ARM::D15, 0);
7098     if (VT.getSizeInBits() == 128)
7099       return make_vector<unsigned>(ARM::Q0, ARM::Q1, ARM::Q2, ARM::Q3,
7100                                    ARM::Q4, ARM::Q5, ARM::Q6, ARM::Q7, 0);
7101       break;
7102   }
7103 
7104   return std::vector<unsigned>();
7105 }
7106 
7107 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
7108 /// vector.  If it is invalid, don't add anything to Ops.
7109 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
7110                                                      char Constraint,
7111                                                      std::vector<SDValue>&Ops,
7112                                                      SelectionDAG &DAG) const {
7113   SDValue Result(0, 0);
7114 
7115   switch (Constraint) {
7116   default: break;
7117   case 'I': case 'J': case 'K': case 'L':
7118   case 'M': case 'N': case 'O':
7119     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
7120     if (!C)
7121       return;
7122 
7123     int64_t CVal64 = C->getSExtValue();
7124     int CVal = (int) CVal64;
7125     // None of these constraints allow values larger than 32 bits.  Check
7126     // that the value fits in an int.
7127     if (CVal != CVal64)
7128       return;
7129 
7130     switch (Constraint) {
7131       case 'I':
7132         if (Subtarget->isThumb1Only()) {
7133           // This must be a constant between 0 and 255, for ADD
7134           // immediates.
7135           if (CVal >= 0 && CVal <= 255)
7136             break;
7137         } else if (Subtarget->isThumb2()) {
7138           // A constant that can be used as an immediate value in a
7139           // data-processing instruction.
7140           if (ARM_AM::getT2SOImmVal(CVal) != -1)
7141             break;
7142         } else {
7143           // A constant that can be used as an immediate value in a
7144           // data-processing instruction.
7145           if (ARM_AM::getSOImmVal(CVal) != -1)
7146             break;
7147         }
7148         return;
7149 
7150       case 'J':
7151         if (Subtarget->isThumb()) {  // FIXME thumb2
7152           // This must be a constant between -255 and -1, for negated ADD
7153           // immediates. This can be used in GCC with an "n" modifier that
7154           // prints the negated value, for use with SUB instructions. It is
7155           // not useful otherwise but is implemented for compatibility.
7156           if (CVal >= -255 && CVal <= -1)
7157             break;
7158         } else {
7159           // This must be a constant between -4095 and 4095. It is not clear
7160           // what this constraint is intended for. Implemented for
7161           // compatibility with GCC.
7162           if (CVal >= -4095 && CVal <= 4095)
7163             break;
7164         }
7165         return;
7166 
7167       case 'K':
7168         if (Subtarget->isThumb1Only()) {
7169           // A 32-bit value where only one byte has a nonzero value. Exclude
7170           // zero to match GCC. This constraint is used by GCC internally for
7171           // constants that can be loaded with a move/shift combination.
7172           // It is not useful otherwise but is implemented for compatibility.
7173           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
7174             break;
7175         } else if (Subtarget->isThumb2()) {
7176           // A constant whose bitwise inverse can be used as an immediate
7177           // value in a data-processing instruction. This can be used in GCC
7178           // with a "B" modifier that prints the inverted value, for use with
7179           // BIC and MVN instructions. It is not useful otherwise but is
7180           // implemented for compatibility.
7181           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
7182             break;
7183         } else {
7184           // A constant whose bitwise inverse can be used as an immediate
7185           // value in a data-processing instruction. This can be used in GCC
7186           // with a "B" modifier that prints the inverted value, for use with
7187           // BIC and MVN instructions. It is not useful otherwise but is
7188           // implemented for compatibility.
7189           if (ARM_AM::getSOImmVal(~CVal) != -1)
7190             break;
7191         }
7192         return;
7193 
7194       case 'L':
7195         if (Subtarget->isThumb1Only()) {
7196           // This must be a constant between -7 and 7,
7197           // for 3-operand ADD/SUB immediate instructions.
7198           if (CVal >= -7 && CVal < 7)
7199             break;
7200         } else if (Subtarget->isThumb2()) {
7201           // A constant whose negation can be used as an immediate value in a
7202           // data-processing instruction. This can be used in GCC with an "n"
7203           // modifier that prints the negated value, for use with SUB
7204           // instructions. It is not useful otherwise but is implemented for
7205           // compatibility.
7206           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
7207             break;
7208         } else {
7209           // A constant whose negation can be used as an immediate value in a
7210           // data-processing instruction. This can be used in GCC with an "n"
7211           // modifier that prints the negated value, for use with SUB
7212           // instructions. It is not useful otherwise but is implemented for
7213           // compatibility.
7214           if (ARM_AM::getSOImmVal(-CVal) != -1)
7215             break;
7216         }
7217         return;
7218 
7219       case 'M':
7220         if (Subtarget->isThumb()) { // FIXME thumb2
7221           // This must be a multiple of 4 between 0 and 1020, for
7222           // ADD sp + immediate.
7223           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
7224             break;
7225         } else {
7226           // A power of two or a constant between 0 and 32.  This is used in
7227           // GCC for the shift amount on shifted register operands, but it is
7228           // useful in general for any shift amounts.
7229           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
7230             break;
7231         }
7232         return;
7233 
7234       case 'N':
7235         if (Subtarget->isThumb()) {  // FIXME thumb2
7236           // This must be a constant between 0 and 31, for shift amounts.
7237           if (CVal >= 0 && CVal <= 31)
7238             break;
7239         }
7240         return;
7241 
7242       case 'O':
7243         if (Subtarget->isThumb()) {  // FIXME thumb2
7244           // This must be a multiple of 4 between -508 and 508, for
7245           // ADD/SUB sp = sp + immediate.
7246           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
7247             break;
7248         }
7249         return;
7250     }
7251     Result = DAG.getTargetConstant(CVal, Op.getValueType());
7252     break;
7253   }
7254 
7255   if (Result.getNode()) {
7256     Ops.push_back(Result);
7257     return;
7258   }
7259   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
7260 }
7261 
7262 bool
7263 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
7264   // The ARM target isn't yet aware of offsets.
7265   return false;
7266 }
7267 
7268 int ARM::getVFPf32Imm(const APFloat &FPImm) {
7269   APInt Imm = FPImm.bitcastToAPInt();
7270   uint32_t Sign = Imm.lshr(31).getZExtValue() & 1;
7271   int32_t Exp = (Imm.lshr(23).getSExtValue() & 0xff) - 127;  // -126 to 127
7272   int64_t Mantissa = Imm.getZExtValue() & 0x7fffff;  // 23 bits
7273 
7274   // We can handle 4 bits of mantissa.
7275   // mantissa = (16+UInt(e:f:g:h))/16.
7276   if (Mantissa & 0x7ffff)
7277     return -1;
7278   Mantissa >>= 19;
7279   if ((Mantissa & 0xf) != Mantissa)
7280     return -1;
7281 
7282   // We can handle 3 bits of exponent: exp == UInt(NOT(b):c:d)-3
7283   if (Exp < -3 || Exp > 4)
7284     return -1;
7285   Exp = ((Exp+3) & 0x7) ^ 4;
7286 
7287   return ((int)Sign << 7) | (Exp << 4) | Mantissa;
7288 }
7289 
7290 int ARM::getVFPf64Imm(const APFloat &FPImm) {
7291   APInt Imm = FPImm.bitcastToAPInt();
7292   uint64_t Sign = Imm.lshr(63).getZExtValue() & 1;
7293   int64_t Exp = (Imm.lshr(52).getSExtValue() & 0x7ff) - 1023;   // -1022 to 1023
7294   uint64_t Mantissa = Imm.getZExtValue() & 0xfffffffffffffLL;
7295 
7296   // We can handle 4 bits of mantissa.
7297   // mantissa = (16+UInt(e:f:g:h))/16.
7298   if (Mantissa & 0xffffffffffffLL)
7299     return -1;
7300   Mantissa >>= 48;
7301   if ((Mantissa & 0xf) != Mantissa)
7302     return -1;
7303 
7304   // We can handle 3 bits of exponent: exp == UInt(NOT(b):c:d)-3
7305   if (Exp < -3 || Exp > 4)
7306     return -1;
7307   Exp = ((Exp+3) & 0x7) ^ 4;
7308 
7309   return ((int)Sign << 7) | (Exp << 4) | Mantissa;
7310 }
7311 
7312 bool ARM::isBitFieldInvertedMask(unsigned v) {
7313   if (v == 0xffffffff)
7314     return 0;
7315   // there can be 1's on either or both "outsides", all the "inside"
7316   // bits must be 0's
7317   unsigned int lsb = 0, msb = 31;
7318   while (v & (1 << msb)) --msb;
7319   while (v & (1 << lsb)) ++lsb;
7320   for (unsigned int i = lsb; i <= msb; ++i) {
7321     if (v & (1 << i))
7322       return 0;
7323   }
7324   return 1;
7325 }
7326 
7327 /// isFPImmLegal - Returns true if the target can instruction select the
7328 /// specified FP immediate natively. If false, the legalizer will
7329 /// materialize the FP immediate as a load from a constant pool.
7330 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
7331   if (!Subtarget->hasVFP3())
7332     return false;
7333   if (VT == MVT::f32)
7334     return ARM::getVFPf32Imm(Imm) != -1;
7335   if (VT == MVT::f64)
7336     return ARM::getVFPf64Imm(Imm) != -1;
7337   return false;
7338 }
7339 
7340 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
7341 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
7342 /// specified in the intrinsic calls.
7343 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
7344                                            const CallInst &I,
7345                                            unsigned Intrinsic) const {
7346   switch (Intrinsic) {
7347   case Intrinsic::arm_neon_vld1:
7348   case Intrinsic::arm_neon_vld2:
7349   case Intrinsic::arm_neon_vld3:
7350   case Intrinsic::arm_neon_vld4:
7351   case Intrinsic::arm_neon_vld2lane:
7352   case Intrinsic::arm_neon_vld3lane:
7353   case Intrinsic::arm_neon_vld4lane: {
7354     Info.opc = ISD::INTRINSIC_W_CHAIN;
7355     // Conservatively set memVT to the entire set of vectors loaded.
7356     uint64_t NumElts = getTargetData()->getTypeAllocSize(I.getType()) / 8;
7357     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
7358     Info.ptrVal = I.getArgOperand(0);
7359     Info.offset = 0;
7360     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
7361     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
7362     Info.vol = false; // volatile loads with NEON intrinsics not supported
7363     Info.readMem = true;
7364     Info.writeMem = false;
7365     return true;
7366   }
7367   case Intrinsic::arm_neon_vst1:
7368   case Intrinsic::arm_neon_vst2:
7369   case Intrinsic::arm_neon_vst3:
7370   case Intrinsic::arm_neon_vst4:
7371   case Intrinsic::arm_neon_vst2lane:
7372   case Intrinsic::arm_neon_vst3lane:
7373   case Intrinsic::arm_neon_vst4lane: {
7374     Info.opc = ISD::INTRINSIC_VOID;
7375     // Conservatively set memVT to the entire set of vectors stored.
7376     unsigned NumElts = 0;
7377     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
7378       const Type *ArgTy = I.getArgOperand(ArgI)->getType();
7379       if (!ArgTy->isVectorTy())
7380         break;
7381       NumElts += getTargetData()->getTypeAllocSize(ArgTy) / 8;
7382     }
7383     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
7384     Info.ptrVal = I.getArgOperand(0);
7385     Info.offset = 0;
7386     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
7387     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
7388     Info.vol = false; // volatile stores with NEON intrinsics not supported
7389     Info.readMem = false;
7390     Info.writeMem = true;
7391     return true;
7392   }
7393   default:
7394     break;
7395   }
7396 
7397   return false;
7398 }
7399