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