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