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