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