ARM: add intrinsics for the v8 ldaex/stlex
[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 "ARMISelLowering.h"
17 #include "ARMCallingConv.h"
18 #include "ARMConstantPoolValue.h"
19 #include "ARMMachineFunctionInfo.h"
20 #include "ARMPerfectShuffle.h"
21 #include "ARMSubtarget.h"
22 #include "ARMTargetMachine.h"
23 #include "ARMTargetObjectFile.h"
24 #include "MCTargetDesc/ARMAddressingModes.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/CodeGen/CallingConvLower.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineBasicBlock.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/SelectionDAG.h"
36 #include "llvm/IR/CallingConv.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalValue.h"
40 #include "llvm/IR/Instruction.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/IR/Type.h"
44 #include "llvm/MC/MCSectionMachO.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/MathExtras.h"
48 #include "llvm/Target/TargetOptions.h"
49 #include <utility>
50 using namespace llvm;
51
52 STATISTIC(NumTailCalls, "Number of tail calls");
53 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
54 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
55
56 cl::opt<bool>
57 EnableARMLongCalls("arm-long-calls", cl::Hidden,
58   cl::desc("Generate calls via indirect call instructions"),
59   cl::init(false));
60
61 static cl::opt<bool>
62 ARMInterworking("arm-interworking", cl::Hidden,
63   cl::desc("Enable / disable ARM interworking (for debugging only)"),
64   cl::init(true));
65
66 namespace {
67   class ARMCCState : public CCState {
68   public:
69     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
70                const TargetMachine &TM, SmallVectorImpl<CCValAssign> &locs,
71                LLVMContext &C, ParmContext PC)
72         : CCState(CC, isVarArg, MF, TM, locs, C) {
73       assert(((PC == Call) || (PC == Prologue)) &&
74              "ARMCCState users must specify whether their context is call"
75              "or prologue generation.");
76       CallOrPrologue = PC;
77     }
78   };
79 }
80
81 // The APCS parameter registers.
82 static const uint16_t GPRArgRegs[] = {
83   ARM::R0, ARM::R1, ARM::R2, ARM::R3
84 };
85
86 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
87                                        MVT PromotedBitwiseVT) {
88   if (VT != PromotedLdStVT) {
89     setOperationAction(ISD::LOAD, VT, Promote);
90     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
91
92     setOperationAction(ISD::STORE, VT, Promote);
93     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
94   }
95
96   MVT ElemTy = VT.getVectorElementType();
97   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
98     setOperationAction(ISD::SETCC, VT, Custom);
99   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
100   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
101   if (ElemTy == MVT::i32) {
102     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
103     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
104     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
105     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
106   } else {
107     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
108     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
109     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
110     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
111   }
112   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
113   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
114   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
115   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
116   setOperationAction(ISD::SELECT,            VT, Expand);
117   setOperationAction(ISD::SELECT_CC,         VT, Expand);
118   setOperationAction(ISD::VSELECT,           VT, Expand);
119   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
120   if (VT.isInteger()) {
121     setOperationAction(ISD::SHL, VT, Custom);
122     setOperationAction(ISD::SRA, VT, Custom);
123     setOperationAction(ISD::SRL, VT, Custom);
124   }
125
126   // Promote all bit-wise operations.
127   if (VT.isInteger() && VT != PromotedBitwiseVT) {
128     setOperationAction(ISD::AND, VT, Promote);
129     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
130     setOperationAction(ISD::OR,  VT, Promote);
131     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
132     setOperationAction(ISD::XOR, VT, Promote);
133     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
134   }
135
136   // Neon does not support vector divide/remainder operations.
137   setOperationAction(ISD::SDIV, VT, Expand);
138   setOperationAction(ISD::UDIV, VT, Expand);
139   setOperationAction(ISD::FDIV, VT, Expand);
140   setOperationAction(ISD::SREM, VT, Expand);
141   setOperationAction(ISD::UREM, VT, Expand);
142   setOperationAction(ISD::FREM, VT, Expand);
143 }
144
145 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
146   addRegisterClass(VT, &ARM::DPRRegClass);
147   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
148 }
149
150 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
151   addRegisterClass(VT, &ARM::DPairRegClass);
152   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
153 }
154
155 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
156   if (TM.getSubtarget<ARMSubtarget>().isTargetMachO())
157     return new TargetLoweringObjectFileMachO();
158
159   return new ARMElfTargetObjectFile();
160 }
161
162 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
163     : TargetLowering(TM, createTLOF(TM)) {
164   Subtarget = &TM.getSubtarget<ARMSubtarget>();
165   RegInfo = TM.getRegisterInfo();
166   Itins = TM.getInstrItineraryData();
167
168   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
169
170   if (Subtarget->isTargetMachO()) {
171     // Uses VFP for Thumb libfuncs if available.
172     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
173         Subtarget->hasARMOps()) {
174       // Single-precision floating-point arithmetic.
175       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
176       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
177       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
178       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
179
180       // Double-precision floating-point arithmetic.
181       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
182       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
183       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
184       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
185
186       // Single-precision comparisons.
187       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
188       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
189       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
190       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
191       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
192       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
193       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
194       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
195
196       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
197       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
198       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
199       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
200       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
201       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
202       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
203       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
204
205       // Double-precision comparisons.
206       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
207       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
208       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
209       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
210       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
211       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
212       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
213       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
214
215       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
216       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
217       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
218       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
219       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
220       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
221       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
222       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
223
224       // Floating-point to integer conversions.
225       // i64 conversions are done via library routines even when generating VFP
226       // instructions, so use the same ones.
227       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
228       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
229       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
230       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
231
232       // Conversions between floating types.
233       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
234       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
235
236       // Integer to floating-point conversions.
237       // i64 conversions are done via library routines even when generating VFP
238       // instructions, so use the same ones.
239       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
240       // e.g., __floatunsidf vs. __floatunssidfvfp.
241       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
242       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
243       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
244       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
245     }
246   }
247
248   // These libcalls are not available in 32-bit.
249   setLibcallName(RTLIB::SHL_I128, 0);
250   setLibcallName(RTLIB::SRL_I128, 0);
251   setLibcallName(RTLIB::SRA_I128, 0);
252
253   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO()) {
254     // Double-precision floating-point arithmetic helper functions
255     // RTABI chapter 4.1.2, Table 2
256     setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
257     setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
258     setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
259     setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
260     setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
261     setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
262     setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
263     setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
264
265     // Double-precision floating-point comparison helper functions
266     // RTABI chapter 4.1.2, Table 3
267     setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
268     setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
269     setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
270     setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
271     setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
272     setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
273     setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
274     setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
275     setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
276     setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
277     setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
278     setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
279     setLibcallName(RTLIB::UO_F64,  "__aeabi_dcmpun");
280     setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
281     setLibcallName(RTLIB::O_F64,   "__aeabi_dcmpun");
282     setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
283     setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
284     setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
285     setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
286     setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
287     setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
288     setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
289     setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
290     setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
291
292     // Single-precision floating-point arithmetic helper functions
293     // RTABI chapter 4.1.2, Table 4
294     setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
295     setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
296     setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
297     setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
298     setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
299     setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
300     setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
301     setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
302
303     // Single-precision floating-point comparison helper functions
304     // RTABI chapter 4.1.2, Table 5
305     setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
306     setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
307     setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
308     setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
309     setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
310     setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
311     setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
312     setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
313     setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
314     setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
315     setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
316     setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
317     setLibcallName(RTLIB::UO_F32,  "__aeabi_fcmpun");
318     setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
319     setLibcallName(RTLIB::O_F32,   "__aeabi_fcmpun");
320     setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
321     setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
322     setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
323     setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
324     setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
325     setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
326     setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
327     setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
328     setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
329
330     // Floating-point to integer conversions.
331     // RTABI chapter 4.1.2, Table 6
332     setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
333     setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
334     setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
335     setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
336     setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
337     setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
338     setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
339     setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
340     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
341     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
342     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
343     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
344     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
345     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
346     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
347     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
348
349     // Conversions between floating types.
350     // RTABI chapter 4.1.2, Table 7
351     setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
352     setLibcallName(RTLIB::FPEXT_F32_F64,   "__aeabi_f2d");
353     setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
354     setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
355
356     // Integer to floating-point conversions.
357     // RTABI chapter 4.1.2, Table 8
358     setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
359     setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
360     setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
361     setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
362     setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
363     setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
364     setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
365     setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
366     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
367     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
368     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
369     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
370     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
371     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
372     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
373     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
374
375     // Long long helper functions
376     // RTABI chapter 4.2, Table 9
377     setLibcallName(RTLIB::MUL_I64,  "__aeabi_lmul");
378     setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
379     setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
380     setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
381     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
382     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
383     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
384     setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
385     setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
386     setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
387
388     // Integer division functions
389     // RTABI chapter 4.3.1
390     setLibcallName(RTLIB::SDIV_I8,  "__aeabi_idiv");
391     setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
392     setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
393     setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
394     setLibcallName(RTLIB::UDIV_I8,  "__aeabi_uidiv");
395     setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
396     setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
397     setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
398     setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
399     setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
400     setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
401     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
402     setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
403     setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
404     setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
405     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
406
407     // Memory operations
408     // RTABI chapter 4.3.4
409     setLibcallName(RTLIB::MEMCPY,  "__aeabi_memcpy");
410     setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
411     setLibcallName(RTLIB::MEMSET,  "__aeabi_memset");
412     setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
413     setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
414     setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
415   }
416
417   // Use divmod compiler-rt calls for iOS 5.0 and later.
418   if (Subtarget->getTargetTriple().isiOS() &&
419       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
420     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
421     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
422   }
423
424   if (Subtarget->isThumb1Only())
425     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
426   else
427     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
428   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
429       !Subtarget->isThumb1Only()) {
430     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
431     if (!Subtarget->isFPOnlySP())
432       addRegisterClass(MVT::f64, &ARM::DPRRegClass);
433
434     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
435   }
436
437   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
438        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
439     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
440          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
441       setTruncStoreAction((MVT::SimpleValueType)VT,
442                           (MVT::SimpleValueType)InnerVT, Expand);
443     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
444     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
445     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
446   }
447
448   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
449   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
450
451   if (Subtarget->hasNEON()) {
452     addDRTypeForNEON(MVT::v2f32);
453     addDRTypeForNEON(MVT::v8i8);
454     addDRTypeForNEON(MVT::v4i16);
455     addDRTypeForNEON(MVT::v2i32);
456     addDRTypeForNEON(MVT::v1i64);
457
458     addQRTypeForNEON(MVT::v4f32);
459     addQRTypeForNEON(MVT::v2f64);
460     addQRTypeForNEON(MVT::v16i8);
461     addQRTypeForNEON(MVT::v8i16);
462     addQRTypeForNEON(MVT::v4i32);
463     addQRTypeForNEON(MVT::v2i64);
464
465     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
466     // neither Neon nor VFP support any arithmetic operations on it.
467     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
468     // supported for v4f32.
469     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
470     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
471     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
472     // FIXME: Code duplication: FDIV and FREM are expanded always, see
473     // ARMTargetLowering::addTypeForNEON method for details.
474     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
475     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
476     // FIXME: Create unittest.
477     // In another words, find a way when "copysign" appears in DAG with vector
478     // operands.
479     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
480     // FIXME: Code duplication: SETCC has custom operation action, see
481     // ARMTargetLowering::addTypeForNEON method for details.
482     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
483     // FIXME: Create unittest for FNEG and for FABS.
484     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
485     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
486     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
487     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
488     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
489     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
490     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
491     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
492     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
493     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
494     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
495     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
496     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
497     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
498     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
499     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
500     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
501     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
502     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
503
504     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
505     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
506     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
507     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
508     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
509     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
510     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
511     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
512     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
513     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
514     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
515     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
516     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
517     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
518     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
519
520     // Mark v2f32 intrinsics.
521     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
522     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
523     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
524     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
525     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
526     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
527     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
528     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
529     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
530     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
531     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
532     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
533     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
534     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
535     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
536
537     // Neon does not support some operations on v1i64 and v2i64 types.
538     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
539     // Custom handling for some quad-vector types to detect VMULL.
540     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
541     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
542     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
543     // Custom handling for some vector types to avoid expensive expansions
544     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
545     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
546     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
547     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
548     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
549     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
550     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
551     // a destination type that is wider than the source, and nor does
552     // it have a FP_TO_[SU]INT instruction with a narrower destination than
553     // source.
554     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
555     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
556     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
557     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
558
559     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
560     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
561
562     // NEON does not have single instruction CTPOP for vectors with element
563     // types wider than 8-bits.  However, custom lowering can leverage the
564     // v8i8/v16i8 vcnt instruction.
565     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
566     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
567     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
568     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
569
570     // NEON only has FMA instructions as of VFP4.
571     if (!Subtarget->hasVFP4()) {
572       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
573       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
574     }
575
576     setTargetDAGCombine(ISD::INTRINSIC_VOID);
577     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
578     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
579     setTargetDAGCombine(ISD::SHL);
580     setTargetDAGCombine(ISD::SRL);
581     setTargetDAGCombine(ISD::SRA);
582     setTargetDAGCombine(ISD::SIGN_EXTEND);
583     setTargetDAGCombine(ISD::ZERO_EXTEND);
584     setTargetDAGCombine(ISD::ANY_EXTEND);
585     setTargetDAGCombine(ISD::SELECT_CC);
586     setTargetDAGCombine(ISD::BUILD_VECTOR);
587     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
588     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
589     setTargetDAGCombine(ISD::STORE);
590     setTargetDAGCombine(ISD::FP_TO_SINT);
591     setTargetDAGCombine(ISD::FP_TO_UINT);
592     setTargetDAGCombine(ISD::FDIV);
593
594     // It is legal to extload from v4i8 to v4i16 or v4i32.
595     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
596                   MVT::v4i16, MVT::v2i16,
597                   MVT::v2i32};
598     for (unsigned i = 0; i < 6; ++i) {
599       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
600       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
601       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
602     }
603   }
604
605   // ARM and Thumb2 support UMLAL/SMLAL.
606   if (!Subtarget->isThumb1Only())
607     setTargetDAGCombine(ISD::ADDC);
608
609
610   computeRegisterProperties();
611
612   // ARM does not have f32 extending load.
613   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
614
615   // ARM does not have i1 sign extending load.
616   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
617
618   // ARM supports all 4 flavors of integer indexed load / store.
619   if (!Subtarget->isThumb1Only()) {
620     for (unsigned im = (unsigned)ISD::PRE_INC;
621          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
622       setIndexedLoadAction(im,  MVT::i1,  Legal);
623       setIndexedLoadAction(im,  MVT::i8,  Legal);
624       setIndexedLoadAction(im,  MVT::i16, Legal);
625       setIndexedLoadAction(im,  MVT::i32, Legal);
626       setIndexedStoreAction(im, MVT::i1,  Legal);
627       setIndexedStoreAction(im, MVT::i8,  Legal);
628       setIndexedStoreAction(im, MVT::i16, Legal);
629       setIndexedStoreAction(im, MVT::i32, Legal);
630     }
631   }
632
633   // i64 operation support.
634   setOperationAction(ISD::MUL,     MVT::i64, Expand);
635   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
636   if (Subtarget->isThumb1Only()) {
637     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
638     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
639   }
640   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
641       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
642     setOperationAction(ISD::MULHS, MVT::i32, Expand);
643
644   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
645   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
646   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
647   setOperationAction(ISD::SRL,       MVT::i64, Custom);
648   setOperationAction(ISD::SRA,       MVT::i64, Custom);
649
650   if (!Subtarget->isThumb1Only()) {
651     // FIXME: We should do this for Thumb1 as well.
652     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
653     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
654     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
655     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
656   }
657
658   // ARM does not have ROTL.
659   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
660   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
661   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
662   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
663     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
664
665   // These just redirect to CTTZ and CTLZ on ARM.
666   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
667   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
668
669   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
670
671   // Only ARMv6 has BSWAP.
672   if (!Subtarget->hasV6Ops())
673     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
674
675   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
676       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
677     // These are expanded into libcalls if the cpu doesn't have HW divider.
678     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
679     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
680   }
681
682   // FIXME: Also set divmod for SREM on EABI
683   setOperationAction(ISD::SREM,  MVT::i32, Expand);
684   setOperationAction(ISD::UREM,  MVT::i32, Expand);
685   // Register based DivRem for AEABI (RTABI 4.2)
686   if (Subtarget->isTargetAEABI()) {
687     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
688     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
689     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
690     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
691     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
692     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
693     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
694     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
695
696     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
697     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
698     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
699     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
700     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
701     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
702     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
703     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
704
705     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
706     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
707   } else {
708     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
709     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
710   }
711
712   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
713   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
714   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
715   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
716   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
717
718   setOperationAction(ISD::TRAP, MVT::Other, Legal);
719
720   // Use the default implementation.
721   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
722   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
723   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
724   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
725   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
726   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
727
728   if (!Subtarget->isTargetMachO()) {
729     // Non-MachO platforms may return values in these registers via the
730     // personality function.
731     setExceptionPointerRegister(ARM::R0);
732     setExceptionSelectorRegister(ARM::R1);
733   }
734
735   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
736   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
737   // the default expansion.
738   if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
739     // ATOMIC_FENCE needs custom lowering; the other 32-bit ones are legal and
740     // handled normally.
741     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
742     // Custom lowering for 64-bit ops
743     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i64, Custom);
744     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i64, Custom);
745     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i64, Custom);
746     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i64, Custom);
747     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i64, Custom);
748     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i64, Custom);
749     setOperationAction(ISD::ATOMIC_LOAD_MIN,  MVT::i64, Custom);
750     setOperationAction(ISD::ATOMIC_LOAD_MAX,  MVT::i64, Custom);
751     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
752     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
753     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
754     // On v8, we have particularly efficient implementations of atomic fences
755     // if they can be combined with nearby atomic loads and stores.
756     if (!Subtarget->hasV8Ops()) {
757       // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
758       setInsertFencesForAtomic(true);
759     }
760     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
761   } else {
762     // If there's anything we can use as a barrier, go through custom lowering
763     // for ATOMIC_FENCE.
764     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
765                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
766
767     // Set them all for expansion, which will force libcalls.
768     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
769     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
770     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
771     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
772     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
773     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
774     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
775     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
776     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
777     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
778     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
779     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
780     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
781     // Unordered/Monotonic case.
782     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
783     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
784   }
785
786   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
787
788   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
789   if (!Subtarget->hasV6Ops()) {
790     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
791     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
792   }
793   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
794
795   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
796       !Subtarget->isThumb1Only()) {
797     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
798     // iff target supports vfp2.
799     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
800     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
801   }
802
803   // We want to custom lower some of our intrinsics.
804   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
805   if (Subtarget->isTargetDarwin()) {
806     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
807     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
808     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
809   }
810
811   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
812   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
813   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
814   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
815   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
816   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
817   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
818   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
819   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
820
821   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
822   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
823   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
824   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
825   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
826
827   // We don't support sin/cos/fmod/copysign/pow
828   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
829   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
830   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
831   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
832   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
833   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
834   setOperationAction(ISD::FREM,      MVT::f64, Expand);
835   setOperationAction(ISD::FREM,      MVT::f32, Expand);
836   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
837       !Subtarget->isThumb1Only()) {
838     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
839     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
840   }
841   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
842   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
843
844   if (!Subtarget->hasVFP4()) {
845     setOperationAction(ISD::FMA, MVT::f64, Expand);
846     setOperationAction(ISD::FMA, MVT::f32, Expand);
847   }
848
849   // Various VFP goodness
850   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
851     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
852     if (Subtarget->hasVFP2()) {
853       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
854       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
855       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
856       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
857     }
858     // Special handling for half-precision FP.
859     if (!Subtarget->hasFP16()) {
860       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
861       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
862     }
863   }
864       
865   // Combine sin / cos into one node or libcall if possible.
866   if (Subtarget->hasSinCos()) {
867     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
868     setLibcallName(RTLIB::SINCOS_F64, "sincos");
869     if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
870       // For iOS, we don't want to the normal expansion of a libcall to
871       // sincos. We want to issue a libcall to __sincos_stret.
872       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
873       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
874     }
875   }
876
877   // We have target-specific dag combine patterns for the following nodes:
878   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
879   setTargetDAGCombine(ISD::ADD);
880   setTargetDAGCombine(ISD::SUB);
881   setTargetDAGCombine(ISD::MUL);
882   setTargetDAGCombine(ISD::AND);
883   setTargetDAGCombine(ISD::OR);
884   setTargetDAGCombine(ISD::XOR);
885
886   if (Subtarget->hasV6Ops())
887     setTargetDAGCombine(ISD::SRL);
888
889   setStackPointerRegisterToSaveRestore(ARM::SP);
890
891   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
892       !Subtarget->hasVFP2())
893     setSchedulingPreference(Sched::RegPressure);
894   else
895     setSchedulingPreference(Sched::Hybrid);
896
897   //// temporary - rewrite interface to use type
898   MaxStoresPerMemset = 8;
899   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
900   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
901   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
902   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
903   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
904
905   // On ARM arguments smaller than 4 bytes are extended, so all arguments
906   // are at least 4 bytes aligned.
907   setMinStackArgumentAlignment(4);
908
909   // Prefer likely predicted branches to selects on out-of-order cores.
910   PredictableSelectIsExpensive = Subtarget->isLikeA9();
911
912   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
913 }
914
915 static void getExclusiveOperation(unsigned Size, AtomicOrdering Ord,
916                                   bool isThumb2, unsigned &LdrOpc,
917                                   unsigned &StrOpc) {
918   static const unsigned LoadBares[4][2] =  {{ARM::LDREXB, ARM::t2LDREXB},
919                                             {ARM::LDREXH, ARM::t2LDREXH},
920                                             {ARM::LDREX,  ARM::t2LDREX},
921                                             {ARM::LDREXD, ARM::t2LDREXD}};
922   static const unsigned LoadAcqs[4][2] =   {{ARM::LDAEXB, ARM::t2LDAEXB},
923                                             {ARM::LDAEXH, ARM::t2LDAEXH},
924                                             {ARM::LDAEX,  ARM::t2LDAEX},
925                                             {ARM::LDAEXD, ARM::t2LDAEXD}};
926   static const unsigned StoreBares[4][2] = {{ARM::STREXB, ARM::t2STREXB},
927                                             {ARM::STREXH, ARM::t2STREXH},
928                                             {ARM::STREX,  ARM::t2STREX},
929                                             {ARM::STREXD, ARM::t2STREXD}};
930   static const unsigned StoreRels[4][2] =  {{ARM::STLEXB, ARM::t2STLEXB},
931                                             {ARM::STLEXH, ARM::t2STLEXH},
932                                             {ARM::STLEX,  ARM::t2STLEX},
933                                             {ARM::STLEXD, ARM::t2STLEXD}};
934
935   const unsigned (*LoadOps)[2], (*StoreOps)[2];
936   if (Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent)
937     LoadOps = LoadAcqs;
938   else
939     LoadOps = LoadBares;
940
941   if (Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent)
942     StoreOps = StoreRels;
943   else
944     StoreOps = StoreBares;
945
946   assert(isPowerOf2_32(Size) && Size <= 8 &&
947          "unsupported size for atomic binary op!");
948
949   LdrOpc = LoadOps[Log2_32(Size)][isThumb2];
950   StrOpc = StoreOps[Log2_32(Size)][isThumb2];
951 }
952
953 // FIXME: It might make sense to define the representative register class as the
954 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
955 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
956 // SPR's representative would be DPR_VFP2. This should work well if register
957 // pressure tracking were modified such that a register use would increment the
958 // pressure of the register class's representative and all of it's super
959 // classes' representatives transitively. We have not implemented this because
960 // of the difficulty prior to coalescing of modeling operand register classes
961 // due to the common occurrence of cross class copies and subregister insertions
962 // and extractions.
963 std::pair<const TargetRegisterClass*, uint8_t>
964 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
965   const TargetRegisterClass *RRC = 0;
966   uint8_t Cost = 1;
967   switch (VT.SimpleTy) {
968   default:
969     return TargetLowering::findRepresentativeClass(VT);
970   // Use DPR as representative register class for all floating point
971   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
972   // the cost is 1 for both f32 and f64.
973   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
974   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
975     RRC = &ARM::DPRRegClass;
976     // When NEON is used for SP, only half of the register file is available
977     // because operations that define both SP and DP results will be constrained
978     // to the VFP2 class (D0-D15). We currently model this constraint prior to
979     // coalescing by double-counting the SP regs. See the FIXME above.
980     if (Subtarget->useNEONForSinglePrecisionFP())
981       Cost = 2;
982     break;
983   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
984   case MVT::v4f32: case MVT::v2f64:
985     RRC = &ARM::DPRRegClass;
986     Cost = 2;
987     break;
988   case MVT::v4i64:
989     RRC = &ARM::DPRRegClass;
990     Cost = 4;
991     break;
992   case MVT::v8i64:
993     RRC = &ARM::DPRRegClass;
994     Cost = 8;
995     break;
996   }
997   return std::make_pair(RRC, Cost);
998 }
999
1000 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1001   switch (Opcode) {
1002   default: return 0;
1003   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1004   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1005   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1006   case ARMISD::CALL:          return "ARMISD::CALL";
1007   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1008   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1009   case ARMISD::tCALL:         return "ARMISD::tCALL";
1010   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1011   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1012   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1013   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1014   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1015   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1016   case ARMISD::CMP:           return "ARMISD::CMP";
1017   case ARMISD::CMN:           return "ARMISD::CMN";
1018   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1019   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1020   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1021   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1022   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1023
1024   case ARMISD::CMOV:          return "ARMISD::CMOV";
1025
1026   case ARMISD::RBIT:          return "ARMISD::RBIT";
1027
1028   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
1029   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
1030   case ARMISD::SITOF:         return "ARMISD::SITOF";
1031   case ARMISD::UITOF:         return "ARMISD::UITOF";
1032
1033   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1034   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1035   case ARMISD::RRX:           return "ARMISD::RRX";
1036
1037   case ARMISD::ADDC:          return "ARMISD::ADDC";
1038   case ARMISD::ADDE:          return "ARMISD::ADDE";
1039   case ARMISD::SUBC:          return "ARMISD::SUBC";
1040   case ARMISD::SUBE:          return "ARMISD::SUBE";
1041
1042   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1043   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1044
1045   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1046   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1047
1048   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1049
1050   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1051
1052   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1053
1054   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1055
1056   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1057
1058   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1059   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1060   case ARMISD::VCGE:          return "ARMISD::VCGE";
1061   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1062   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1063   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1064   case ARMISD::VCGT:          return "ARMISD::VCGT";
1065   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1066   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1067   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1068   case ARMISD::VTST:          return "ARMISD::VTST";
1069
1070   case ARMISD::VSHL:          return "ARMISD::VSHL";
1071   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1072   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1073   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1074   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1075   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1076   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1077   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1078   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1079   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1080   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1081   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1082   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1083   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1084   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1085   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1086   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1087   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1088   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1089   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1090   case ARMISD::VDUP:          return "ARMISD::VDUP";
1091   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1092   case ARMISD::VEXT:          return "ARMISD::VEXT";
1093   case ARMISD::VREV64:        return "ARMISD::VREV64";
1094   case ARMISD::VREV32:        return "ARMISD::VREV32";
1095   case ARMISD::VREV16:        return "ARMISD::VREV16";
1096   case ARMISD::VZIP:          return "ARMISD::VZIP";
1097   case ARMISD::VUZP:          return "ARMISD::VUZP";
1098   case ARMISD::VTRN:          return "ARMISD::VTRN";
1099   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1100   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1101   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1102   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1103   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1104   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1105   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1106   case ARMISD::FMAX:          return "ARMISD::FMAX";
1107   case ARMISD::FMIN:          return "ARMISD::FMIN";
1108   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1109   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1110   case ARMISD::BFI:           return "ARMISD::BFI";
1111   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1112   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1113   case ARMISD::VBSL:          return "ARMISD::VBSL";
1114   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1115   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1116   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1117   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1118   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1119   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1120   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1121   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1122   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1123   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1124   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1125   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1126   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1127   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1128   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1129   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1130   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1131   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1132   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1133   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1134   }
1135 }
1136
1137 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1138   if (!VT.isVector()) return getPointerTy();
1139   return VT.changeVectorElementTypeToInteger();
1140 }
1141
1142 /// getRegClassFor - Return the register class that should be used for the
1143 /// specified value type.
1144 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1145   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1146   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1147   // load / store 4 to 8 consecutive D registers.
1148   if (Subtarget->hasNEON()) {
1149     if (VT == MVT::v4i64)
1150       return &ARM::QQPRRegClass;
1151     if (VT == MVT::v8i64)
1152       return &ARM::QQQQPRRegClass;
1153   }
1154   return TargetLowering::getRegClassFor(VT);
1155 }
1156
1157 // Create a fast isel object.
1158 FastISel *
1159 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1160                                   const TargetLibraryInfo *libInfo) const {
1161   return ARM::createFastISel(funcInfo, libInfo);
1162 }
1163
1164 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1165 /// be used for loads / stores from the global.
1166 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1167   return (Subtarget->isThumb1Only() ? 127 : 4095);
1168 }
1169
1170 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1171   unsigned NumVals = N->getNumValues();
1172   if (!NumVals)
1173     return Sched::RegPressure;
1174
1175   for (unsigned i = 0; i != NumVals; ++i) {
1176     EVT VT = N->getValueType(i);
1177     if (VT == MVT::Glue || VT == MVT::Other)
1178       continue;
1179     if (VT.isFloatingPoint() || VT.isVector())
1180       return Sched::ILP;
1181   }
1182
1183   if (!N->isMachineOpcode())
1184     return Sched::RegPressure;
1185
1186   // Load are scheduled for latency even if there instruction itinerary
1187   // is not available.
1188   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1189   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1190
1191   if (MCID.getNumDefs() == 0)
1192     return Sched::RegPressure;
1193   if (!Itins->isEmpty() &&
1194       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1195     return Sched::ILP;
1196
1197   return Sched::RegPressure;
1198 }
1199
1200 //===----------------------------------------------------------------------===//
1201 // Lowering Code
1202 //===----------------------------------------------------------------------===//
1203
1204 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1205 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1206   switch (CC) {
1207   default: llvm_unreachable("Unknown condition code!");
1208   case ISD::SETNE:  return ARMCC::NE;
1209   case ISD::SETEQ:  return ARMCC::EQ;
1210   case ISD::SETGT:  return ARMCC::GT;
1211   case ISD::SETGE:  return ARMCC::GE;
1212   case ISD::SETLT:  return ARMCC::LT;
1213   case ISD::SETLE:  return ARMCC::LE;
1214   case ISD::SETUGT: return ARMCC::HI;
1215   case ISD::SETUGE: return ARMCC::HS;
1216   case ISD::SETULT: return ARMCC::LO;
1217   case ISD::SETULE: return ARMCC::LS;
1218   }
1219 }
1220
1221 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1222 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1223                         ARMCC::CondCodes &CondCode2) {
1224   CondCode2 = ARMCC::AL;
1225   switch (CC) {
1226   default: llvm_unreachable("Unknown FP condition!");
1227   case ISD::SETEQ:
1228   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1229   case ISD::SETGT:
1230   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1231   case ISD::SETGE:
1232   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1233   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1234   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1235   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1236   case ISD::SETO:   CondCode = ARMCC::VC; break;
1237   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1238   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1239   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1240   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1241   case ISD::SETLT:
1242   case ISD::SETULT: CondCode = ARMCC::LT; break;
1243   case ISD::SETLE:
1244   case ISD::SETULE: CondCode = ARMCC::LE; break;
1245   case ISD::SETNE:
1246   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1247   }
1248 }
1249
1250 //===----------------------------------------------------------------------===//
1251 //                      Calling Convention Implementation
1252 //===----------------------------------------------------------------------===//
1253
1254 #include "ARMGenCallingConv.inc"
1255
1256 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1257 /// given CallingConvention value.
1258 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1259                                                  bool Return,
1260                                                  bool isVarArg) const {
1261   switch (CC) {
1262   default:
1263     llvm_unreachable("Unsupported calling convention");
1264   case CallingConv::Fast:
1265     if (Subtarget->hasVFP2() && !isVarArg) {
1266       if (!Subtarget->isAAPCS_ABI())
1267         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1268       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1269       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1270     }
1271     // Fallthrough
1272   case CallingConv::C: {
1273     // Use target triple & subtarget features to do actual dispatch.
1274     if (!Subtarget->isAAPCS_ABI())
1275       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1276     else if (Subtarget->hasVFP2() &&
1277              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1278              !isVarArg)
1279       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1280     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1281   }
1282   case CallingConv::ARM_AAPCS_VFP:
1283     if (!isVarArg)
1284       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1285     // Fallthrough
1286   case CallingConv::ARM_AAPCS:
1287     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1288   case CallingConv::ARM_APCS:
1289     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1290   case CallingConv::GHC:
1291     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1292   }
1293 }
1294
1295 /// LowerCallResult - Lower the result values of a call into the
1296 /// appropriate copies out of appropriate physical registers.
1297 SDValue
1298 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1299                                    CallingConv::ID CallConv, bool isVarArg,
1300                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1301                                    SDLoc dl, SelectionDAG &DAG,
1302                                    SmallVectorImpl<SDValue> &InVals,
1303                                    bool isThisReturn, SDValue ThisVal) const {
1304
1305   // Assign locations to each value returned by this call.
1306   SmallVector<CCValAssign, 16> RVLocs;
1307   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1308                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1309   CCInfo.AnalyzeCallResult(Ins,
1310                            CCAssignFnForNode(CallConv, /* Return*/ true,
1311                                              isVarArg));
1312
1313   // Copy all of the result registers out of their specified physreg.
1314   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1315     CCValAssign VA = RVLocs[i];
1316
1317     // Pass 'this' value directly from the argument to return value, to avoid
1318     // reg unit interference
1319     if (i == 0 && isThisReturn) {
1320       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1321              "unexpected return calling convention register assignment");
1322       InVals.push_back(ThisVal);
1323       continue;
1324     }
1325
1326     SDValue Val;
1327     if (VA.needsCustom()) {
1328       // Handle f64 or half of a v2f64.
1329       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1330                                       InFlag);
1331       Chain = Lo.getValue(1);
1332       InFlag = Lo.getValue(2);
1333       VA = RVLocs[++i]; // skip ahead to next loc
1334       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1335                                       InFlag);
1336       Chain = Hi.getValue(1);
1337       InFlag = Hi.getValue(2);
1338       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1339
1340       if (VA.getLocVT() == MVT::v2f64) {
1341         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1342         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1343                           DAG.getConstant(0, MVT::i32));
1344
1345         VA = RVLocs[++i]; // skip ahead to next loc
1346         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1347         Chain = Lo.getValue(1);
1348         InFlag = Lo.getValue(2);
1349         VA = RVLocs[++i]; // skip ahead to next loc
1350         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1351         Chain = Hi.getValue(1);
1352         InFlag = Hi.getValue(2);
1353         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1354         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1355                           DAG.getConstant(1, MVT::i32));
1356       }
1357     } else {
1358       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1359                                InFlag);
1360       Chain = Val.getValue(1);
1361       InFlag = Val.getValue(2);
1362     }
1363
1364     switch (VA.getLocInfo()) {
1365     default: llvm_unreachable("Unknown loc info!");
1366     case CCValAssign::Full: break;
1367     case CCValAssign::BCvt:
1368       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1369       break;
1370     }
1371
1372     InVals.push_back(Val);
1373   }
1374
1375   return Chain;
1376 }
1377
1378 /// LowerMemOpCallTo - Store the argument to the stack.
1379 SDValue
1380 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1381                                     SDValue StackPtr, SDValue Arg,
1382                                     SDLoc dl, SelectionDAG &DAG,
1383                                     const CCValAssign &VA,
1384                                     ISD::ArgFlagsTy Flags) const {
1385   unsigned LocMemOffset = VA.getLocMemOffset();
1386   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1387   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1388   return DAG.getStore(Chain, dl, Arg, PtrOff,
1389                       MachinePointerInfo::getStack(LocMemOffset),
1390                       false, false, 0);
1391 }
1392
1393 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1394                                          SDValue Chain, SDValue &Arg,
1395                                          RegsToPassVector &RegsToPass,
1396                                          CCValAssign &VA, CCValAssign &NextVA,
1397                                          SDValue &StackPtr,
1398                                          SmallVectorImpl<SDValue> &MemOpChains,
1399                                          ISD::ArgFlagsTy Flags) const {
1400
1401   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1402                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1403   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1404
1405   if (NextVA.isRegLoc())
1406     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1407   else {
1408     assert(NextVA.isMemLoc());
1409     if (StackPtr.getNode() == 0)
1410       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1411
1412     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1413                                            dl, DAG, NextVA,
1414                                            Flags));
1415   }
1416 }
1417
1418 /// LowerCall - Lowering a call into a callseq_start <-
1419 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1420 /// nodes.
1421 SDValue
1422 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1423                              SmallVectorImpl<SDValue> &InVals) const {
1424   SelectionDAG &DAG                     = CLI.DAG;
1425   SDLoc &dl                          = CLI.DL;
1426   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1427   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1428   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1429   SDValue Chain                         = CLI.Chain;
1430   SDValue Callee                        = CLI.Callee;
1431   bool &isTailCall                      = CLI.IsTailCall;
1432   CallingConv::ID CallConv              = CLI.CallConv;
1433   bool doesNotRet                       = CLI.DoesNotReturn;
1434   bool isVarArg                         = CLI.IsVarArg;
1435
1436   MachineFunction &MF = DAG.getMachineFunction();
1437   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1438   bool isThisReturn   = false;
1439   bool isSibCall      = false;
1440
1441   // Disable tail calls if they're not supported.
1442   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1443     isTailCall = false;
1444
1445   if (isTailCall) {
1446     // Check if it's really possible to do a tail call.
1447     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1448                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1449                                                    Outs, OutVals, Ins, DAG);
1450     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1451     // detected sibcalls.
1452     if (isTailCall) {
1453       ++NumTailCalls;
1454       isSibCall = true;
1455     }
1456   }
1457
1458   // Analyze operands of the call, assigning locations to each operand.
1459   SmallVector<CCValAssign, 16> ArgLocs;
1460   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1461                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1462   CCInfo.AnalyzeCallOperands(Outs,
1463                              CCAssignFnForNode(CallConv, /* Return*/ false,
1464                                                isVarArg));
1465
1466   // Get a count of how many bytes are to be pushed on the stack.
1467   unsigned NumBytes = CCInfo.getNextStackOffset();
1468
1469   // For tail calls, memory operands are available in our caller's stack.
1470   if (isSibCall)
1471     NumBytes = 0;
1472
1473   // Adjust the stack pointer for the new arguments...
1474   // These operations are automatically eliminated by the prolog/epilog pass
1475   if (!isSibCall)
1476     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1477                                  dl);
1478
1479   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1480
1481   RegsToPassVector RegsToPass;
1482   SmallVector<SDValue, 8> MemOpChains;
1483
1484   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1485   // of tail call optimization, arguments are handled later.
1486   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1487        i != e;
1488        ++i, ++realArgIdx) {
1489     CCValAssign &VA = ArgLocs[i];
1490     SDValue Arg = OutVals[realArgIdx];
1491     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1492     bool isByVal = Flags.isByVal();
1493
1494     // Promote the value if needed.
1495     switch (VA.getLocInfo()) {
1496     default: llvm_unreachable("Unknown loc info!");
1497     case CCValAssign::Full: break;
1498     case CCValAssign::SExt:
1499       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1500       break;
1501     case CCValAssign::ZExt:
1502       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1503       break;
1504     case CCValAssign::AExt:
1505       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1506       break;
1507     case CCValAssign::BCvt:
1508       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1509       break;
1510     }
1511
1512     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1513     if (VA.needsCustom()) {
1514       if (VA.getLocVT() == MVT::v2f64) {
1515         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1516                                   DAG.getConstant(0, MVT::i32));
1517         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1518                                   DAG.getConstant(1, MVT::i32));
1519
1520         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1521                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1522
1523         VA = ArgLocs[++i]; // skip ahead to next loc
1524         if (VA.isRegLoc()) {
1525           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1526                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1527         } else {
1528           assert(VA.isMemLoc());
1529
1530           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1531                                                  dl, DAG, VA, Flags));
1532         }
1533       } else {
1534         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1535                          StackPtr, MemOpChains, Flags);
1536       }
1537     } else if (VA.isRegLoc()) {
1538       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1539         assert(VA.getLocVT() == MVT::i32 &&
1540                "unexpected calling convention register assignment");
1541         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1542                "unexpected use of 'returned'");
1543         isThisReturn = true;
1544       }
1545       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1546     } else if (isByVal) {
1547       assert(VA.isMemLoc());
1548       unsigned offset = 0;
1549
1550       // True if this byval aggregate will be split between registers
1551       // and memory.
1552       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1553       unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1554
1555       if (CurByValIdx < ByValArgsCount) {
1556
1557         unsigned RegBegin, RegEnd;
1558         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1559
1560         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1561         unsigned int i, j;
1562         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1563           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1564           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1565           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1566                                      MachinePointerInfo(),
1567                                      false, false, false,
1568                                      DAG.InferPtrAlignment(AddArg));
1569           MemOpChains.push_back(Load.getValue(1));
1570           RegsToPass.push_back(std::make_pair(j, Load));
1571         }
1572
1573         // If parameter size outsides register area, "offset" value
1574         // helps us to calculate stack slot for remained part properly.
1575         offset = RegEnd - RegBegin;
1576
1577         CCInfo.nextInRegsParam();
1578       }
1579
1580       if (Flags.getByValSize() > 4*offset) {
1581         unsigned LocMemOffset = VA.getLocMemOffset();
1582         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1583         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1584                                   StkPtrOff);
1585         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1586         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1587         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1588                                            MVT::i32);
1589         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1590
1591         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1592         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1593         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1594                                           Ops, array_lengthof(Ops)));
1595       }
1596     } else if (!isSibCall) {
1597       assert(VA.isMemLoc());
1598
1599       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1600                                              dl, DAG, VA, Flags));
1601     }
1602   }
1603
1604   if (!MemOpChains.empty())
1605     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1606                         &MemOpChains[0], MemOpChains.size());
1607
1608   // Build a sequence of copy-to-reg nodes chained together with token chain
1609   // and flag operands which copy the outgoing args into the appropriate regs.
1610   SDValue InFlag;
1611   // Tail call byval lowering might overwrite argument registers so in case of
1612   // tail call optimization the copies to registers are lowered later.
1613   if (!isTailCall)
1614     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1615       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1616                                RegsToPass[i].second, InFlag);
1617       InFlag = Chain.getValue(1);
1618     }
1619
1620   // For tail calls lower the arguments to the 'real' stack slot.
1621   if (isTailCall) {
1622     // Force all the incoming stack arguments to be loaded from the stack
1623     // before any new outgoing arguments are stored to the stack, because the
1624     // outgoing stack slots may alias the incoming argument stack slots, and
1625     // the alias isn't otherwise explicit. This is slightly more conservative
1626     // than necessary, because it means that each store effectively depends
1627     // on every argument instead of just those arguments it would clobber.
1628
1629     // Do not flag preceding copytoreg stuff together with the following stuff.
1630     InFlag = SDValue();
1631     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1632       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1633                                RegsToPass[i].second, InFlag);
1634       InFlag = Chain.getValue(1);
1635     }
1636     InFlag = SDValue();
1637   }
1638
1639   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1640   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1641   // node so that legalize doesn't hack it.
1642   bool isDirect = false;
1643   bool isARMFunc = false;
1644   bool isLocalARMFunc = false;
1645   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1646
1647   if (EnableARMLongCalls) {
1648     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1649             && "long-calls with non-static relocation model!");
1650     // Handle a global address or an external symbol. If it's not one of
1651     // those, the target's already in a register, so we don't need to do
1652     // anything extra.
1653     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1654       const GlobalValue *GV = G->getGlobal();
1655       // Create a constant pool entry for the callee address
1656       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1657       ARMConstantPoolValue *CPV =
1658         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1659
1660       // Get the address of the callee into a register
1661       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1662       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1663       Callee = DAG.getLoad(getPointerTy(), dl,
1664                            DAG.getEntryNode(), CPAddr,
1665                            MachinePointerInfo::getConstantPool(),
1666                            false, false, false, 0);
1667     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1668       const char *Sym = S->getSymbol();
1669
1670       // Create a constant pool entry for the callee address
1671       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1672       ARMConstantPoolValue *CPV =
1673         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1674                                       ARMPCLabelIndex, 0);
1675       // Get the address of the callee into a register
1676       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1677       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1678       Callee = DAG.getLoad(getPointerTy(), dl,
1679                            DAG.getEntryNode(), CPAddr,
1680                            MachinePointerInfo::getConstantPool(),
1681                            false, false, false, 0);
1682     }
1683   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1684     const GlobalValue *GV = G->getGlobal();
1685     isDirect = true;
1686     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1687     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1688                    getTargetMachine().getRelocationModel() != Reloc::Static;
1689     isARMFunc = !Subtarget->isThumb() || isStub;
1690     // ARM call to a local ARM function is predicable.
1691     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1692     // tBX takes a register source operand.
1693     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1694       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1695       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1696                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy()));
1697     } else {
1698       // On ELF targets for PIC code, direct calls should go through the PLT
1699       unsigned OpFlags = 0;
1700       if (Subtarget->isTargetELF() &&
1701           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1702         OpFlags = ARMII::MO_PLT;
1703       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1704     }
1705   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1706     isDirect = true;
1707     bool isStub = Subtarget->isTargetMachO() &&
1708                   getTargetMachine().getRelocationModel() != Reloc::Static;
1709     isARMFunc = !Subtarget->isThumb() || isStub;
1710     // tBX takes a register source operand.
1711     const char *Sym = S->getSymbol();
1712     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1713       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1714       ARMConstantPoolValue *CPV =
1715         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1716                                       ARMPCLabelIndex, 4);
1717       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1718       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1719       Callee = DAG.getLoad(getPointerTy(), dl,
1720                            DAG.getEntryNode(), CPAddr,
1721                            MachinePointerInfo::getConstantPool(),
1722                            false, false, false, 0);
1723       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1724       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1725                            getPointerTy(), Callee, PICLabel);
1726     } else {
1727       unsigned OpFlags = 0;
1728       // On ELF targets for PIC code, direct calls should go through the PLT
1729       if (Subtarget->isTargetELF() &&
1730                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1731         OpFlags = ARMII::MO_PLT;
1732       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1733     }
1734   }
1735
1736   // FIXME: handle tail calls differently.
1737   unsigned CallOpc;
1738   bool HasMinSizeAttr = Subtarget->isMinSize();
1739   if (Subtarget->isThumb()) {
1740     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1741       CallOpc = ARMISD::CALL_NOLINK;
1742     else
1743       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1744   } else {
1745     if (!isDirect && !Subtarget->hasV5TOps())
1746       CallOpc = ARMISD::CALL_NOLINK;
1747     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1748                // Emit regular call when code size is the priority
1749                !HasMinSizeAttr)
1750       // "mov lr, pc; b _foo" to avoid confusing the RSP
1751       CallOpc = ARMISD::CALL_NOLINK;
1752     else
1753       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1754   }
1755
1756   std::vector<SDValue> Ops;
1757   Ops.push_back(Chain);
1758   Ops.push_back(Callee);
1759
1760   // Add argument registers to the end of the list so that they are known live
1761   // into the call.
1762   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1763     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1764                                   RegsToPass[i].second.getValueType()));
1765
1766   // Add a register mask operand representing the call-preserved registers.
1767   if (!isTailCall) {
1768     const uint32_t *Mask;
1769     const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1770     const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1771     if (isThisReturn) {
1772       // For 'this' returns, use the R0-preserving mask if applicable
1773       Mask = ARI->getThisReturnPreservedMask(CallConv);
1774       if (!Mask) {
1775         // Set isThisReturn to false if the calling convention is not one that
1776         // allows 'returned' to be modeled in this way, so LowerCallResult does
1777         // not try to pass 'this' straight through
1778         isThisReturn = false;
1779         Mask = ARI->getCallPreservedMask(CallConv);
1780       }
1781     } else
1782       Mask = ARI->getCallPreservedMask(CallConv);
1783
1784     assert(Mask && "Missing call preserved mask for calling convention");
1785     Ops.push_back(DAG.getRegisterMask(Mask));
1786   }
1787
1788   if (InFlag.getNode())
1789     Ops.push_back(InFlag);
1790
1791   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1792   if (isTailCall)
1793     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1794
1795   // Returns a chain and a flag for retval copy to use.
1796   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1797   InFlag = Chain.getValue(1);
1798
1799   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1800                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1801   if (!Ins.empty())
1802     InFlag = Chain.getValue(1);
1803
1804   // Handle result values, copying them out of physregs into vregs that we
1805   // return.
1806   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1807                          InVals, isThisReturn,
1808                          isThisReturn ? OutVals[0] : SDValue());
1809 }
1810
1811 /// HandleByVal - Every parameter *after* a byval parameter is passed
1812 /// on the stack.  Remember the next parameter register to allocate,
1813 /// and then confiscate the rest of the parameter registers to insure
1814 /// this.
1815 void
1816 ARMTargetLowering::HandleByVal(
1817     CCState *State, unsigned &size, unsigned Align) const {
1818   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1819   assert((State->getCallOrPrologue() == Prologue ||
1820           State->getCallOrPrologue() == Call) &&
1821          "unhandled ParmContext");
1822
1823   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1824     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1825       unsigned AlignInRegs = Align / 4;
1826       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1827       for (unsigned i = 0; i < Waste; ++i)
1828         reg = State->AllocateReg(GPRArgRegs, 4);
1829     }
1830     if (reg != 0) {
1831       unsigned excess = 4 * (ARM::R4 - reg);
1832
1833       // Special case when NSAA != SP and parameter size greater than size of
1834       // all remained GPR regs. In that case we can't split parameter, we must
1835       // send it to stack. We also must set NCRN to R4, so waste all
1836       // remained registers.
1837       const unsigned NSAAOffset = State->getNextStackOffset();
1838       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1839         while (State->AllocateReg(GPRArgRegs, 4))
1840           ;
1841         return;
1842       }
1843
1844       // First register for byval parameter is the first register that wasn't
1845       // allocated before this method call, so it would be "reg".
1846       // If parameter is small enough to be saved in range [reg, r4), then
1847       // the end (first after last) register would be reg + param-size-in-regs,
1848       // else parameter would be splitted between registers and stack,
1849       // end register would be r4 in this case.
1850       unsigned ByValRegBegin = reg;
1851       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1852       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1853       // Note, first register is allocated in the beginning of function already,
1854       // allocate remained amount of registers we need.
1855       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1856         State->AllocateReg(GPRArgRegs, 4);
1857       // A byval parameter that is split between registers and memory needs its
1858       // size truncated here.
1859       // In the case where the entire structure fits in registers, we set the
1860       // size in memory to zero.
1861       if (size < excess)
1862         size = 0;
1863       else
1864         size -= excess;
1865     }
1866   }
1867 }
1868
1869 /// MatchingStackOffset - Return true if the given stack call argument is
1870 /// already available in the same position (relatively) of the caller's
1871 /// incoming argument stack.
1872 static
1873 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1874                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1875                          const TargetInstrInfo *TII) {
1876   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1877   int FI = INT_MAX;
1878   if (Arg.getOpcode() == ISD::CopyFromReg) {
1879     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1880     if (!TargetRegisterInfo::isVirtualRegister(VR))
1881       return false;
1882     MachineInstr *Def = MRI->getVRegDef(VR);
1883     if (!Def)
1884       return false;
1885     if (!Flags.isByVal()) {
1886       if (!TII->isLoadFromStackSlot(Def, FI))
1887         return false;
1888     } else {
1889       return false;
1890     }
1891   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1892     if (Flags.isByVal())
1893       // ByVal argument is passed in as a pointer but it's now being
1894       // dereferenced. e.g.
1895       // define @foo(%struct.X* %A) {
1896       //   tail call @bar(%struct.X* byval %A)
1897       // }
1898       return false;
1899     SDValue Ptr = Ld->getBasePtr();
1900     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1901     if (!FINode)
1902       return false;
1903     FI = FINode->getIndex();
1904   } else
1905     return false;
1906
1907   assert(FI != INT_MAX);
1908   if (!MFI->isFixedObjectIndex(FI))
1909     return false;
1910   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1911 }
1912
1913 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1914 /// for tail call optimization. Targets which want to do tail call
1915 /// optimization should implement this function.
1916 bool
1917 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1918                                                      CallingConv::ID CalleeCC,
1919                                                      bool isVarArg,
1920                                                      bool isCalleeStructRet,
1921                                                      bool isCallerStructRet,
1922                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1923                                     const SmallVectorImpl<SDValue> &OutVals,
1924                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1925                                                      SelectionDAG& DAG) const {
1926   const Function *CallerF = DAG.getMachineFunction().getFunction();
1927   CallingConv::ID CallerCC = CallerF->getCallingConv();
1928   bool CCMatch = CallerCC == CalleeCC;
1929
1930   // Look for obvious safe cases to perform tail call optimization that do not
1931   // require ABI changes. This is what gcc calls sibcall.
1932
1933   // Do not sibcall optimize vararg calls unless the call site is not passing
1934   // any arguments.
1935   if (isVarArg && !Outs.empty())
1936     return false;
1937
1938   // Exception-handling functions need a special set of instructions to indicate
1939   // a return to the hardware. Tail-calling another function would probably
1940   // break this.
1941   if (CallerF->hasFnAttribute("interrupt"))
1942     return false;
1943
1944   // Also avoid sibcall optimization if either caller or callee uses struct
1945   // return semantics.
1946   if (isCalleeStructRet || isCallerStructRet)
1947     return false;
1948
1949   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1950   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1951   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1952   // support in the assembler and linker to be used. This would need to be
1953   // fixed to fully support tail calls in Thumb1.
1954   //
1955   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1956   // LR.  This means if we need to reload LR, it takes an extra instructions,
1957   // which outweighs the value of the tail call; but here we don't know yet
1958   // whether LR is going to be used.  Probably the right approach is to
1959   // generate the tail call here and turn it back into CALL/RET in
1960   // emitEpilogue if LR is used.
1961
1962   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1963   // but we need to make sure there are enough registers; the only valid
1964   // registers are the 4 used for parameters.  We don't currently do this
1965   // case.
1966   if (Subtarget->isThumb1Only())
1967     return false;
1968
1969   // If the calling conventions do not match, then we'd better make sure the
1970   // results are returned in the same way as what the caller expects.
1971   if (!CCMatch) {
1972     SmallVector<CCValAssign, 16> RVLocs1;
1973     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1974                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1975     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1976
1977     SmallVector<CCValAssign, 16> RVLocs2;
1978     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1979                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1980     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1981
1982     if (RVLocs1.size() != RVLocs2.size())
1983       return false;
1984     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1985       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1986         return false;
1987       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1988         return false;
1989       if (RVLocs1[i].isRegLoc()) {
1990         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1991           return false;
1992       } else {
1993         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1994           return false;
1995       }
1996     }
1997   }
1998
1999   // If Caller's vararg or byval argument has been split between registers and
2000   // stack, do not perform tail call, since part of the argument is in caller's
2001   // local frame.
2002   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2003                                       getInfo<ARMFunctionInfo>();
2004   if (AFI_Caller->getArgRegsSaveSize())
2005     return false;
2006
2007   // If the callee takes no arguments then go on to check the results of the
2008   // call.
2009   if (!Outs.empty()) {
2010     // Check if stack adjustment is needed. For now, do not do this if any
2011     // argument is passed on the stack.
2012     SmallVector<CCValAssign, 16> ArgLocs;
2013     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2014                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
2015     CCInfo.AnalyzeCallOperands(Outs,
2016                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2017     if (CCInfo.getNextStackOffset()) {
2018       MachineFunction &MF = DAG.getMachineFunction();
2019
2020       // Check if the arguments are already laid out in the right way as
2021       // the caller's fixed stack objects.
2022       MachineFrameInfo *MFI = MF.getFrameInfo();
2023       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2024       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2025       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2026            i != e;
2027            ++i, ++realArgIdx) {
2028         CCValAssign &VA = ArgLocs[i];
2029         EVT RegVT = VA.getLocVT();
2030         SDValue Arg = OutVals[realArgIdx];
2031         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2032         if (VA.getLocInfo() == CCValAssign::Indirect)
2033           return false;
2034         if (VA.needsCustom()) {
2035           // f64 and vector types are split into multiple registers or
2036           // register/stack-slot combinations.  The types will not match
2037           // the registers; give up on memory f64 refs until we figure
2038           // out what to do about this.
2039           if (!VA.isRegLoc())
2040             return false;
2041           if (!ArgLocs[++i].isRegLoc())
2042             return false;
2043           if (RegVT == MVT::v2f64) {
2044             if (!ArgLocs[++i].isRegLoc())
2045               return false;
2046             if (!ArgLocs[++i].isRegLoc())
2047               return false;
2048           }
2049         } else if (!VA.isRegLoc()) {
2050           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2051                                    MFI, MRI, TII))
2052             return false;
2053         }
2054       }
2055     }
2056   }
2057
2058   return true;
2059 }
2060
2061 bool
2062 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2063                                   MachineFunction &MF, bool isVarArg,
2064                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2065                                   LLVMContext &Context) const {
2066   SmallVector<CCValAssign, 16> RVLocs;
2067   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2068   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2069                                                     isVarArg));
2070 }
2071
2072 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2073                                     SDLoc DL, SelectionDAG &DAG) {
2074   const MachineFunction &MF = DAG.getMachineFunction();
2075   const Function *F = MF.getFunction();
2076
2077   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2078
2079   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2080   // version of the "preferred return address". These offsets affect the return
2081   // instruction if this is a return from PL1 without hypervisor extensions.
2082   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2083   //    SWI:     0      "subs pc, lr, #0"
2084   //    ABORT:   +4     "subs pc, lr, #4"
2085   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2086   // UNDEF varies depending on where the exception came from ARM or Thumb
2087   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2088
2089   int64_t LROffset;
2090   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2091       IntKind == "ABORT")
2092     LROffset = 4;
2093   else if (IntKind == "SWI" || IntKind == "UNDEF")
2094     LROffset = 0;
2095   else
2096     report_fatal_error("Unsupported interrupt attribute. If present, value "
2097                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2098
2099   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2100
2101   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other,
2102                      RetOps.data(), RetOps.size());
2103 }
2104
2105 SDValue
2106 ARMTargetLowering::LowerReturn(SDValue Chain,
2107                                CallingConv::ID CallConv, bool isVarArg,
2108                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2109                                const SmallVectorImpl<SDValue> &OutVals,
2110                                SDLoc dl, SelectionDAG &DAG) const {
2111
2112   // CCValAssign - represent the assignment of the return value to a location.
2113   SmallVector<CCValAssign, 16> RVLocs;
2114
2115   // CCState - Info about the registers and stack slots.
2116   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2117                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2118
2119   // Analyze outgoing return values.
2120   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2121                                                isVarArg));
2122
2123   SDValue Flag;
2124   SmallVector<SDValue, 4> RetOps;
2125   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2126
2127   // Copy the result values into the output registers.
2128   for (unsigned i = 0, realRVLocIdx = 0;
2129        i != RVLocs.size();
2130        ++i, ++realRVLocIdx) {
2131     CCValAssign &VA = RVLocs[i];
2132     assert(VA.isRegLoc() && "Can only return in registers!");
2133
2134     SDValue Arg = OutVals[realRVLocIdx];
2135
2136     switch (VA.getLocInfo()) {
2137     default: llvm_unreachable("Unknown loc info!");
2138     case CCValAssign::Full: break;
2139     case CCValAssign::BCvt:
2140       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2141       break;
2142     }
2143
2144     if (VA.needsCustom()) {
2145       if (VA.getLocVT() == MVT::v2f64) {
2146         // Extract the first half and return it in two registers.
2147         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2148                                    DAG.getConstant(0, MVT::i32));
2149         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2150                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2151
2152         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
2153         Flag = Chain.getValue(1);
2154         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2155         VA = RVLocs[++i]; // skip ahead to next loc
2156         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2157                                  HalfGPRs.getValue(1), Flag);
2158         Flag = Chain.getValue(1);
2159         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2160         VA = RVLocs[++i]; // skip ahead to next loc
2161
2162         // Extract the 2nd half and fall through to handle it as an f64 value.
2163         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2164                           DAG.getConstant(1, MVT::i32));
2165       }
2166       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2167       // available.
2168       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2169                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
2170       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
2171       Flag = Chain.getValue(1);
2172       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2173       VA = RVLocs[++i]; // skip ahead to next loc
2174       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
2175                                Flag);
2176     } else
2177       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2178
2179     // Guarantee that all emitted copies are
2180     // stuck together, avoiding something bad.
2181     Flag = Chain.getValue(1);
2182     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2183   }
2184
2185   // Update chain and glue.
2186   RetOps[0] = Chain;
2187   if (Flag.getNode())
2188     RetOps.push_back(Flag);
2189
2190   // CPUs which aren't M-class use a special sequence to return from
2191   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2192   // though we use "subs pc, lr, #N").
2193   //
2194   // M-class CPUs actually use a normal return sequence with a special
2195   // (hardware-provided) value in LR, so the normal code path works.
2196   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2197       !Subtarget->isMClass()) {
2198     if (Subtarget->isThumb1Only())
2199       report_fatal_error("interrupt attribute is not supported in Thumb1");
2200     return LowerInterruptReturn(RetOps, dl, DAG);
2201   }
2202
2203   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
2204                      RetOps.data(), RetOps.size());
2205 }
2206
2207 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2208   if (N->getNumValues() != 1)
2209     return false;
2210   if (!N->hasNUsesOfValue(1, 0))
2211     return false;
2212
2213   SDValue TCChain = Chain;
2214   SDNode *Copy = *N->use_begin();
2215   if (Copy->getOpcode() == ISD::CopyToReg) {
2216     // If the copy has a glue operand, we conservatively assume it isn't safe to
2217     // perform a tail call.
2218     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2219       return false;
2220     TCChain = Copy->getOperand(0);
2221   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2222     SDNode *VMov = Copy;
2223     // f64 returned in a pair of GPRs.
2224     SmallPtrSet<SDNode*, 2> Copies;
2225     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2226          UI != UE; ++UI) {
2227       if (UI->getOpcode() != ISD::CopyToReg)
2228         return false;
2229       Copies.insert(*UI);
2230     }
2231     if (Copies.size() > 2)
2232       return false;
2233
2234     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2235          UI != UE; ++UI) {
2236       SDValue UseChain = UI->getOperand(0);
2237       if (Copies.count(UseChain.getNode()))
2238         // Second CopyToReg
2239         Copy = *UI;
2240       else
2241         // First CopyToReg
2242         TCChain = UseChain;
2243     }
2244   } else if (Copy->getOpcode() == ISD::BITCAST) {
2245     // f32 returned in a single GPR.
2246     if (!Copy->hasOneUse())
2247       return false;
2248     Copy = *Copy->use_begin();
2249     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2250       return false;
2251     TCChain = Copy->getOperand(0);
2252   } else {
2253     return false;
2254   }
2255
2256   bool HasRet = false;
2257   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2258        UI != UE; ++UI) {
2259     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2260         UI->getOpcode() != ARMISD::INTRET_FLAG)
2261       return false;
2262     HasRet = true;
2263   }
2264
2265   if (!HasRet)
2266     return false;
2267
2268   Chain = TCChain;
2269   return true;
2270 }
2271
2272 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2273   if (!Subtarget->supportsTailCall())
2274     return false;
2275
2276   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2277     return false;
2278
2279   return !Subtarget->isThumb1Only();
2280 }
2281
2282 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2283 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2284 // one of the above mentioned nodes. It has to be wrapped because otherwise
2285 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2286 // be used to form addressing mode. These wrapped nodes will be selected
2287 // into MOVi.
2288 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2289   EVT PtrVT = Op.getValueType();
2290   // FIXME there is no actual debug info here
2291   SDLoc dl(Op);
2292   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2293   SDValue Res;
2294   if (CP->isMachineConstantPoolEntry())
2295     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2296                                     CP->getAlignment());
2297   else
2298     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2299                                     CP->getAlignment());
2300   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2301 }
2302
2303 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2304   return MachineJumpTableInfo::EK_Inline;
2305 }
2306
2307 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2308                                              SelectionDAG &DAG) const {
2309   MachineFunction &MF = DAG.getMachineFunction();
2310   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2311   unsigned ARMPCLabelIndex = 0;
2312   SDLoc DL(Op);
2313   EVT PtrVT = getPointerTy();
2314   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2315   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2316   SDValue CPAddr;
2317   if (RelocM == Reloc::Static) {
2318     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2319   } else {
2320     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2321     ARMPCLabelIndex = AFI->createPICLabelUId();
2322     ARMConstantPoolValue *CPV =
2323       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2324                                       ARMCP::CPBlockAddress, PCAdj);
2325     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2326   }
2327   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2328   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2329                                MachinePointerInfo::getConstantPool(),
2330                                false, false, false, 0);
2331   if (RelocM == Reloc::Static)
2332     return Result;
2333   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2334   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2335 }
2336
2337 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2338 SDValue
2339 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2340                                                  SelectionDAG &DAG) const {
2341   SDLoc dl(GA);
2342   EVT PtrVT = getPointerTy();
2343   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2344   MachineFunction &MF = DAG.getMachineFunction();
2345   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2346   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2347   ARMConstantPoolValue *CPV =
2348     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2349                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2350   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2351   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2352   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2353                          MachinePointerInfo::getConstantPool(),
2354                          false, false, false, 0);
2355   SDValue Chain = Argument.getValue(1);
2356
2357   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2358   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2359
2360   // call __tls_get_addr.
2361   ArgListTy Args;
2362   ArgListEntry Entry;
2363   Entry.Node = Argument;
2364   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2365   Args.push_back(Entry);
2366   // FIXME: is there useful debug info available here?
2367   TargetLowering::CallLoweringInfo CLI(Chain,
2368                 (Type *) Type::getInt32Ty(*DAG.getContext()),
2369                 false, false, false, false,
2370                 0, CallingConv::C, /*isTailCall=*/false,
2371                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2372                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2373   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2374   return CallResult.first;
2375 }
2376
2377 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2378 // "local exec" model.
2379 SDValue
2380 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2381                                         SelectionDAG &DAG,
2382                                         TLSModel::Model model) const {
2383   const GlobalValue *GV = GA->getGlobal();
2384   SDLoc dl(GA);
2385   SDValue Offset;
2386   SDValue Chain = DAG.getEntryNode();
2387   EVT PtrVT = getPointerTy();
2388   // Get the Thread Pointer
2389   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2390
2391   if (model == TLSModel::InitialExec) {
2392     MachineFunction &MF = DAG.getMachineFunction();
2393     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2394     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2395     // Initial exec model.
2396     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2397     ARMConstantPoolValue *CPV =
2398       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2399                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2400                                       true);
2401     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2402     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2403     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2404                          MachinePointerInfo::getConstantPool(),
2405                          false, false, false, 0);
2406     Chain = Offset.getValue(1);
2407
2408     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2409     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2410
2411     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2412                          MachinePointerInfo::getConstantPool(),
2413                          false, false, false, 0);
2414   } else {
2415     // local exec model
2416     assert(model == TLSModel::LocalExec);
2417     ARMConstantPoolValue *CPV =
2418       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2419     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2420     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2421     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2422                          MachinePointerInfo::getConstantPool(),
2423                          false, false, false, 0);
2424   }
2425
2426   // The address of the thread local variable is the add of the thread
2427   // pointer with the offset of the variable.
2428   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2429 }
2430
2431 SDValue
2432 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2433   // TODO: implement the "local dynamic" model
2434   assert(Subtarget->isTargetELF() &&
2435          "TLS not implemented for non-ELF targets");
2436   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2437
2438   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2439
2440   switch (model) {
2441     case TLSModel::GeneralDynamic:
2442     case TLSModel::LocalDynamic:
2443       return LowerToTLSGeneralDynamicModel(GA, DAG);
2444     case TLSModel::InitialExec:
2445     case TLSModel::LocalExec:
2446       return LowerToTLSExecModels(GA, DAG, model);
2447   }
2448   llvm_unreachable("bogus TLS model");
2449 }
2450
2451 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2452                                                  SelectionDAG &DAG) const {
2453   EVT PtrVT = getPointerTy();
2454   SDLoc dl(Op);
2455   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2456   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2457     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2458     ARMConstantPoolValue *CPV =
2459       ARMConstantPoolConstant::Create(GV,
2460                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2461     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2462     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2463     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2464                                  CPAddr,
2465                                  MachinePointerInfo::getConstantPool(),
2466                                  false, false, false, 0);
2467     SDValue Chain = Result.getValue(1);
2468     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2469     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2470     if (!UseGOTOFF)
2471       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2472                            MachinePointerInfo::getGOT(),
2473                            false, false, false, 0);
2474     return Result;
2475   }
2476
2477   // If we have T2 ops, we can materialize the address directly via movt/movw
2478   // pair. This is always cheaper.
2479   if (Subtarget->useMovt()) {
2480     ++NumMovwMovt;
2481     // FIXME: Once remat is capable of dealing with instructions with register
2482     // operands, expand this into two nodes.
2483     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2484                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2485   } else {
2486     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2487     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2488     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2489                        MachinePointerInfo::getConstantPool(),
2490                        false, false, false, 0);
2491   }
2492 }
2493
2494 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2495                                                     SelectionDAG &DAG) const {
2496   EVT PtrVT = getPointerTy();
2497   SDLoc dl(Op);
2498   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2499   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2500
2501   if (Subtarget->useMovt())
2502     ++NumMovwMovt;
2503
2504   // FIXME: Once remat is capable of dealing with instructions with register
2505   // operands, expand this into multiple nodes
2506   unsigned Wrapper =
2507       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2508
2509   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2510   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2511
2512   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2513     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2514                          MachinePointerInfo::getGOT(), false, false, false, 0);
2515   return Result;
2516 }
2517
2518 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2519                                                     SelectionDAG &DAG) const {
2520   assert(Subtarget->isTargetELF() &&
2521          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2522   MachineFunction &MF = DAG.getMachineFunction();
2523   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2524   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2525   EVT PtrVT = getPointerTy();
2526   SDLoc dl(Op);
2527   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2528   ARMConstantPoolValue *CPV =
2529     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2530                                   ARMPCLabelIndex, PCAdj);
2531   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2532   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2533   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2534                                MachinePointerInfo::getConstantPool(),
2535                                false, false, false, 0);
2536   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2537   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2538 }
2539
2540 SDValue
2541 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2542   SDLoc dl(Op);
2543   SDValue Val = DAG.getConstant(0, MVT::i32);
2544   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2545                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2546                      Op.getOperand(1), Val);
2547 }
2548
2549 SDValue
2550 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2551   SDLoc dl(Op);
2552   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2553                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2554 }
2555
2556 SDValue
2557 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2558                                           const ARMSubtarget *Subtarget) const {
2559   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2560   SDLoc dl(Op);
2561   switch (IntNo) {
2562   default: return SDValue();    // Don't custom lower most intrinsics.
2563   case Intrinsic::arm_thread_pointer: {
2564     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2565     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2566   }
2567   case Intrinsic::eh_sjlj_lsda: {
2568     MachineFunction &MF = DAG.getMachineFunction();
2569     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2570     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2571     EVT PtrVT = getPointerTy();
2572     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2573     SDValue CPAddr;
2574     unsigned PCAdj = (RelocM != Reloc::PIC_)
2575       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2576     ARMConstantPoolValue *CPV =
2577       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2578                                       ARMCP::CPLSDA, PCAdj);
2579     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2580     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2581     SDValue Result =
2582       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2583                   MachinePointerInfo::getConstantPool(),
2584                   false, false, false, 0);
2585
2586     if (RelocM == Reloc::PIC_) {
2587       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2588       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2589     }
2590     return Result;
2591   }
2592   case Intrinsic::arm_neon_vmulls:
2593   case Intrinsic::arm_neon_vmullu: {
2594     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2595       ? ARMISD::VMULLs : ARMISD::VMULLu;
2596     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2597                        Op.getOperand(1), Op.getOperand(2));
2598   }
2599   }
2600 }
2601
2602 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2603                                  const ARMSubtarget *Subtarget) {
2604   // FIXME: handle "fence singlethread" more efficiently.
2605   SDLoc dl(Op);
2606   if (!Subtarget->hasDataBarrier()) {
2607     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2608     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2609     // here.
2610     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2611            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2612     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2613                        DAG.getConstant(0, MVT::i32));
2614   }
2615
2616   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2617   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2618   unsigned Domain = ARM_MB::ISH;
2619   if (Subtarget->isMClass()) {
2620     // Only a full system barrier exists in the M-class architectures.
2621     Domain = ARM_MB::SY;
2622   } else if (Subtarget->isSwift() && Ord == Release) {
2623     // Swift happens to implement ISHST barriers in a way that's compatible with
2624     // Release semantics but weaker than ISH so we'd be fools not to use
2625     // it. Beware: other processors probably don't!
2626     Domain = ARM_MB::ISHST;
2627   }
2628
2629   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2630                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2631                      DAG.getConstant(Domain, MVT::i32));
2632 }
2633
2634 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2635                              const ARMSubtarget *Subtarget) {
2636   // ARM pre v5TE and Thumb1 does not have preload instructions.
2637   if (!(Subtarget->isThumb2() ||
2638         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2639     // Just preserve the chain.
2640     return Op.getOperand(0);
2641
2642   SDLoc dl(Op);
2643   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2644   if (!isRead &&
2645       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2646     // ARMv7 with MP extension has PLDW.
2647     return Op.getOperand(0);
2648
2649   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2650   if (Subtarget->isThumb()) {
2651     // Invert the bits.
2652     isRead = ~isRead & 1;
2653     isData = ~isData & 1;
2654   }
2655
2656   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2657                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2658                      DAG.getConstant(isData, MVT::i32));
2659 }
2660
2661 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2662   MachineFunction &MF = DAG.getMachineFunction();
2663   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2664
2665   // vastart just stores the address of the VarArgsFrameIndex slot into the
2666   // memory location argument.
2667   SDLoc dl(Op);
2668   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2669   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2670   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2671   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2672                       MachinePointerInfo(SV), false, false, 0);
2673 }
2674
2675 SDValue
2676 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2677                                         SDValue &Root, SelectionDAG &DAG,
2678                                         SDLoc dl) const {
2679   MachineFunction &MF = DAG.getMachineFunction();
2680   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2681
2682   const TargetRegisterClass *RC;
2683   if (AFI->isThumb1OnlyFunction())
2684     RC = &ARM::tGPRRegClass;
2685   else
2686     RC = &ARM::GPRRegClass;
2687
2688   // Transform the arguments stored in physical registers into virtual ones.
2689   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2690   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2691
2692   SDValue ArgValue2;
2693   if (NextVA.isMemLoc()) {
2694     MachineFrameInfo *MFI = MF.getFrameInfo();
2695     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2696
2697     // Create load node to retrieve arguments from the stack.
2698     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2699     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2700                             MachinePointerInfo::getFixedStack(FI),
2701                             false, false, false, 0);
2702   } else {
2703     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2704     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2705   }
2706
2707   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2708 }
2709
2710 void
2711 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2712                                   unsigned InRegsParamRecordIdx,
2713                                   unsigned ArgSize,
2714                                   unsigned &ArgRegsSize,
2715                                   unsigned &ArgRegsSaveSize)
2716   const {
2717   unsigned NumGPRs;
2718   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2719     unsigned RBegin, REnd;
2720     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2721     NumGPRs = REnd - RBegin;
2722   } else {
2723     unsigned int firstUnalloced;
2724     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2725                                                 sizeof(GPRArgRegs) /
2726                                                 sizeof(GPRArgRegs[0]));
2727     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2728   }
2729
2730   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2731   ArgRegsSize = NumGPRs * 4;
2732
2733   // If parameter is split between stack and GPRs...
2734   if (NumGPRs && Align > 4 &&
2735       (ArgRegsSize < ArgSize ||
2736         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2737     // Add padding for part of param recovered from GPRs.  For example,
2738     // if Align == 8, its last byte must be at address K*8 - 1.
2739     // We need to do it, since remained (stack) part of parameter has
2740     // stack alignment, and we need to "attach" "GPRs head" without gaps
2741     // to it:
2742     // Stack:
2743     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2744     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2745     //
2746     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2747     unsigned Padding =
2748         OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2749     ArgRegsSaveSize = ArgRegsSize + Padding;
2750   } else
2751     // We don't need to extend regs save size for byval parameters if they
2752     // are passed via GPRs only.
2753     ArgRegsSaveSize = ArgRegsSize;
2754 }
2755
2756 // The remaining GPRs hold either the beginning of variable-argument
2757 // data, or the beginning of an aggregate passed by value (usually
2758 // byval).  Either way, we allocate stack slots adjacent to the data
2759 // provided by our caller, and store the unallocated registers there.
2760 // If this is a variadic function, the va_list pointer will begin with
2761 // these values; otherwise, this reassembles a (byval) structure that
2762 // was split between registers and memory.
2763 // Return: The frame index registers were stored into.
2764 int
2765 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2766                                   SDLoc dl, SDValue &Chain,
2767                                   const Value *OrigArg,
2768                                   unsigned InRegsParamRecordIdx,
2769                                   unsigned OffsetFromOrigArg,
2770                                   unsigned ArgOffset,
2771                                   unsigned ArgSize,
2772                                   bool ForceMutable,
2773                                   unsigned ByValStoreOffset,
2774                                   unsigned TotalArgRegsSaveSize) const {
2775
2776   // Currently, two use-cases possible:
2777   // Case #1. Non-var-args function, and we meet first byval parameter.
2778   //          Setup first unallocated register as first byval register;
2779   //          eat all remained registers
2780   //          (these two actions are performed by HandleByVal method).
2781   //          Then, here, we initialize stack frame with
2782   //          "store-reg" instructions.
2783   // Case #2. Var-args function, that doesn't contain byval parameters.
2784   //          The same: eat all remained unallocated registers,
2785   //          initialize stack frame.
2786
2787   MachineFunction &MF = DAG.getMachineFunction();
2788   MachineFrameInfo *MFI = MF.getFrameInfo();
2789   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2790   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2791   unsigned RBegin, REnd;
2792   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2793     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2794     firstRegToSaveIndex = RBegin - ARM::R0;
2795     lastRegToSaveIndex = REnd - ARM::R0;
2796   } else {
2797     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2798       (GPRArgRegs, array_lengthof(GPRArgRegs));
2799     lastRegToSaveIndex = 4;
2800   }
2801
2802   unsigned ArgRegsSize, ArgRegsSaveSize;
2803   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2804                  ArgRegsSize, ArgRegsSaveSize);
2805
2806   // Store any by-val regs to their spots on the stack so that they may be
2807   // loaded by deferencing the result of formal parameter pointer or va_next.
2808   // Note: once stack area for byval/varargs registers
2809   // was initialized, it can't be initialized again.
2810   if (ArgRegsSaveSize) {
2811     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2812
2813     if (Padding) {
2814       assert(AFI->getStoredByValParamsPadding() == 0 &&
2815              "The only parameter may be padded.");
2816       AFI->setStoredByValParamsPadding(Padding);
2817     }
2818
2819     int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2820                                             Padding +
2821                                               ByValStoreOffset -
2822                                               (int64_t)TotalArgRegsSaveSize,
2823                                             false);
2824     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2825     if (Padding) {
2826        MFI->CreateFixedObject(Padding,
2827                               ArgOffset + ByValStoreOffset -
2828                                 (int64_t)ArgRegsSaveSize,
2829                               false);
2830     }
2831
2832     SmallVector<SDValue, 4> MemOps;
2833     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2834          ++firstRegToSaveIndex, ++i) {
2835       const TargetRegisterClass *RC;
2836       if (AFI->isThumb1OnlyFunction())
2837         RC = &ARM::tGPRRegClass;
2838       else
2839         RC = &ARM::GPRRegClass;
2840
2841       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2842       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2843       SDValue Store =
2844         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2845                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2846                      false, false, 0);
2847       MemOps.push_back(Store);
2848       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2849                         DAG.getConstant(4, getPointerTy()));
2850     }
2851
2852     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2853
2854     if (!MemOps.empty())
2855       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2856                           &MemOps[0], MemOps.size());
2857     return FrameIndex;
2858   } else {
2859     if (ArgSize == 0) {
2860       // We cannot allocate a zero-byte object for the first variadic argument,
2861       // so just make up a size.
2862       ArgSize = 4;
2863     }
2864     // This will point to the next argument passed via stack.
2865     return MFI->CreateFixedObject(
2866       ArgSize, ArgOffset, !ForceMutable);
2867   }
2868 }
2869
2870 // Setup stack frame, the va_list pointer will start from.
2871 void
2872 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2873                                         SDLoc dl, SDValue &Chain,
2874                                         unsigned ArgOffset,
2875                                         unsigned TotalArgRegsSaveSize,
2876                                         bool ForceMutable) const {
2877   MachineFunction &MF = DAG.getMachineFunction();
2878   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2879
2880   // Try to store any remaining integer argument regs
2881   // to their spots on the stack so that they may be loaded by deferencing
2882   // the result of va_next.
2883   // If there is no regs to be stored, just point address after last
2884   // argument passed via stack.
2885   int FrameIndex =
2886     StoreByValRegs(CCInfo, DAG, dl, Chain, 0, CCInfo.getInRegsParamsCount(),
2887                    0, ArgOffset, 0, ForceMutable, 0, TotalArgRegsSaveSize);
2888
2889   AFI->setVarArgsFrameIndex(FrameIndex);
2890 }
2891
2892 SDValue
2893 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2894                                         CallingConv::ID CallConv, bool isVarArg,
2895                                         const SmallVectorImpl<ISD::InputArg>
2896                                           &Ins,
2897                                         SDLoc dl, SelectionDAG &DAG,
2898                                         SmallVectorImpl<SDValue> &InVals)
2899                                           const {
2900   MachineFunction &MF = DAG.getMachineFunction();
2901   MachineFrameInfo *MFI = MF.getFrameInfo();
2902
2903   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2904
2905   // Assign locations to all of the incoming arguments.
2906   SmallVector<CCValAssign, 16> ArgLocs;
2907   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2908                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2909   CCInfo.AnalyzeFormalArguments(Ins,
2910                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2911                                                   isVarArg));
2912
2913   SmallVector<SDValue, 16> ArgValues;
2914   int lastInsIndex = -1;
2915   SDValue ArgValue;
2916   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2917   unsigned CurArgIdx = 0;
2918
2919   // Initially ArgRegsSaveSize is zero.
2920   // Then we increase this value each time we meet byval parameter.
2921   // We also increase this value in case of varargs function.
2922   AFI->setArgRegsSaveSize(0);
2923
2924   unsigned ByValStoreOffset = 0;
2925   unsigned TotalArgRegsSaveSize = 0;
2926   unsigned ArgRegsSaveSizeMaxAlign = 4;
2927
2928   // Calculate the amount of stack space that we need to allocate to store
2929   // byval and variadic arguments that are passed in registers.
2930   // We need to know this before we allocate the first byval or variadic
2931   // argument, as they will be allocated a stack slot below the CFA (Canonical
2932   // Frame Address, the stack pointer at entry to the function).
2933   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2934     CCValAssign &VA = ArgLocs[i];
2935     if (VA.isMemLoc()) {
2936       int index = VA.getValNo();
2937       if (index != lastInsIndex) {
2938         ISD::ArgFlagsTy Flags = Ins[index].Flags;
2939         if (Flags.isByVal()) {
2940           unsigned ExtraArgRegsSize;
2941           unsigned ExtraArgRegsSaveSize;
2942           computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
2943                          Flags.getByValSize(),
2944                          ExtraArgRegsSize, ExtraArgRegsSaveSize);
2945
2946           TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2947           if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
2948               ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
2949           CCInfo.nextInRegsParam();
2950         }
2951         lastInsIndex = index;
2952       }
2953     }
2954   }
2955   CCInfo.rewindByValRegsInfo();
2956   lastInsIndex = -1;
2957   if (isVarArg) {
2958     unsigned ExtraArgRegsSize;
2959     unsigned ExtraArgRegsSaveSize;
2960     computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
2961                    ExtraArgRegsSize, ExtraArgRegsSaveSize);
2962     TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2963   }
2964   // If the arg regs save area contains N-byte aligned values, the
2965   // bottom of it must be at least N-byte aligned.
2966   TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
2967   TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
2968
2969   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2970     CCValAssign &VA = ArgLocs[i];
2971     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2972     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2973     // Arguments stored in registers.
2974     if (VA.isRegLoc()) {
2975       EVT RegVT = VA.getLocVT();
2976
2977       if (VA.needsCustom()) {
2978         // f64 and vector types are split up into multiple registers or
2979         // combinations of registers and stack slots.
2980         if (VA.getLocVT() == MVT::v2f64) {
2981           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2982                                                    Chain, DAG, dl);
2983           VA = ArgLocs[++i]; // skip ahead to next loc
2984           SDValue ArgValue2;
2985           if (VA.isMemLoc()) {
2986             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2987             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2988             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2989                                     MachinePointerInfo::getFixedStack(FI),
2990                                     false, false, false, 0);
2991           } else {
2992             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2993                                              Chain, DAG, dl);
2994           }
2995           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2996           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2997                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2998           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2999                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3000         } else
3001           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3002
3003       } else {
3004         const TargetRegisterClass *RC;
3005
3006         if (RegVT == MVT::f32)
3007           RC = &ARM::SPRRegClass;
3008         else if (RegVT == MVT::f64)
3009           RC = &ARM::DPRRegClass;
3010         else if (RegVT == MVT::v2f64)
3011           RC = &ARM::QPRRegClass;
3012         else if (RegVT == MVT::i32)
3013           RC = AFI->isThumb1OnlyFunction() ?
3014             (const TargetRegisterClass*)&ARM::tGPRRegClass :
3015             (const TargetRegisterClass*)&ARM::GPRRegClass;
3016         else
3017           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3018
3019         // Transform the arguments in physical registers into virtual ones.
3020         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3021         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3022       }
3023
3024       // If this is an 8 or 16-bit value, it is really passed promoted
3025       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3026       // truncate to the right size.
3027       switch (VA.getLocInfo()) {
3028       default: llvm_unreachable("Unknown loc info!");
3029       case CCValAssign::Full: break;
3030       case CCValAssign::BCvt:
3031         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3032         break;
3033       case CCValAssign::SExt:
3034         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3035                                DAG.getValueType(VA.getValVT()));
3036         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3037         break;
3038       case CCValAssign::ZExt:
3039         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3040                                DAG.getValueType(VA.getValVT()));
3041         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3042         break;
3043       }
3044
3045       InVals.push_back(ArgValue);
3046
3047     } else { // VA.isRegLoc()
3048
3049       // sanity check
3050       assert(VA.isMemLoc());
3051       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3052
3053       int index = ArgLocs[i].getValNo();
3054
3055       // Some Ins[] entries become multiple ArgLoc[] entries.
3056       // Process them only once.
3057       if (index != lastInsIndex)
3058         {
3059           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3060           // FIXME: For now, all byval parameter objects are marked mutable.
3061           // This can be changed with more analysis.
3062           // In case of tail call optimization mark all arguments mutable.
3063           // Since they could be overwritten by lowering of arguments in case of
3064           // a tail call.
3065           if (Flags.isByVal()) {
3066             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3067
3068             ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3069             int FrameIndex = StoreByValRegs(
3070                 CCInfo, DAG, dl, Chain, CurOrigArg,
3071                 CurByValIndex,
3072                 Ins[VA.getValNo()].PartOffset,
3073                 VA.getLocMemOffset(),
3074                 Flags.getByValSize(),
3075                 true /*force mutable frames*/,
3076                 ByValStoreOffset,
3077                 TotalArgRegsSaveSize);
3078             ByValStoreOffset += Flags.getByValSize();
3079             ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3080             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3081             CCInfo.nextInRegsParam();
3082           } else {
3083             unsigned FIOffset = VA.getLocMemOffset();
3084             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3085                                             FIOffset, true);
3086
3087             // Create load nodes to retrieve arguments from the stack.
3088             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3089             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3090                                          MachinePointerInfo::getFixedStack(FI),
3091                                          false, false, false, 0));
3092           }
3093           lastInsIndex = index;
3094         }
3095     }
3096   }
3097
3098   // varargs
3099   if (isVarArg)
3100     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3101                          CCInfo.getNextStackOffset(),
3102                          TotalArgRegsSaveSize);
3103
3104   return Chain;
3105 }
3106
3107 /// isFloatingPointZero - Return true if this is +0.0.
3108 static bool isFloatingPointZero(SDValue Op) {
3109   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3110     return CFP->getValueAPF().isPosZero();
3111   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3112     // Maybe this has already been legalized into the constant pool?
3113     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3114       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3115       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3116         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3117           return CFP->getValueAPF().isPosZero();
3118     }
3119   }
3120   return false;
3121 }
3122
3123 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3124 /// the given operands.
3125 SDValue
3126 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3127                              SDValue &ARMcc, SelectionDAG &DAG,
3128                              SDLoc dl) const {
3129   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3130     unsigned C = RHSC->getZExtValue();
3131     if (!isLegalICmpImmediate(C)) {
3132       // Constant does not fit, try adjusting it by one?
3133       switch (CC) {
3134       default: break;
3135       case ISD::SETLT:
3136       case ISD::SETGE:
3137         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3138           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3139           RHS = DAG.getConstant(C-1, MVT::i32);
3140         }
3141         break;
3142       case ISD::SETULT:
3143       case ISD::SETUGE:
3144         if (C != 0 && isLegalICmpImmediate(C-1)) {
3145           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3146           RHS = DAG.getConstant(C-1, MVT::i32);
3147         }
3148         break;
3149       case ISD::SETLE:
3150       case ISD::SETGT:
3151         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3152           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3153           RHS = DAG.getConstant(C+1, MVT::i32);
3154         }
3155         break;
3156       case ISD::SETULE:
3157       case ISD::SETUGT:
3158         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3159           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3160           RHS = DAG.getConstant(C+1, MVT::i32);
3161         }
3162         break;
3163       }
3164     }
3165   }
3166
3167   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3168   ARMISD::NodeType CompareType;
3169   switch (CondCode) {
3170   default:
3171     CompareType = ARMISD::CMP;
3172     break;
3173   case ARMCC::EQ:
3174   case ARMCC::NE:
3175     // Uses only Z Flag
3176     CompareType = ARMISD::CMPZ;
3177     break;
3178   }
3179   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3180   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3181 }
3182
3183 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3184 SDValue
3185 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3186                              SDLoc dl) const {
3187   SDValue Cmp;
3188   if (!isFloatingPointZero(RHS))
3189     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3190   else
3191     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3192   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3193 }
3194
3195 /// duplicateCmp - Glue values can have only one use, so this function
3196 /// duplicates a comparison node.
3197 SDValue
3198 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3199   unsigned Opc = Cmp.getOpcode();
3200   SDLoc DL(Cmp);
3201   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3202     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3203
3204   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3205   Cmp = Cmp.getOperand(0);
3206   Opc = Cmp.getOpcode();
3207   if (Opc == ARMISD::CMPFP)
3208     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3209   else {
3210     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3211     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3212   }
3213   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3214 }
3215
3216 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3217   SDValue Cond = Op.getOperand(0);
3218   SDValue SelectTrue = Op.getOperand(1);
3219   SDValue SelectFalse = Op.getOperand(2);
3220   SDLoc dl(Op);
3221
3222   // Convert:
3223   //
3224   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3225   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3226   //
3227   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3228     const ConstantSDNode *CMOVTrue =
3229       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3230     const ConstantSDNode *CMOVFalse =
3231       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3232
3233     if (CMOVTrue && CMOVFalse) {
3234       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3235       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3236
3237       SDValue True;
3238       SDValue False;
3239       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3240         True = SelectTrue;
3241         False = SelectFalse;
3242       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3243         True = SelectFalse;
3244         False = SelectTrue;
3245       }
3246
3247       if (True.getNode() && False.getNode()) {
3248         EVT VT = Op.getValueType();
3249         SDValue ARMcc = Cond.getOperand(2);
3250         SDValue CCR = Cond.getOperand(3);
3251         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3252         assert(True.getValueType() == VT);
3253         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3254       }
3255     }
3256   }
3257
3258   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3259   // undefined bits before doing a full-word comparison with zero.
3260   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3261                      DAG.getConstant(1, Cond.getValueType()));
3262
3263   return DAG.getSelectCC(dl, Cond,
3264                          DAG.getConstant(0, Cond.getValueType()),
3265                          SelectTrue, SelectFalse, ISD::SETNE);
3266 }
3267
3268 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3269   if (CC == ISD::SETNE)
3270     return ISD::SETEQ;
3271   return ISD::getSetCCInverse(CC, true);
3272 }
3273
3274 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3275                                  bool &swpCmpOps, bool &swpVselOps) {
3276   // Start by selecting the GE condition code for opcodes that return true for
3277   // 'equality'
3278   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3279       CC == ISD::SETULE)
3280     CondCode = ARMCC::GE;
3281
3282   // and GT for opcodes that return false for 'equality'.
3283   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3284            CC == ISD::SETULT)
3285     CondCode = ARMCC::GT;
3286
3287   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3288   // to swap the compare operands.
3289   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3290       CC == ISD::SETULT)
3291     swpCmpOps = true;
3292
3293   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3294   // If we have an unordered opcode, we need to swap the operands to the VSEL
3295   // instruction (effectively negating the condition).
3296   //
3297   // This also has the effect of swapping which one of 'less' or 'greater'
3298   // returns true, so we also swap the compare operands. It also switches
3299   // whether we return true for 'equality', so we compensate by picking the
3300   // opposite condition code to our original choice.
3301   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3302       CC == ISD::SETUGT) {
3303     swpCmpOps = !swpCmpOps;
3304     swpVselOps = !swpVselOps;
3305     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3306   }
3307
3308   // 'ordered' is 'anything but unordered', so use the VS condition code and
3309   // swap the VSEL operands.
3310   if (CC == ISD::SETO) {
3311     CondCode = ARMCC::VS;
3312     swpVselOps = true;
3313   }
3314
3315   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3316   // code and swap the VSEL operands.
3317   if (CC == ISD::SETUNE) {
3318     CondCode = ARMCC::EQ;
3319     swpVselOps = true;
3320   }
3321 }
3322
3323 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3324   EVT VT = Op.getValueType();
3325   SDValue LHS = Op.getOperand(0);
3326   SDValue RHS = Op.getOperand(1);
3327   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3328   SDValue TrueVal = Op.getOperand(2);
3329   SDValue FalseVal = Op.getOperand(3);
3330   SDLoc dl(Op);
3331
3332   if (LHS.getValueType() == MVT::i32) {
3333     // Try to generate VSEL on ARMv8.
3334     // The VSEL instruction can't use all the usual ARM condition
3335     // codes: it only has two bits to select the condition code, so it's
3336     // constrained to use only GE, GT, VS and EQ.
3337     //
3338     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3339     // swap the operands of the previous compare instruction (effectively
3340     // inverting the compare condition, swapping 'less' and 'greater') and
3341     // sometimes need to swap the operands to the VSEL (which inverts the
3342     // condition in the sense of firing whenever the previous condition didn't)
3343     if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3344                                       TrueVal.getValueType() == MVT::f64)) {
3345       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3346       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3347           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3348         CC = getInverseCCForVSEL(CC);
3349         std::swap(TrueVal, FalseVal);
3350       }
3351     }
3352
3353     SDValue ARMcc;
3354     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3355     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3356     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3357                        Cmp);
3358   }
3359
3360   ARMCC::CondCodes CondCode, CondCode2;
3361   FPCCToARMCC(CC, CondCode, CondCode2);
3362
3363   // Try to generate VSEL on ARMv8.
3364   if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3365                                     TrueVal.getValueType() == MVT::f64)) {
3366     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3367     // same operands, as follows:
3368     //   c = fcmp [ogt, olt, ugt, ult] a, b
3369     //   select c, a, b
3370     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3371     // handled differently than the original code sequence.
3372     if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3373         RHS == FalseVal) {
3374       if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3375         return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3376       if (CC == ISD::SETOLT || CC == ISD::SETULT)
3377         return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3378     }
3379
3380     bool swpCmpOps = false;
3381     bool swpVselOps = false;
3382     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3383
3384     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3385         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3386       if (swpCmpOps)
3387         std::swap(LHS, RHS);
3388       if (swpVselOps)
3389         std::swap(TrueVal, FalseVal);
3390     }
3391   }
3392
3393   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3394   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3395   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3396   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3397                                ARMcc, CCR, Cmp);
3398   if (CondCode2 != ARMCC::AL) {
3399     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3400     // FIXME: Needs another CMP because flag can have but one use.
3401     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3402     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3403                          Result, TrueVal, ARMcc2, CCR, Cmp2);
3404   }
3405   return Result;
3406 }
3407
3408 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3409 /// to morph to an integer compare sequence.
3410 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3411                            const ARMSubtarget *Subtarget) {
3412   SDNode *N = Op.getNode();
3413   if (!N->hasOneUse())
3414     // Otherwise it requires moving the value from fp to integer registers.
3415     return false;
3416   if (!N->getNumValues())
3417     return false;
3418   EVT VT = Op.getValueType();
3419   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3420     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3421     // vmrs are very slow, e.g. cortex-a8.
3422     return false;
3423
3424   if (isFloatingPointZero(Op)) {
3425     SeenZero = true;
3426     return true;
3427   }
3428   return ISD::isNormalLoad(N);
3429 }
3430
3431 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3432   if (isFloatingPointZero(Op))
3433     return DAG.getConstant(0, MVT::i32);
3434
3435   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3436     return DAG.getLoad(MVT::i32, SDLoc(Op),
3437                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3438                        Ld->isVolatile(), Ld->isNonTemporal(),
3439                        Ld->isInvariant(), Ld->getAlignment());
3440
3441   llvm_unreachable("Unknown VFP cmp argument!");
3442 }
3443
3444 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3445                            SDValue &RetVal1, SDValue &RetVal2) {
3446   if (isFloatingPointZero(Op)) {
3447     RetVal1 = DAG.getConstant(0, MVT::i32);
3448     RetVal2 = DAG.getConstant(0, MVT::i32);
3449     return;
3450   }
3451
3452   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3453     SDValue Ptr = Ld->getBasePtr();
3454     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3455                           Ld->getChain(), Ptr,
3456                           Ld->getPointerInfo(),
3457                           Ld->isVolatile(), Ld->isNonTemporal(),
3458                           Ld->isInvariant(), Ld->getAlignment());
3459
3460     EVT PtrType = Ptr.getValueType();
3461     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3462     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3463                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3464     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3465                           Ld->getChain(), NewPtr,
3466                           Ld->getPointerInfo().getWithOffset(4),
3467                           Ld->isVolatile(), Ld->isNonTemporal(),
3468                           Ld->isInvariant(), NewAlign);
3469     return;
3470   }
3471
3472   llvm_unreachable("Unknown VFP cmp argument!");
3473 }
3474
3475 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3476 /// f32 and even f64 comparisons to integer ones.
3477 SDValue
3478 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3479   SDValue Chain = Op.getOperand(0);
3480   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3481   SDValue LHS = Op.getOperand(2);
3482   SDValue RHS = Op.getOperand(3);
3483   SDValue Dest = Op.getOperand(4);
3484   SDLoc dl(Op);
3485
3486   bool LHSSeenZero = false;
3487   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3488   bool RHSSeenZero = false;
3489   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3490   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3491     // If unsafe fp math optimization is enabled and there are no other uses of
3492     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3493     // to an integer comparison.
3494     if (CC == ISD::SETOEQ)
3495       CC = ISD::SETEQ;
3496     else if (CC == ISD::SETUNE)
3497       CC = ISD::SETNE;
3498
3499     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3500     SDValue ARMcc;
3501     if (LHS.getValueType() == MVT::f32) {
3502       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3503                         bitcastf32Toi32(LHS, DAG), Mask);
3504       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3505                         bitcastf32Toi32(RHS, DAG), Mask);
3506       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3507       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3508       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3509                          Chain, Dest, ARMcc, CCR, Cmp);
3510     }
3511
3512     SDValue LHS1, LHS2;
3513     SDValue RHS1, RHS2;
3514     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3515     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3516     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3517     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3518     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3519     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3520     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3521     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3522     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3523   }
3524
3525   return SDValue();
3526 }
3527
3528 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3529   SDValue Chain = Op.getOperand(0);
3530   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3531   SDValue LHS = Op.getOperand(2);
3532   SDValue RHS = Op.getOperand(3);
3533   SDValue Dest = Op.getOperand(4);
3534   SDLoc dl(Op);
3535
3536   if (LHS.getValueType() == MVT::i32) {
3537     SDValue ARMcc;
3538     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3539     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3540     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3541                        Chain, Dest, ARMcc, CCR, Cmp);
3542   }
3543
3544   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3545
3546   if (getTargetMachine().Options.UnsafeFPMath &&
3547       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3548        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3549     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3550     if (Result.getNode())
3551       return Result;
3552   }
3553
3554   ARMCC::CondCodes CondCode, CondCode2;
3555   FPCCToARMCC(CC, CondCode, CondCode2);
3556
3557   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3558   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3559   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3560   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3561   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3562   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3563   if (CondCode2 != ARMCC::AL) {
3564     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3565     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3566     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3567   }
3568   return Res;
3569 }
3570
3571 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3572   SDValue Chain = Op.getOperand(0);
3573   SDValue Table = Op.getOperand(1);
3574   SDValue Index = Op.getOperand(2);
3575   SDLoc dl(Op);
3576
3577   EVT PTy = getPointerTy();
3578   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3579   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3580   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3581   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3582   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3583   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3584   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3585   if (Subtarget->isThumb2()) {
3586     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3587     // which does another jump to the destination. This also makes it easier
3588     // to translate it to TBB / TBH later.
3589     // FIXME: This might not work if the function is extremely large.
3590     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3591                        Addr, Op.getOperand(2), JTI, UId);
3592   }
3593   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3594     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3595                        MachinePointerInfo::getJumpTable(),
3596                        false, false, false, 0);
3597     Chain = Addr.getValue(1);
3598     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3599     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3600   } else {
3601     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3602                        MachinePointerInfo::getJumpTable(),
3603                        false, false, false, 0);
3604     Chain = Addr.getValue(1);
3605     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3606   }
3607 }
3608
3609 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3610   EVT VT = Op.getValueType();
3611   SDLoc dl(Op);
3612
3613   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3614     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3615       return Op;
3616     return DAG.UnrollVectorOp(Op.getNode());
3617   }
3618
3619   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3620          "Invalid type for custom lowering!");
3621   if (VT != MVT::v4i16)
3622     return DAG.UnrollVectorOp(Op.getNode());
3623
3624   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3625   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3626 }
3627
3628 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3629   EVT VT = Op.getValueType();
3630   if (VT.isVector())
3631     return LowerVectorFP_TO_INT(Op, DAG);
3632
3633   SDLoc dl(Op);
3634   unsigned Opc;
3635
3636   switch (Op.getOpcode()) {
3637   default: llvm_unreachable("Invalid opcode!");
3638   case ISD::FP_TO_SINT:
3639     Opc = ARMISD::FTOSI;
3640     break;
3641   case ISD::FP_TO_UINT:
3642     Opc = ARMISD::FTOUI;
3643     break;
3644   }
3645   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3646   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3647 }
3648
3649 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3650   EVT VT = Op.getValueType();
3651   SDLoc dl(Op);
3652
3653   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3654     if (VT.getVectorElementType() == MVT::f32)
3655       return Op;
3656     return DAG.UnrollVectorOp(Op.getNode());
3657   }
3658
3659   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3660          "Invalid type for custom lowering!");
3661   if (VT != MVT::v4f32)
3662     return DAG.UnrollVectorOp(Op.getNode());
3663
3664   unsigned CastOpc;
3665   unsigned Opc;
3666   switch (Op.getOpcode()) {
3667   default: llvm_unreachable("Invalid opcode!");
3668   case ISD::SINT_TO_FP:
3669     CastOpc = ISD::SIGN_EXTEND;
3670     Opc = ISD::SINT_TO_FP;
3671     break;
3672   case ISD::UINT_TO_FP:
3673     CastOpc = ISD::ZERO_EXTEND;
3674     Opc = ISD::UINT_TO_FP;
3675     break;
3676   }
3677
3678   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3679   return DAG.getNode(Opc, dl, VT, Op);
3680 }
3681
3682 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3683   EVT VT = Op.getValueType();
3684   if (VT.isVector())
3685     return LowerVectorINT_TO_FP(Op, DAG);
3686
3687   SDLoc dl(Op);
3688   unsigned Opc;
3689
3690   switch (Op.getOpcode()) {
3691   default: llvm_unreachable("Invalid opcode!");
3692   case ISD::SINT_TO_FP:
3693     Opc = ARMISD::SITOF;
3694     break;
3695   case ISD::UINT_TO_FP:
3696     Opc = ARMISD::UITOF;
3697     break;
3698   }
3699
3700   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3701   return DAG.getNode(Opc, dl, VT, Op);
3702 }
3703
3704 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3705   // Implement fcopysign with a fabs and a conditional fneg.
3706   SDValue Tmp0 = Op.getOperand(0);
3707   SDValue Tmp1 = Op.getOperand(1);
3708   SDLoc dl(Op);
3709   EVT VT = Op.getValueType();
3710   EVT SrcVT = Tmp1.getValueType();
3711   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3712     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3713   bool UseNEON = !InGPR && Subtarget->hasNEON();
3714
3715   if (UseNEON) {
3716     // Use VBSL to copy the sign bit.
3717     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3718     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3719                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3720     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3721     if (VT == MVT::f64)
3722       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3723                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3724                          DAG.getConstant(32, MVT::i32));
3725     else /*if (VT == MVT::f32)*/
3726       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3727     if (SrcVT == MVT::f32) {
3728       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3729       if (VT == MVT::f64)
3730         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3731                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3732                            DAG.getConstant(32, MVT::i32));
3733     } else if (VT == MVT::f32)
3734       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3735                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3736                          DAG.getConstant(32, MVT::i32));
3737     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3738     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3739
3740     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3741                                             MVT::i32);
3742     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3743     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3744                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3745
3746     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3747                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3748                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3749     if (VT == MVT::f32) {
3750       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3751       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3752                         DAG.getConstant(0, MVT::i32));
3753     } else {
3754       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3755     }
3756
3757     return Res;
3758   }
3759
3760   // Bitcast operand 1 to i32.
3761   if (SrcVT == MVT::f64)
3762     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3763                        &Tmp1, 1).getValue(1);
3764   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3765
3766   // Or in the signbit with integer operations.
3767   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3768   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3769   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3770   if (VT == MVT::f32) {
3771     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3772                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3773     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3774                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3775   }
3776
3777   // f64: Or the high part with signbit and then combine two parts.
3778   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3779                      &Tmp0, 1);
3780   SDValue Lo = Tmp0.getValue(0);
3781   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3782   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3783   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3784 }
3785
3786 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3787   MachineFunction &MF = DAG.getMachineFunction();
3788   MachineFrameInfo *MFI = MF.getFrameInfo();
3789   MFI->setReturnAddressIsTaken(true);
3790
3791   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3792     return SDValue();
3793
3794   EVT VT = Op.getValueType();
3795   SDLoc dl(Op);
3796   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3797   if (Depth) {
3798     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3799     SDValue Offset = DAG.getConstant(4, MVT::i32);
3800     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3801                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3802                        MachinePointerInfo(), false, false, false, 0);
3803   }
3804
3805   // Return LR, which contains the return address. Mark it an implicit live-in.
3806   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3807   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3808 }
3809
3810 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3811   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3812   MFI->setFrameAddressIsTaken(true);
3813
3814   EVT VT = Op.getValueType();
3815   SDLoc dl(Op);  // FIXME probably not meaningful
3816   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3817   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetMachO())
3818     ? ARM::R7 : ARM::R11;
3819   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3820   while (Depth--)
3821     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3822                             MachinePointerInfo(),
3823                             false, false, false, 0);
3824   return FrameAddr;
3825 }
3826
3827 /// ExpandBITCAST - If the target supports VFP, this function is called to
3828 /// expand a bit convert where either the source or destination type is i64 to
3829 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3830 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3831 /// vectors), since the legalizer won't know what to do with that.
3832 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3833   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3834   SDLoc dl(N);
3835   SDValue Op = N->getOperand(0);
3836
3837   // This function is only supposed to be called for i64 types, either as the
3838   // source or destination of the bit convert.
3839   EVT SrcVT = Op.getValueType();
3840   EVT DstVT = N->getValueType(0);
3841   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3842          "ExpandBITCAST called for non-i64 type");
3843
3844   // Turn i64->f64 into VMOVDRR.
3845   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3846     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3847                              DAG.getConstant(0, MVT::i32));
3848     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3849                              DAG.getConstant(1, MVT::i32));
3850     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3851                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3852   }
3853
3854   // Turn f64->i64 into VMOVRRD.
3855   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3856     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3857                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3858     // Merge the pieces into a single i64 value.
3859     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3860   }
3861
3862   return SDValue();
3863 }
3864
3865 /// getZeroVector - Returns a vector of specified type with all zero elements.
3866 /// Zero vectors are used to represent vector negation and in those cases
3867 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3868 /// not support i64 elements, so sometimes the zero vectors will need to be
3869 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3870 /// zero vector.
3871 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3872   assert(VT.isVector() && "Expected a vector type");
3873   // The canonical modified immediate encoding of a zero vector is....0!
3874   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3875   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3876   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3877   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3878 }
3879
3880 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3881 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3882 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3883                                                 SelectionDAG &DAG) const {
3884   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3885   EVT VT = Op.getValueType();
3886   unsigned VTBits = VT.getSizeInBits();
3887   SDLoc dl(Op);
3888   SDValue ShOpLo = Op.getOperand(0);
3889   SDValue ShOpHi = Op.getOperand(1);
3890   SDValue ShAmt  = Op.getOperand(2);
3891   SDValue ARMcc;
3892   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3893
3894   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3895
3896   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3897                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3898   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3899   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3900                                    DAG.getConstant(VTBits, MVT::i32));
3901   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3902   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3903   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3904
3905   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3906   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3907                           ARMcc, DAG, dl);
3908   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3909   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3910                            CCR, Cmp);
3911
3912   SDValue Ops[2] = { Lo, Hi };
3913   return DAG.getMergeValues(Ops, 2, dl);
3914 }
3915
3916 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3917 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3918 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3919                                                SelectionDAG &DAG) const {
3920   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3921   EVT VT = Op.getValueType();
3922   unsigned VTBits = VT.getSizeInBits();
3923   SDLoc dl(Op);
3924   SDValue ShOpLo = Op.getOperand(0);
3925   SDValue ShOpHi = Op.getOperand(1);
3926   SDValue ShAmt  = Op.getOperand(2);
3927   SDValue ARMcc;
3928
3929   assert(Op.getOpcode() == ISD::SHL_PARTS);
3930   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3931                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3932   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3933   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3934                                    DAG.getConstant(VTBits, MVT::i32));
3935   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3936   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3937
3938   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3939   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3940   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3941                           ARMcc, DAG, dl);
3942   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3943   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3944                            CCR, Cmp);
3945
3946   SDValue Ops[2] = { Lo, Hi };
3947   return DAG.getMergeValues(Ops, 2, dl);
3948 }
3949
3950 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3951                                             SelectionDAG &DAG) const {
3952   // The rounding mode is in bits 23:22 of the FPSCR.
3953   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3954   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3955   // so that the shift + and get folded into a bitfield extract.
3956   SDLoc dl(Op);
3957   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3958                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3959                                               MVT::i32));
3960   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3961                                   DAG.getConstant(1U << 22, MVT::i32));
3962   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3963                               DAG.getConstant(22, MVT::i32));
3964   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3965                      DAG.getConstant(3, MVT::i32));
3966 }
3967
3968 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3969                          const ARMSubtarget *ST) {
3970   EVT VT = N->getValueType(0);
3971   SDLoc dl(N);
3972
3973   if (!ST->hasV6T2Ops())
3974     return SDValue();
3975
3976   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3977   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3978 }
3979
3980 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3981 /// for each 16-bit element from operand, repeated.  The basic idea is to
3982 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3983 ///
3984 /// Trace for v4i16:
3985 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
3986 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3987 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3988 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3989 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
3990 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
3991 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3992 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
3993 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3994   EVT VT = N->getValueType(0);
3995   SDLoc DL(N);
3996
3997   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
3998   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
3999   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4000   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4001   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4002   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4003 }
4004
4005 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4006 /// bit-count for each 16-bit element from the operand.  We need slightly
4007 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4008 /// 64/128-bit registers.
4009 ///
4010 /// Trace for v4i16:
4011 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4012 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4013 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4014 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4015 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4016   EVT VT = N->getValueType(0);
4017   SDLoc DL(N);
4018
4019   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4020   if (VT.is64BitVector()) {
4021     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4022     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4023                        DAG.getIntPtrConstant(0));
4024   } else {
4025     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4026                                     BitCounts, DAG.getIntPtrConstant(0));
4027     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4028   }
4029 }
4030
4031 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4032 /// bit-count for each 32-bit element from the operand.  The idea here is
4033 /// to split the vector into 16-bit elements, leverage the 16-bit count
4034 /// routine, and then combine the results.
4035 ///
4036 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4037 /// input    = [v0    v1    ] (vi: 32-bit elements)
4038 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4039 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4040 /// vrev: N0 = [k1 k0 k3 k2 ]
4041 ///            [k0 k1 k2 k3 ]
4042 ///       N1 =+[k1 k0 k3 k2 ]
4043 ///            [k0 k2 k1 k3 ]
4044 ///       N2 =+[k1 k3 k0 k2 ]
4045 ///            [k0    k2    k1    k3    ]
4046 /// Extended =+[k1    k3    k0    k2    ]
4047 ///            [k0    k2    ]
4048 /// Extracted=+[k1    k3    ]
4049 ///
4050 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4051   EVT VT = N->getValueType(0);
4052   SDLoc DL(N);
4053
4054   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4055
4056   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4057   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4058   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4059   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4060   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4061
4062   if (VT.is64BitVector()) {
4063     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4064     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4065                        DAG.getIntPtrConstant(0));
4066   } else {
4067     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4068                                     DAG.getIntPtrConstant(0));
4069     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4070   }
4071 }
4072
4073 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4074                           const ARMSubtarget *ST) {
4075   EVT VT = N->getValueType(0);
4076
4077   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4078   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4079           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4080          "Unexpected type for custom ctpop lowering");
4081
4082   if (VT.getVectorElementType() == MVT::i32)
4083     return lowerCTPOP32BitElements(N, DAG);
4084   else
4085     return lowerCTPOP16BitElements(N, DAG);
4086 }
4087
4088 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4089                           const ARMSubtarget *ST) {
4090   EVT VT = N->getValueType(0);
4091   SDLoc dl(N);
4092
4093   if (!VT.isVector())
4094     return SDValue();
4095
4096   // Lower vector shifts on NEON to use VSHL.
4097   assert(ST->hasNEON() && "unexpected vector shift");
4098
4099   // Left shifts translate directly to the vshiftu intrinsic.
4100   if (N->getOpcode() == ISD::SHL)
4101     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4102                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4103                        N->getOperand(0), N->getOperand(1));
4104
4105   assert((N->getOpcode() == ISD::SRA ||
4106           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4107
4108   // NEON uses the same intrinsics for both left and right shifts.  For
4109   // right shifts, the shift amounts are negative, so negate the vector of
4110   // shift amounts.
4111   EVT ShiftVT = N->getOperand(1).getValueType();
4112   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4113                                      getZeroVector(ShiftVT, DAG, dl),
4114                                      N->getOperand(1));
4115   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4116                              Intrinsic::arm_neon_vshifts :
4117                              Intrinsic::arm_neon_vshiftu);
4118   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4119                      DAG.getConstant(vshiftInt, MVT::i32),
4120                      N->getOperand(0), NegatedCount);
4121 }
4122
4123 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4124                                 const ARMSubtarget *ST) {
4125   EVT VT = N->getValueType(0);
4126   SDLoc dl(N);
4127
4128   // We can get here for a node like i32 = ISD::SHL i32, i64
4129   if (VT != MVT::i64)
4130     return SDValue();
4131
4132   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4133          "Unknown shift to lower!");
4134
4135   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4136   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4137       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4138     return SDValue();
4139
4140   // If we are in thumb mode, we don't have RRX.
4141   if (ST->isThumb1Only()) return SDValue();
4142
4143   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4144   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4145                            DAG.getConstant(0, MVT::i32));
4146   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4147                            DAG.getConstant(1, MVT::i32));
4148
4149   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4150   // captures the result into a carry flag.
4151   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4152   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
4153
4154   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4155   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4156
4157   // Merge the pieces into a single i64 value.
4158  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4159 }
4160
4161 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4162   SDValue TmpOp0, TmpOp1;
4163   bool Invert = false;
4164   bool Swap = false;
4165   unsigned Opc = 0;
4166
4167   SDValue Op0 = Op.getOperand(0);
4168   SDValue Op1 = Op.getOperand(1);
4169   SDValue CC = Op.getOperand(2);
4170   EVT VT = Op.getValueType();
4171   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4172   SDLoc dl(Op);
4173
4174   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4175     switch (SetCCOpcode) {
4176     default: llvm_unreachable("Illegal FP comparison");
4177     case ISD::SETUNE:
4178     case ISD::SETNE:  Invert = true; // Fallthrough
4179     case ISD::SETOEQ:
4180     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4181     case ISD::SETOLT:
4182     case ISD::SETLT: Swap = true; // Fallthrough
4183     case ISD::SETOGT:
4184     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4185     case ISD::SETOLE:
4186     case ISD::SETLE:  Swap = true; // Fallthrough
4187     case ISD::SETOGE:
4188     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4189     case ISD::SETUGE: Swap = true; // Fallthrough
4190     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4191     case ISD::SETUGT: Swap = true; // Fallthrough
4192     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4193     case ISD::SETUEQ: Invert = true; // Fallthrough
4194     case ISD::SETONE:
4195       // Expand this to (OLT | OGT).
4196       TmpOp0 = Op0;
4197       TmpOp1 = Op1;
4198       Opc = ISD::OR;
4199       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4200       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4201       break;
4202     case ISD::SETUO: Invert = true; // Fallthrough
4203     case ISD::SETO:
4204       // Expand this to (OLT | OGE).
4205       TmpOp0 = Op0;
4206       TmpOp1 = Op1;
4207       Opc = ISD::OR;
4208       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4209       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4210       break;
4211     }
4212   } else {
4213     // Integer comparisons.
4214     switch (SetCCOpcode) {
4215     default: llvm_unreachable("Illegal integer comparison");
4216     case ISD::SETNE:  Invert = true;
4217     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4218     case ISD::SETLT:  Swap = true;
4219     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4220     case ISD::SETLE:  Swap = true;
4221     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4222     case ISD::SETULT: Swap = true;
4223     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4224     case ISD::SETULE: Swap = true;
4225     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4226     }
4227
4228     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4229     if (Opc == ARMISD::VCEQ) {
4230
4231       SDValue AndOp;
4232       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4233         AndOp = Op0;
4234       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4235         AndOp = Op1;
4236
4237       // Ignore bitconvert.
4238       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4239         AndOp = AndOp.getOperand(0);
4240
4241       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4242         Opc = ARMISD::VTST;
4243         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4244         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4245         Invert = !Invert;
4246       }
4247     }
4248   }
4249
4250   if (Swap)
4251     std::swap(Op0, Op1);
4252
4253   // If one of the operands is a constant vector zero, attempt to fold the
4254   // comparison to a specialized compare-against-zero form.
4255   SDValue SingleOp;
4256   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4257     SingleOp = Op0;
4258   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4259     if (Opc == ARMISD::VCGE)
4260       Opc = ARMISD::VCLEZ;
4261     else if (Opc == ARMISD::VCGT)
4262       Opc = ARMISD::VCLTZ;
4263     SingleOp = Op1;
4264   }
4265
4266   SDValue Result;
4267   if (SingleOp.getNode()) {
4268     switch (Opc) {
4269     case ARMISD::VCEQ:
4270       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4271     case ARMISD::VCGE:
4272       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4273     case ARMISD::VCLEZ:
4274       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4275     case ARMISD::VCGT:
4276       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4277     case ARMISD::VCLTZ:
4278       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4279     default:
4280       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4281     }
4282   } else {
4283      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4284   }
4285
4286   if (Invert)
4287     Result = DAG.getNOT(dl, Result, VT);
4288
4289   return Result;
4290 }
4291
4292 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4293 /// valid vector constant for a NEON instruction with a "modified immediate"
4294 /// operand (e.g., VMOV).  If so, return the encoded value.
4295 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4296                                  unsigned SplatBitSize, SelectionDAG &DAG,
4297                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4298   unsigned OpCmode, Imm;
4299
4300   // SplatBitSize is set to the smallest size that splats the vector, so a
4301   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4302   // immediate instructions others than VMOV do not support the 8-bit encoding
4303   // of a zero vector, and the default encoding of zero is supposed to be the
4304   // 32-bit version.
4305   if (SplatBits == 0)
4306     SplatBitSize = 32;
4307
4308   switch (SplatBitSize) {
4309   case 8:
4310     if (type != VMOVModImm)
4311       return SDValue();
4312     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4313     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4314     OpCmode = 0xe;
4315     Imm = SplatBits;
4316     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4317     break;
4318
4319   case 16:
4320     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4321     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4322     if ((SplatBits & ~0xff) == 0) {
4323       // Value = 0x00nn: Op=x, Cmode=100x.
4324       OpCmode = 0x8;
4325       Imm = SplatBits;
4326       break;
4327     }
4328     if ((SplatBits & ~0xff00) == 0) {
4329       // Value = 0xnn00: Op=x, Cmode=101x.
4330       OpCmode = 0xa;
4331       Imm = SplatBits >> 8;
4332       break;
4333     }
4334     return SDValue();
4335
4336   case 32:
4337     // NEON's 32-bit VMOV supports splat values where:
4338     // * only one byte is nonzero, or
4339     // * the least significant byte is 0xff and the second byte is nonzero, or
4340     // * the least significant 2 bytes are 0xff and the third is nonzero.
4341     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4342     if ((SplatBits & ~0xff) == 0) {
4343       // Value = 0x000000nn: Op=x, Cmode=000x.
4344       OpCmode = 0;
4345       Imm = SplatBits;
4346       break;
4347     }
4348     if ((SplatBits & ~0xff00) == 0) {
4349       // Value = 0x0000nn00: Op=x, Cmode=001x.
4350       OpCmode = 0x2;
4351       Imm = SplatBits >> 8;
4352       break;
4353     }
4354     if ((SplatBits & ~0xff0000) == 0) {
4355       // Value = 0x00nn0000: Op=x, Cmode=010x.
4356       OpCmode = 0x4;
4357       Imm = SplatBits >> 16;
4358       break;
4359     }
4360     if ((SplatBits & ~0xff000000) == 0) {
4361       // Value = 0xnn000000: Op=x, Cmode=011x.
4362       OpCmode = 0x6;
4363       Imm = SplatBits >> 24;
4364       break;
4365     }
4366
4367     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4368     if (type == OtherModImm) return SDValue();
4369
4370     if ((SplatBits & ~0xffff) == 0 &&
4371         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4372       // Value = 0x0000nnff: Op=x, Cmode=1100.
4373       OpCmode = 0xc;
4374       Imm = SplatBits >> 8;
4375       break;
4376     }
4377
4378     if ((SplatBits & ~0xffffff) == 0 &&
4379         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4380       // Value = 0x00nnffff: Op=x, Cmode=1101.
4381       OpCmode = 0xd;
4382       Imm = SplatBits >> 16;
4383       break;
4384     }
4385
4386     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4387     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4388     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4389     // and fall through here to test for a valid 64-bit splat.  But, then the
4390     // caller would also need to check and handle the change in size.
4391     return SDValue();
4392
4393   case 64: {
4394     if (type != VMOVModImm)
4395       return SDValue();
4396     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4397     uint64_t BitMask = 0xff;
4398     uint64_t Val = 0;
4399     unsigned ImmMask = 1;
4400     Imm = 0;
4401     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4402       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4403         Val |= BitMask;
4404         Imm |= ImmMask;
4405       } else if ((SplatBits & BitMask) != 0) {
4406         return SDValue();
4407       }
4408       BitMask <<= 8;
4409       ImmMask <<= 1;
4410     }
4411     // Op=1, Cmode=1110.
4412     OpCmode = 0x1e;
4413     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4414     break;
4415   }
4416
4417   default:
4418     llvm_unreachable("unexpected size for isNEONModifiedImm");
4419   }
4420
4421   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4422   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4423 }
4424
4425 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4426                                            const ARMSubtarget *ST) const {
4427   if (!ST->hasVFP3())
4428     return SDValue();
4429
4430   bool IsDouble = Op.getValueType() == MVT::f64;
4431   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4432
4433   // Try splatting with a VMOV.f32...
4434   APFloat FPVal = CFP->getValueAPF();
4435   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4436
4437   if (ImmVal != -1) {
4438     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4439       // We have code in place to select a valid ConstantFP already, no need to
4440       // do any mangling.
4441       return Op;
4442     }
4443
4444     // It's a float and we are trying to use NEON operations where
4445     // possible. Lower it to a splat followed by an extract.
4446     SDLoc DL(Op);
4447     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4448     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4449                                       NewVal);
4450     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4451                        DAG.getConstant(0, MVT::i32));
4452   }
4453
4454   // The rest of our options are NEON only, make sure that's allowed before
4455   // proceeding..
4456   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4457     return SDValue();
4458
4459   EVT VMovVT;
4460   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4461
4462   // It wouldn't really be worth bothering for doubles except for one very
4463   // important value, which does happen to match: 0.0. So make sure we don't do
4464   // anything stupid.
4465   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4466     return SDValue();
4467
4468   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4469   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4470                                      false, VMOVModImm);
4471   if (NewVal != SDValue()) {
4472     SDLoc DL(Op);
4473     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4474                                       NewVal);
4475     if (IsDouble)
4476       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4477
4478     // It's a float: cast and extract a vector element.
4479     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4480                                        VecConstant);
4481     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4482                        DAG.getConstant(0, MVT::i32));
4483   }
4484
4485   // Finally, try a VMVN.i32
4486   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4487                              false, VMVNModImm);
4488   if (NewVal != SDValue()) {
4489     SDLoc DL(Op);
4490     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4491
4492     if (IsDouble)
4493       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4494
4495     // It's a float: cast and extract a vector element.
4496     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4497                                        VecConstant);
4498     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4499                        DAG.getConstant(0, MVT::i32));
4500   }
4501
4502   return SDValue();
4503 }
4504
4505 // check if an VEXT instruction can handle the shuffle mask when the
4506 // vector sources of the shuffle are the same.
4507 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4508   unsigned NumElts = VT.getVectorNumElements();
4509
4510   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4511   if (M[0] < 0)
4512     return false;
4513
4514   Imm = M[0];
4515
4516   // If this is a VEXT shuffle, the immediate value is the index of the first
4517   // element.  The other shuffle indices must be the successive elements after
4518   // the first one.
4519   unsigned ExpectedElt = Imm;
4520   for (unsigned i = 1; i < NumElts; ++i) {
4521     // Increment the expected index.  If it wraps around, just follow it
4522     // back to index zero and keep going.
4523     ++ExpectedElt;
4524     if (ExpectedElt == NumElts)
4525       ExpectedElt = 0;
4526
4527     if (M[i] < 0) continue; // ignore UNDEF indices
4528     if (ExpectedElt != static_cast<unsigned>(M[i]))
4529       return false;
4530   }
4531
4532   return true;
4533 }
4534
4535
4536 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4537                        bool &ReverseVEXT, unsigned &Imm) {
4538   unsigned NumElts = VT.getVectorNumElements();
4539   ReverseVEXT = false;
4540
4541   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4542   if (M[0] < 0)
4543     return false;
4544
4545   Imm = M[0];
4546
4547   // If this is a VEXT shuffle, the immediate value is the index of the first
4548   // element.  The other shuffle indices must be the successive elements after
4549   // the first one.
4550   unsigned ExpectedElt = Imm;
4551   for (unsigned i = 1; i < NumElts; ++i) {
4552     // Increment the expected index.  If it wraps around, it may still be
4553     // a VEXT but the source vectors must be swapped.
4554     ExpectedElt += 1;
4555     if (ExpectedElt == NumElts * 2) {
4556       ExpectedElt = 0;
4557       ReverseVEXT = true;
4558     }
4559
4560     if (M[i] < 0) continue; // ignore UNDEF indices
4561     if (ExpectedElt != static_cast<unsigned>(M[i]))
4562       return false;
4563   }
4564
4565   // Adjust the index value if the source operands will be swapped.
4566   if (ReverseVEXT)
4567     Imm -= NumElts;
4568
4569   return true;
4570 }
4571
4572 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4573 /// instruction with the specified blocksize.  (The order of the elements
4574 /// within each block of the vector is reversed.)
4575 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4576   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4577          "Only possible block sizes for VREV are: 16, 32, 64");
4578
4579   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4580   if (EltSz == 64)
4581     return false;
4582
4583   unsigned NumElts = VT.getVectorNumElements();
4584   unsigned BlockElts = M[0] + 1;
4585   // If the first shuffle index is UNDEF, be optimistic.
4586   if (M[0] < 0)
4587     BlockElts = BlockSize / EltSz;
4588
4589   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4590     return false;
4591
4592   for (unsigned i = 0; i < NumElts; ++i) {
4593     if (M[i] < 0) continue; // ignore UNDEF indices
4594     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4595       return false;
4596   }
4597
4598   return true;
4599 }
4600
4601 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4602   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4603   // range, then 0 is placed into the resulting vector. So pretty much any mask
4604   // of 8 elements can work here.
4605   return VT == MVT::v8i8 && M.size() == 8;
4606 }
4607
4608 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4609   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4610   if (EltSz == 64)
4611     return false;
4612
4613   unsigned NumElts = VT.getVectorNumElements();
4614   WhichResult = (M[0] == 0 ? 0 : 1);
4615   for (unsigned i = 0; i < NumElts; i += 2) {
4616     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4617         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4618       return false;
4619   }
4620   return true;
4621 }
4622
4623 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4624 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4625 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4626 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4627   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4628   if (EltSz == 64)
4629     return false;
4630
4631   unsigned NumElts = VT.getVectorNumElements();
4632   WhichResult = (M[0] == 0 ? 0 : 1);
4633   for (unsigned i = 0; i < NumElts; i += 2) {
4634     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4635         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4636       return false;
4637   }
4638   return true;
4639 }
4640
4641 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4642   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4643   if (EltSz == 64)
4644     return false;
4645
4646   unsigned NumElts = VT.getVectorNumElements();
4647   WhichResult = (M[0] == 0 ? 0 : 1);
4648   for (unsigned i = 0; i != NumElts; ++i) {
4649     if (M[i] < 0) continue; // ignore UNDEF indices
4650     if ((unsigned) M[i] != 2 * i + WhichResult)
4651       return false;
4652   }
4653
4654   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4655   if (VT.is64BitVector() && EltSz == 32)
4656     return false;
4657
4658   return true;
4659 }
4660
4661 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4662 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4663 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4664 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4665   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4666   if (EltSz == 64)
4667     return false;
4668
4669   unsigned Half = VT.getVectorNumElements() / 2;
4670   WhichResult = (M[0] == 0 ? 0 : 1);
4671   for (unsigned j = 0; j != 2; ++j) {
4672     unsigned Idx = WhichResult;
4673     for (unsigned i = 0; i != Half; ++i) {
4674       int MIdx = M[i + j * Half];
4675       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4676         return false;
4677       Idx += 2;
4678     }
4679   }
4680
4681   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4682   if (VT.is64BitVector() && EltSz == 32)
4683     return false;
4684
4685   return true;
4686 }
4687
4688 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4689   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4690   if (EltSz == 64)
4691     return false;
4692
4693   unsigned NumElts = VT.getVectorNumElements();
4694   WhichResult = (M[0] == 0 ? 0 : 1);
4695   unsigned Idx = WhichResult * NumElts / 2;
4696   for (unsigned i = 0; i != NumElts; i += 2) {
4697     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4698         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4699       return false;
4700     Idx += 1;
4701   }
4702
4703   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4704   if (VT.is64BitVector() && EltSz == 32)
4705     return false;
4706
4707   return true;
4708 }
4709
4710 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4711 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4712 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4713 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4714   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4715   if (EltSz == 64)
4716     return false;
4717
4718   unsigned NumElts = VT.getVectorNumElements();
4719   WhichResult = (M[0] == 0 ? 0 : 1);
4720   unsigned Idx = WhichResult * NumElts / 2;
4721   for (unsigned i = 0; i != NumElts; i += 2) {
4722     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4723         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4724       return false;
4725     Idx += 1;
4726   }
4727
4728   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4729   if (VT.is64BitVector() && EltSz == 32)
4730     return false;
4731
4732   return true;
4733 }
4734
4735 /// \return true if this is a reverse operation on an vector.
4736 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4737   unsigned NumElts = VT.getVectorNumElements();
4738   // Make sure the mask has the right size.
4739   if (NumElts != M.size())
4740       return false;
4741
4742   // Look for <15, ..., 3, -1, 1, 0>.
4743   for (unsigned i = 0; i != NumElts; ++i)
4744     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4745       return false;
4746
4747   return true;
4748 }
4749
4750 // If N is an integer constant that can be moved into a register in one
4751 // instruction, return an SDValue of such a constant (will become a MOV
4752 // instruction).  Otherwise return null.
4753 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4754                                      const ARMSubtarget *ST, SDLoc dl) {
4755   uint64_t Val;
4756   if (!isa<ConstantSDNode>(N))
4757     return SDValue();
4758   Val = cast<ConstantSDNode>(N)->getZExtValue();
4759
4760   if (ST->isThumb1Only()) {
4761     if (Val <= 255 || ~Val <= 255)
4762       return DAG.getConstant(Val, MVT::i32);
4763   } else {
4764     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4765       return DAG.getConstant(Val, MVT::i32);
4766   }
4767   return SDValue();
4768 }
4769
4770 // If this is a case we can't handle, return null and let the default
4771 // expansion code take care of it.
4772 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4773                                              const ARMSubtarget *ST) const {
4774   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4775   SDLoc dl(Op);
4776   EVT VT = Op.getValueType();
4777
4778   APInt SplatBits, SplatUndef;
4779   unsigned SplatBitSize;
4780   bool HasAnyUndefs;
4781   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4782     if (SplatBitSize <= 64) {
4783       // Check if an immediate VMOV works.
4784       EVT VmovVT;
4785       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4786                                       SplatUndef.getZExtValue(), SplatBitSize,
4787                                       DAG, VmovVT, VT.is128BitVector(),
4788                                       VMOVModImm);
4789       if (Val.getNode()) {
4790         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4791         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4792       }
4793
4794       // Try an immediate VMVN.
4795       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4796       Val = isNEONModifiedImm(NegatedImm,
4797                                       SplatUndef.getZExtValue(), SplatBitSize,
4798                                       DAG, VmovVT, VT.is128BitVector(),
4799                                       VMVNModImm);
4800       if (Val.getNode()) {
4801         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4802         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4803       }
4804
4805       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4806       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4807         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4808         if (ImmVal != -1) {
4809           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4810           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4811         }
4812       }
4813     }
4814   }
4815
4816   // Scan through the operands to see if only one value is used.
4817   //
4818   // As an optimisation, even if more than one value is used it may be more
4819   // profitable to splat with one value then change some lanes.
4820   //
4821   // Heuristically we decide to do this if the vector has a "dominant" value,
4822   // defined as splatted to more than half of the lanes.
4823   unsigned NumElts = VT.getVectorNumElements();
4824   bool isOnlyLowElement = true;
4825   bool usesOnlyOneValue = true;
4826   bool hasDominantValue = false;
4827   bool isConstant = true;
4828
4829   // Map of the number of times a particular SDValue appears in the
4830   // element list.
4831   DenseMap<SDValue, unsigned> ValueCounts;
4832   SDValue Value;
4833   for (unsigned i = 0; i < NumElts; ++i) {
4834     SDValue V = Op.getOperand(i);
4835     if (V.getOpcode() == ISD::UNDEF)
4836       continue;
4837     if (i > 0)
4838       isOnlyLowElement = false;
4839     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4840       isConstant = false;
4841
4842     ValueCounts.insert(std::make_pair(V, 0));
4843     unsigned &Count = ValueCounts[V];
4844
4845     // Is this value dominant? (takes up more than half of the lanes)
4846     if (++Count > (NumElts / 2)) {
4847       hasDominantValue = true;
4848       Value = V;
4849     }
4850   }
4851   if (ValueCounts.size() != 1)
4852     usesOnlyOneValue = false;
4853   if (!Value.getNode() && ValueCounts.size() > 0)
4854     Value = ValueCounts.begin()->first;
4855
4856   if (ValueCounts.size() == 0)
4857     return DAG.getUNDEF(VT);
4858
4859   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
4860   // Keep going if we are hitting this case.
4861   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
4862     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4863
4864   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4865
4866   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4867   // i32 and try again.
4868   if (hasDominantValue && EltSize <= 32) {
4869     if (!isConstant) {
4870       SDValue N;
4871
4872       // If we are VDUPing a value that comes directly from a vector, that will
4873       // cause an unnecessary move to and from a GPR, where instead we could
4874       // just use VDUPLANE. We can only do this if the lane being extracted
4875       // is at a constant index, as the VDUP from lane instructions only have
4876       // constant-index forms.
4877       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4878           isa<ConstantSDNode>(Value->getOperand(1))) {
4879         // We need to create a new undef vector to use for the VDUPLANE if the
4880         // size of the vector from which we get the value is different than the
4881         // size of the vector that we need to create. We will insert the element
4882         // such that the register coalescer will remove unnecessary copies.
4883         if (VT != Value->getOperand(0).getValueType()) {
4884           ConstantSDNode *constIndex;
4885           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4886           assert(constIndex && "The index is not a constant!");
4887           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4888                              VT.getVectorNumElements();
4889           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4890                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4891                         Value, DAG.getConstant(index, MVT::i32)),
4892                            DAG.getConstant(index, MVT::i32));
4893         } else
4894           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4895                         Value->getOperand(0), Value->getOperand(1));
4896       } else
4897         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4898
4899       if (!usesOnlyOneValue) {
4900         // The dominant value was splatted as 'N', but we now have to insert
4901         // all differing elements.
4902         for (unsigned I = 0; I < NumElts; ++I) {
4903           if (Op.getOperand(I) == Value)
4904             continue;
4905           SmallVector<SDValue, 3> Ops;
4906           Ops.push_back(N);
4907           Ops.push_back(Op.getOperand(I));
4908           Ops.push_back(DAG.getConstant(I, MVT::i32));
4909           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4910         }
4911       }
4912       return N;
4913     }
4914     if (VT.getVectorElementType().isFloatingPoint()) {
4915       SmallVector<SDValue, 8> Ops;
4916       for (unsigned i = 0; i < NumElts; ++i)
4917         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4918                                   Op.getOperand(i)));
4919       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4920       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4921       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4922       if (Val.getNode())
4923         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4924     }
4925     if (usesOnlyOneValue) {
4926       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4927       if (isConstant && Val.getNode())
4928         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4929     }
4930   }
4931
4932   // If all elements are constants and the case above didn't get hit, fall back
4933   // to the default expansion, which will generate a load from the constant
4934   // pool.
4935   if (isConstant)
4936     return SDValue();
4937
4938   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4939   if (NumElts >= 4) {
4940     SDValue shuffle = ReconstructShuffle(Op, DAG);
4941     if (shuffle != SDValue())
4942       return shuffle;
4943   }
4944
4945   // Vectors with 32- or 64-bit elements can be built by directly assigning
4946   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4947   // will be legalized.
4948   if (EltSize >= 32) {
4949     // Do the expansion with floating-point types, since that is what the VFP
4950     // registers are defined to use, and since i64 is not legal.
4951     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4952     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4953     SmallVector<SDValue, 8> Ops;
4954     for (unsigned i = 0; i < NumElts; ++i)
4955       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4956     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4957     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4958   }
4959
4960   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
4961   // know the default expansion would otherwise fall back on something even
4962   // worse. For a vector with one or two non-undef values, that's
4963   // scalar_to_vector for the elements followed by a shuffle (provided the
4964   // shuffle is valid for the target) and materialization element by element
4965   // on the stack followed by a load for everything else.
4966   if (!isConstant && !usesOnlyOneValue) {
4967     SDValue Vec = DAG.getUNDEF(VT);
4968     for (unsigned i = 0 ; i < NumElts; ++i) {
4969       SDValue V = Op.getOperand(i);
4970       if (V.getOpcode() == ISD::UNDEF)
4971         continue;
4972       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
4973       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
4974     }
4975     return Vec;
4976   }
4977
4978   return SDValue();
4979 }
4980
4981 // Gather data to see if the operation can be modelled as a
4982 // shuffle in combination with VEXTs.
4983 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4984                                               SelectionDAG &DAG) const {
4985   SDLoc dl(Op);
4986   EVT VT = Op.getValueType();
4987   unsigned NumElts = VT.getVectorNumElements();
4988
4989   SmallVector<SDValue, 2> SourceVecs;
4990   SmallVector<unsigned, 2> MinElts;
4991   SmallVector<unsigned, 2> MaxElts;
4992
4993   for (unsigned i = 0; i < NumElts; ++i) {
4994     SDValue V = Op.getOperand(i);
4995     if (V.getOpcode() == ISD::UNDEF)
4996       continue;
4997     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4998       // A shuffle can only come from building a vector from various
4999       // elements of other vectors.
5000       return SDValue();
5001     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5002                VT.getVectorElementType()) {
5003       // This code doesn't know how to handle shuffles where the vector
5004       // element types do not match (this happens because type legalization
5005       // promotes the return type of EXTRACT_VECTOR_ELT).
5006       // FIXME: It might be appropriate to extend this code to handle
5007       // mismatched types.
5008       return SDValue();
5009     }
5010
5011     // Record this extraction against the appropriate vector if possible...
5012     SDValue SourceVec = V.getOperand(0);
5013     // If the element number isn't a constant, we can't effectively
5014     // analyze what's going on.
5015     if (!isa<ConstantSDNode>(V.getOperand(1)))
5016       return SDValue();
5017     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5018     bool FoundSource = false;
5019     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5020       if (SourceVecs[j] == SourceVec) {
5021         if (MinElts[j] > EltNo)
5022           MinElts[j] = EltNo;
5023         if (MaxElts[j] < EltNo)
5024           MaxElts[j] = EltNo;
5025         FoundSource = true;
5026         break;
5027       }
5028     }
5029
5030     // Or record a new source if not...
5031     if (!FoundSource) {
5032       SourceVecs.push_back(SourceVec);
5033       MinElts.push_back(EltNo);
5034       MaxElts.push_back(EltNo);
5035     }
5036   }
5037
5038   // Currently only do something sane when at most two source vectors
5039   // involved.
5040   if (SourceVecs.size() > 2)
5041     return SDValue();
5042
5043   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5044   int VEXTOffsets[2] = {0, 0};
5045
5046   // This loop extracts the usage patterns of the source vectors
5047   // and prepares appropriate SDValues for a shuffle if possible.
5048   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5049     if (SourceVecs[i].getValueType() == VT) {
5050       // No VEXT necessary
5051       ShuffleSrcs[i] = SourceVecs[i];
5052       VEXTOffsets[i] = 0;
5053       continue;
5054     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5055       // It probably isn't worth padding out a smaller vector just to
5056       // break it down again in a shuffle.
5057       return SDValue();
5058     }
5059
5060     // Since only 64-bit and 128-bit vectors are legal on ARM and
5061     // we've eliminated the other cases...
5062     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5063            "unexpected vector sizes in ReconstructShuffle");
5064
5065     if (MaxElts[i] - MinElts[i] >= NumElts) {
5066       // Span too large for a VEXT to cope
5067       return SDValue();
5068     }
5069
5070     if (MinElts[i] >= NumElts) {
5071       // The extraction can just take the second half
5072       VEXTOffsets[i] = NumElts;
5073       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5074                                    SourceVecs[i],
5075                                    DAG.getIntPtrConstant(NumElts));
5076     } else if (MaxElts[i] < NumElts) {
5077       // The extraction can just take the first half
5078       VEXTOffsets[i] = 0;
5079       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5080                                    SourceVecs[i],
5081                                    DAG.getIntPtrConstant(0));
5082     } else {
5083       // An actual VEXT is needed
5084       VEXTOffsets[i] = MinElts[i];
5085       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5086                                      SourceVecs[i],
5087                                      DAG.getIntPtrConstant(0));
5088       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5089                                      SourceVecs[i],
5090                                      DAG.getIntPtrConstant(NumElts));
5091       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5092                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5093     }
5094   }
5095
5096   SmallVector<int, 8> Mask;
5097
5098   for (unsigned i = 0; i < NumElts; ++i) {
5099     SDValue Entry = Op.getOperand(i);
5100     if (Entry.getOpcode() == ISD::UNDEF) {
5101       Mask.push_back(-1);
5102       continue;
5103     }
5104
5105     SDValue ExtractVec = Entry.getOperand(0);
5106     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5107                                           .getOperand(1))->getSExtValue();
5108     if (ExtractVec == SourceVecs[0]) {
5109       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5110     } else {
5111       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5112     }
5113   }
5114
5115   // Final check before we try to produce nonsense...
5116   if (isShuffleMaskLegal(Mask, VT))
5117     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5118                                 &Mask[0]);
5119
5120   return SDValue();
5121 }
5122
5123 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5124 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5125 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5126 /// are assumed to be legal.
5127 bool
5128 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5129                                       EVT VT) const {
5130   if (VT.getVectorNumElements() == 4 &&
5131       (VT.is128BitVector() || VT.is64BitVector())) {
5132     unsigned PFIndexes[4];
5133     for (unsigned i = 0; i != 4; ++i) {
5134       if (M[i] < 0)
5135         PFIndexes[i] = 8;
5136       else
5137         PFIndexes[i] = M[i];
5138     }
5139
5140     // Compute the index in the perfect shuffle table.
5141     unsigned PFTableIndex =
5142       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5143     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5144     unsigned Cost = (PFEntry >> 30);
5145
5146     if (Cost <= 4)
5147       return true;
5148   }
5149
5150   bool ReverseVEXT;
5151   unsigned Imm, WhichResult;
5152
5153   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5154   return (EltSize >= 32 ||
5155           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5156           isVREVMask(M, VT, 64) ||
5157           isVREVMask(M, VT, 32) ||
5158           isVREVMask(M, VT, 16) ||
5159           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5160           isVTBLMask(M, VT) ||
5161           isVTRNMask(M, VT, WhichResult) ||
5162           isVUZPMask(M, VT, WhichResult) ||
5163           isVZIPMask(M, VT, WhichResult) ||
5164           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5165           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5166           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5167           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5168 }
5169
5170 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5171 /// the specified operations to build the shuffle.
5172 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5173                                       SDValue RHS, SelectionDAG &DAG,
5174                                       SDLoc dl) {
5175   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5176   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5177   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5178
5179   enum {
5180     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5181     OP_VREV,
5182     OP_VDUP0,
5183     OP_VDUP1,
5184     OP_VDUP2,
5185     OP_VDUP3,
5186     OP_VEXT1,
5187     OP_VEXT2,
5188     OP_VEXT3,
5189     OP_VUZPL, // VUZP, left result
5190     OP_VUZPR, // VUZP, right result
5191     OP_VZIPL, // VZIP, left result
5192     OP_VZIPR, // VZIP, right result
5193     OP_VTRNL, // VTRN, left result
5194     OP_VTRNR  // VTRN, right result
5195   };
5196
5197   if (OpNum == OP_COPY) {
5198     if (LHSID == (1*9+2)*9+3) return LHS;
5199     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5200     return RHS;
5201   }
5202
5203   SDValue OpLHS, OpRHS;
5204   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5205   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5206   EVT VT = OpLHS.getValueType();
5207
5208   switch (OpNum) {
5209   default: llvm_unreachable("Unknown shuffle opcode!");
5210   case OP_VREV:
5211     // VREV divides the vector in half and swaps within the half.
5212     if (VT.getVectorElementType() == MVT::i32 ||
5213         VT.getVectorElementType() == MVT::f32)
5214       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5215     // vrev <4 x i16> -> VREV32
5216     if (VT.getVectorElementType() == MVT::i16)
5217       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5218     // vrev <4 x i8> -> VREV16
5219     assert(VT.getVectorElementType() == MVT::i8);
5220     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5221   case OP_VDUP0:
5222   case OP_VDUP1:
5223   case OP_VDUP2:
5224   case OP_VDUP3:
5225     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5226                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5227   case OP_VEXT1:
5228   case OP_VEXT2:
5229   case OP_VEXT3:
5230     return DAG.getNode(ARMISD::VEXT, dl, VT,
5231                        OpLHS, OpRHS,
5232                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5233   case OP_VUZPL:
5234   case OP_VUZPR:
5235     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5236                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5237   case OP_VZIPL:
5238   case OP_VZIPR:
5239     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5240                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5241   case OP_VTRNL:
5242   case OP_VTRNR:
5243     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5244                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5245   }
5246 }
5247
5248 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5249                                        ArrayRef<int> ShuffleMask,
5250                                        SelectionDAG &DAG) {
5251   // Check to see if we can use the VTBL instruction.
5252   SDValue V1 = Op.getOperand(0);
5253   SDValue V2 = Op.getOperand(1);
5254   SDLoc DL(Op);
5255
5256   SmallVector<SDValue, 8> VTBLMask;
5257   for (ArrayRef<int>::iterator
5258          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5259     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5260
5261   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5262     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5263                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5264                                    &VTBLMask[0], 8));
5265
5266   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5267                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5268                                  &VTBLMask[0], 8));
5269 }
5270
5271 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5272                                                       SelectionDAG &DAG) {
5273   SDLoc DL(Op);
5274   SDValue OpLHS = Op.getOperand(0);
5275   EVT VT = OpLHS.getValueType();
5276
5277   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5278          "Expect an v8i16/v16i8 type");
5279   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5280   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5281   // extract the first 8 bytes into the top double word and the last 8 bytes
5282   // into the bottom double word. The v8i16 case is similar.
5283   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5284   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5285                      DAG.getConstant(ExtractNum, MVT::i32));
5286 }
5287
5288 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5289   SDValue V1 = Op.getOperand(0);
5290   SDValue V2 = Op.getOperand(1);
5291   SDLoc dl(Op);
5292   EVT VT = Op.getValueType();
5293   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5294
5295   // Convert shuffles that are directly supported on NEON to target-specific
5296   // DAG nodes, instead of keeping them as shuffles and matching them again
5297   // during code selection.  This is more efficient and avoids the possibility
5298   // of inconsistencies between legalization and selection.
5299   // FIXME: floating-point vectors should be canonicalized to integer vectors
5300   // of the same time so that they get CSEd properly.
5301   ArrayRef<int> ShuffleMask = SVN->getMask();
5302
5303   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5304   if (EltSize <= 32) {
5305     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5306       int Lane = SVN->getSplatIndex();
5307       // If this is undef splat, generate it via "just" vdup, if possible.
5308       if (Lane == -1) Lane = 0;
5309
5310       // Test if V1 is a SCALAR_TO_VECTOR.
5311       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5312         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5313       }
5314       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5315       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5316       // reaches it).
5317       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5318           !isa<ConstantSDNode>(V1.getOperand(0))) {
5319         bool IsScalarToVector = true;
5320         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5321           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5322             IsScalarToVector = false;
5323             break;
5324           }
5325         if (IsScalarToVector)
5326           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5327       }
5328       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5329                          DAG.getConstant(Lane, MVT::i32));
5330     }
5331
5332     bool ReverseVEXT;
5333     unsigned Imm;
5334     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5335       if (ReverseVEXT)
5336         std::swap(V1, V2);
5337       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5338                          DAG.getConstant(Imm, MVT::i32));
5339     }
5340
5341     if (isVREVMask(ShuffleMask, VT, 64))
5342       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5343     if (isVREVMask(ShuffleMask, VT, 32))
5344       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5345     if (isVREVMask(ShuffleMask, VT, 16))
5346       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5347
5348     if (V2->getOpcode() == ISD::UNDEF &&
5349         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5350       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5351                          DAG.getConstant(Imm, MVT::i32));
5352     }
5353
5354     // Check for Neon shuffles that modify both input vectors in place.
5355     // If both results are used, i.e., if there are two shuffles with the same
5356     // source operands and with masks corresponding to both results of one of
5357     // these operations, DAG memoization will ensure that a single node is
5358     // used for both shuffles.
5359     unsigned WhichResult;
5360     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5361       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5362                          V1, V2).getValue(WhichResult);
5363     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5364       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5365                          V1, V2).getValue(WhichResult);
5366     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5367       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5368                          V1, V2).getValue(WhichResult);
5369
5370     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5371       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5372                          V1, V1).getValue(WhichResult);
5373     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5374       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5375                          V1, V1).getValue(WhichResult);
5376     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5377       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5378                          V1, V1).getValue(WhichResult);
5379   }
5380
5381   // If the shuffle is not directly supported and it has 4 elements, use
5382   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5383   unsigned NumElts = VT.getVectorNumElements();
5384   if (NumElts == 4) {
5385     unsigned PFIndexes[4];
5386     for (unsigned i = 0; i != 4; ++i) {
5387       if (ShuffleMask[i] < 0)
5388         PFIndexes[i] = 8;
5389       else
5390         PFIndexes[i] = ShuffleMask[i];
5391     }
5392
5393     // Compute the index in the perfect shuffle table.
5394     unsigned PFTableIndex =
5395       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5396     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5397     unsigned Cost = (PFEntry >> 30);
5398
5399     if (Cost <= 4)
5400       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5401   }
5402
5403   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5404   if (EltSize >= 32) {
5405     // Do the expansion with floating-point types, since that is what the VFP
5406     // registers are defined to use, and since i64 is not legal.
5407     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5408     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5409     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5410     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5411     SmallVector<SDValue, 8> Ops;
5412     for (unsigned i = 0; i < NumElts; ++i) {
5413       if (ShuffleMask[i] < 0)
5414         Ops.push_back(DAG.getUNDEF(EltVT));
5415       else
5416         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5417                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5418                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5419                                                   MVT::i32)));
5420     }
5421     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5422     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5423   }
5424
5425   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5426     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5427
5428   if (VT == MVT::v8i8) {
5429     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5430     if (NewOp.getNode())
5431       return NewOp;
5432   }
5433
5434   return SDValue();
5435 }
5436
5437 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5438   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5439   SDValue Lane = Op.getOperand(2);
5440   if (!isa<ConstantSDNode>(Lane))
5441     return SDValue();
5442
5443   return Op;
5444 }
5445
5446 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5447   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5448   SDValue Lane = Op.getOperand(1);
5449   if (!isa<ConstantSDNode>(Lane))
5450     return SDValue();
5451
5452   SDValue Vec = Op.getOperand(0);
5453   if (Op.getValueType() == MVT::i32 &&
5454       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5455     SDLoc dl(Op);
5456     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5457   }
5458
5459   return Op;
5460 }
5461
5462 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5463   // The only time a CONCAT_VECTORS operation can have legal types is when
5464   // two 64-bit vectors are concatenated to a 128-bit vector.
5465   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5466          "unexpected CONCAT_VECTORS");
5467   SDLoc dl(Op);
5468   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5469   SDValue Op0 = Op.getOperand(0);
5470   SDValue Op1 = Op.getOperand(1);
5471   if (Op0.getOpcode() != ISD::UNDEF)
5472     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5473                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5474                       DAG.getIntPtrConstant(0));
5475   if (Op1.getOpcode() != ISD::UNDEF)
5476     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5477                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5478                       DAG.getIntPtrConstant(1));
5479   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5480 }
5481
5482 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5483 /// element has been zero/sign-extended, depending on the isSigned parameter,
5484 /// from an integer type half its size.
5485 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5486                                    bool isSigned) {
5487   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5488   EVT VT = N->getValueType(0);
5489   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5490     SDNode *BVN = N->getOperand(0).getNode();
5491     if (BVN->getValueType(0) != MVT::v4i32 ||
5492         BVN->getOpcode() != ISD::BUILD_VECTOR)
5493       return false;
5494     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5495     unsigned HiElt = 1 - LoElt;
5496     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5497     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5498     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5499     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5500     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5501       return false;
5502     if (isSigned) {
5503       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5504           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5505         return true;
5506     } else {
5507       if (Hi0->isNullValue() && Hi1->isNullValue())
5508         return true;
5509     }
5510     return false;
5511   }
5512
5513   if (N->getOpcode() != ISD::BUILD_VECTOR)
5514     return false;
5515
5516   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5517     SDNode *Elt = N->getOperand(i).getNode();
5518     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5519       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5520       unsigned HalfSize = EltSize / 2;
5521       if (isSigned) {
5522         if (!isIntN(HalfSize, C->getSExtValue()))
5523           return false;
5524       } else {
5525         if (!isUIntN(HalfSize, C->getZExtValue()))
5526           return false;
5527       }
5528       continue;
5529     }
5530     return false;
5531   }
5532
5533   return true;
5534 }
5535
5536 /// isSignExtended - Check if a node is a vector value that is sign-extended
5537 /// or a constant BUILD_VECTOR with sign-extended elements.
5538 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5539   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5540     return true;
5541   if (isExtendedBUILD_VECTOR(N, DAG, true))
5542     return true;
5543   return false;
5544 }
5545
5546 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5547 /// or a constant BUILD_VECTOR with zero-extended elements.
5548 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5549   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5550     return true;
5551   if (isExtendedBUILD_VECTOR(N, DAG, false))
5552     return true;
5553   return false;
5554 }
5555
5556 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5557   if (OrigVT.getSizeInBits() >= 64)
5558     return OrigVT;
5559
5560   assert(OrigVT.isSimple() && "Expecting a simple value type");
5561
5562   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5563   switch (OrigSimpleTy) {
5564   default: llvm_unreachable("Unexpected Vector Type");
5565   case MVT::v2i8:
5566   case MVT::v2i16:
5567      return MVT::v2i32;
5568   case MVT::v4i8:
5569     return  MVT::v4i16;
5570   }
5571 }
5572
5573 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5574 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5575 /// We insert the required extension here to get the vector to fill a D register.
5576 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5577                                             const EVT &OrigTy,
5578                                             const EVT &ExtTy,
5579                                             unsigned ExtOpcode) {
5580   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5581   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5582   // 64-bits we need to insert a new extension so that it will be 64-bits.
5583   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5584   if (OrigTy.getSizeInBits() >= 64)
5585     return N;
5586
5587   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5588   EVT NewVT = getExtensionTo64Bits(OrigTy);
5589
5590   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5591 }
5592
5593 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5594 /// does not do any sign/zero extension. If the original vector is less
5595 /// than 64 bits, an appropriate extension will be added after the load to
5596 /// reach a total size of 64 bits. We have to add the extension separately
5597 /// because ARM does not have a sign/zero extending load for vectors.
5598 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5599   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5600
5601   // The load already has the right type.
5602   if (ExtendedTy == LD->getMemoryVT())
5603     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5604                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5605                 LD->isNonTemporal(), LD->isInvariant(),
5606                 LD->getAlignment());
5607
5608   // We need to create a zextload/sextload. We cannot just create a load
5609   // followed by a zext/zext node because LowerMUL is also run during normal
5610   // operation legalization where we can't create illegal types.
5611   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5612                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5613                         LD->getMemoryVT(), LD->isVolatile(),
5614                         LD->isNonTemporal(), LD->getAlignment());
5615 }
5616
5617 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5618 /// extending load, or BUILD_VECTOR with extended elements, return the
5619 /// unextended value. The unextended vector should be 64 bits so that it can
5620 /// be used as an operand to a VMULL instruction. If the original vector size
5621 /// before extension is less than 64 bits we add a an extension to resize
5622 /// the vector to 64 bits.
5623 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5624   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5625     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5626                                         N->getOperand(0)->getValueType(0),
5627                                         N->getValueType(0),
5628                                         N->getOpcode());
5629
5630   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5631     return SkipLoadExtensionForVMULL(LD, DAG);
5632
5633   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5634   // have been legalized as a BITCAST from v4i32.
5635   if (N->getOpcode() == ISD::BITCAST) {
5636     SDNode *BVN = N->getOperand(0).getNode();
5637     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5638            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5639     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5640     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5641                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5642   }
5643   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5644   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5645   EVT VT = N->getValueType(0);
5646   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5647   unsigned NumElts = VT.getVectorNumElements();
5648   MVT TruncVT = MVT::getIntegerVT(EltSize);
5649   SmallVector<SDValue, 8> Ops;
5650   for (unsigned i = 0; i != NumElts; ++i) {
5651     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5652     const APInt &CInt = C->getAPIntValue();
5653     // Element types smaller than 32 bits are not legal, so use i32 elements.
5654     // The values are implicitly truncated so sext vs. zext doesn't matter.
5655     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5656   }
5657   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5658                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5659 }
5660
5661 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5662   unsigned Opcode = N->getOpcode();
5663   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5664     SDNode *N0 = N->getOperand(0).getNode();
5665     SDNode *N1 = N->getOperand(1).getNode();
5666     return N0->hasOneUse() && N1->hasOneUse() &&
5667       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5668   }
5669   return false;
5670 }
5671
5672 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5673   unsigned Opcode = N->getOpcode();
5674   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5675     SDNode *N0 = N->getOperand(0).getNode();
5676     SDNode *N1 = N->getOperand(1).getNode();
5677     return N0->hasOneUse() && N1->hasOneUse() &&
5678       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5679   }
5680   return false;
5681 }
5682
5683 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5684   // Multiplications are only custom-lowered for 128-bit vectors so that
5685   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5686   EVT VT = Op.getValueType();
5687   assert(VT.is128BitVector() && VT.isInteger() &&
5688          "unexpected type for custom-lowering ISD::MUL");
5689   SDNode *N0 = Op.getOperand(0).getNode();
5690   SDNode *N1 = Op.getOperand(1).getNode();
5691   unsigned NewOpc = 0;
5692   bool isMLA = false;
5693   bool isN0SExt = isSignExtended(N0, DAG);
5694   bool isN1SExt = isSignExtended(N1, DAG);
5695   if (isN0SExt && isN1SExt)
5696     NewOpc = ARMISD::VMULLs;
5697   else {
5698     bool isN0ZExt = isZeroExtended(N0, DAG);
5699     bool isN1ZExt = isZeroExtended(N1, DAG);
5700     if (isN0ZExt && isN1ZExt)
5701       NewOpc = ARMISD::VMULLu;
5702     else if (isN1SExt || isN1ZExt) {
5703       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5704       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5705       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5706         NewOpc = ARMISD::VMULLs;
5707         isMLA = true;
5708       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5709         NewOpc = ARMISD::VMULLu;
5710         isMLA = true;
5711       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5712         std::swap(N0, N1);
5713         NewOpc = ARMISD::VMULLu;
5714         isMLA = true;
5715       }
5716     }
5717
5718     if (!NewOpc) {
5719       if (VT == MVT::v2i64)
5720         // Fall through to expand this.  It is not legal.
5721         return SDValue();
5722       else
5723         // Other vector multiplications are legal.
5724         return Op;
5725     }
5726   }
5727
5728   // Legalize to a VMULL instruction.
5729   SDLoc DL(Op);
5730   SDValue Op0;
5731   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5732   if (!isMLA) {
5733     Op0 = SkipExtensionForVMULL(N0, DAG);
5734     assert(Op0.getValueType().is64BitVector() &&
5735            Op1.getValueType().is64BitVector() &&
5736            "unexpected types for extended operands to VMULL");
5737     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5738   }
5739
5740   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5741   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5742   //   vmull q0, d4, d6
5743   //   vmlal q0, d5, d6
5744   // is faster than
5745   //   vaddl q0, d4, d5
5746   //   vmovl q1, d6
5747   //   vmul  q0, q0, q1
5748   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5749   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5750   EVT Op1VT = Op1.getValueType();
5751   return DAG.getNode(N0->getOpcode(), DL, VT,
5752                      DAG.getNode(NewOpc, DL, VT,
5753                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5754                      DAG.getNode(NewOpc, DL, VT,
5755                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5756 }
5757
5758 static SDValue
5759 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5760   // Convert to float
5761   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5762   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5763   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5764   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5765   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5766   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5767   // Get reciprocal estimate.
5768   // float4 recip = vrecpeq_f32(yf);
5769   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5770                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5771   // Because char has a smaller range than uchar, we can actually get away
5772   // without any newton steps.  This requires that we use a weird bias
5773   // of 0xb000, however (again, this has been exhaustively tested).
5774   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5775   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5776   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5777   Y = DAG.getConstant(0xb000, MVT::i32);
5778   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5779   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5780   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5781   // Convert back to short.
5782   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5783   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5784   return X;
5785 }
5786
5787 static SDValue
5788 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5789   SDValue N2;
5790   // Convert to float.
5791   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5792   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5793   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5794   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5795   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5796   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5797
5798   // Use reciprocal estimate and one refinement step.
5799   // float4 recip = vrecpeq_f32(yf);
5800   // recip *= vrecpsq_f32(yf, recip);
5801   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5802                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5803   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5804                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5805                    N1, N2);
5806   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5807   // Because short has a smaller range than ushort, we can actually get away
5808   // with only a single newton step.  This requires that we use a weird bias
5809   // of 89, however (again, this has been exhaustively tested).
5810   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5811   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5812   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5813   N1 = DAG.getConstant(0x89, MVT::i32);
5814   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5815   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5816   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5817   // Convert back to integer and return.
5818   // return vmovn_s32(vcvt_s32_f32(result));
5819   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5820   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5821   return N0;
5822 }
5823
5824 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5825   EVT VT = Op.getValueType();
5826   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5827          "unexpected type for custom-lowering ISD::SDIV");
5828
5829   SDLoc dl(Op);
5830   SDValue N0 = Op.getOperand(0);
5831   SDValue N1 = Op.getOperand(1);
5832   SDValue N2, N3;
5833
5834   if (VT == MVT::v8i8) {
5835     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5836     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5837
5838     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5839                      DAG.getIntPtrConstant(4));
5840     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5841                      DAG.getIntPtrConstant(4));
5842     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5843                      DAG.getIntPtrConstant(0));
5844     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5845                      DAG.getIntPtrConstant(0));
5846
5847     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5848     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5849
5850     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5851     N0 = LowerCONCAT_VECTORS(N0, DAG);
5852
5853     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5854     return N0;
5855   }
5856   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5857 }
5858
5859 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5860   EVT VT = Op.getValueType();
5861   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5862          "unexpected type for custom-lowering ISD::UDIV");
5863
5864   SDLoc dl(Op);
5865   SDValue N0 = Op.getOperand(0);
5866   SDValue N1 = Op.getOperand(1);
5867   SDValue N2, N3;
5868
5869   if (VT == MVT::v8i8) {
5870     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5871     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5872
5873     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5874                      DAG.getIntPtrConstant(4));
5875     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5876                      DAG.getIntPtrConstant(4));
5877     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5878                      DAG.getIntPtrConstant(0));
5879     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5880                      DAG.getIntPtrConstant(0));
5881
5882     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5883     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5884
5885     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5886     N0 = LowerCONCAT_VECTORS(N0, DAG);
5887
5888     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5889                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5890                      N0);
5891     return N0;
5892   }
5893
5894   // v4i16 sdiv ... Convert to float.
5895   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5896   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5897   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5898   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5899   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5900   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5901
5902   // Use reciprocal estimate and two refinement steps.
5903   // float4 recip = vrecpeq_f32(yf);
5904   // recip *= vrecpsq_f32(yf, recip);
5905   // recip *= vrecpsq_f32(yf, recip);
5906   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5907                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5908   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5909                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5910                    BN1, N2);
5911   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5912   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5913                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5914                    BN1, N2);
5915   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5916   // Simply multiplying by the reciprocal estimate can leave us a few ulps
5917   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5918   // and that it will never cause us to return an answer too large).
5919   // float4 result = as_float4(as_int4(xf*recip) + 2);
5920   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5921   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5922   N1 = DAG.getConstant(2, MVT::i32);
5923   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5924   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5925   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5926   // Convert back to integer and return.
5927   // return vmovn_u32(vcvt_s32_f32(result));
5928   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5929   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5930   return N0;
5931 }
5932
5933 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5934   EVT VT = Op.getNode()->getValueType(0);
5935   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5936
5937   unsigned Opc;
5938   bool ExtraOp = false;
5939   switch (Op.getOpcode()) {
5940   default: llvm_unreachable("Invalid code");
5941   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5942   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5943   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5944   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5945   }
5946
5947   if (!ExtraOp)
5948     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5949                        Op.getOperand(1));
5950   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5951                      Op.getOperand(1), Op.getOperand(2));
5952 }
5953
5954 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
5955   assert(Subtarget->isTargetDarwin());
5956
5957   // For iOS, we want to call an alternative entry point: __sincos_stret,
5958   // return values are passed via sret.
5959   SDLoc dl(Op);
5960   SDValue Arg = Op.getOperand(0);
5961   EVT ArgVT = Arg.getValueType();
5962   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
5963
5964   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
5965   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5966
5967   // Pair of floats / doubles used to pass the result.
5968   StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
5969
5970   // Create stack object for sret.
5971   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
5972   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
5973   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
5974   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
5975
5976   ArgListTy Args;
5977   ArgListEntry Entry;
5978
5979   Entry.Node = SRet;
5980   Entry.Ty = RetTy->getPointerTo();
5981   Entry.isSExt = false;
5982   Entry.isZExt = false;
5983   Entry.isSRet = true;
5984   Args.push_back(Entry);
5985
5986   Entry.Node = Arg;
5987   Entry.Ty = ArgTy;
5988   Entry.isSExt = false;
5989   Entry.isZExt = false;
5990   Args.push_back(Entry);
5991
5992   const char *LibcallName  = (ArgVT == MVT::f64)
5993   ? "__sincos_stret" : "__sincosf_stret";
5994   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
5995
5996   TargetLowering::
5997   CallLoweringInfo CLI(DAG.getEntryNode(), Type::getVoidTy(*DAG.getContext()),
5998                        false, false, false, false, 0,
5999                        CallingConv::C, /*isTaillCall=*/false,
6000                        /*doesNotRet=*/false, /*isReturnValueUsed*/false,
6001                        Callee, Args, DAG, dl);
6002   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6003
6004   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6005                                 MachinePointerInfo(), false, false, false, 0);
6006
6007   // Address of cos field.
6008   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6009                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6010   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6011                                 MachinePointerInfo(), false, false, false, 0);
6012
6013   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6014   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6015                      LoadSin.getValue(0), LoadCos.getValue(0));
6016 }
6017
6018 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6019   // Monotonic load/store is legal for all targets
6020   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6021     return Op;
6022
6023   // Acquire/Release load/store is not legal for targets without a
6024   // dmb or equivalent available.
6025   return SDValue();
6026 }
6027
6028 static void
6029 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
6030                     SelectionDAG &DAG) {
6031   SDLoc dl(Node);
6032   assert (Node->getValueType(0) == MVT::i64 &&
6033           "Only know how to expand i64 atomics");
6034   AtomicSDNode *AN = cast<AtomicSDNode>(Node);
6035
6036   SmallVector<SDValue, 6> Ops;
6037   Ops.push_back(Node->getOperand(0)); // Chain
6038   Ops.push_back(Node->getOperand(1)); // Ptr
6039   for(unsigned i=2; i<Node->getNumOperands(); i++) {
6040     // Low part
6041     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6042                               Node->getOperand(i), DAG.getIntPtrConstant(0)));
6043     // High part
6044     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6045                               Node->getOperand(i), DAG.getIntPtrConstant(1)));
6046   }
6047   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6048   SDValue Result = DAG.getAtomic(
6049       Node->getOpcode(), dl, MVT::i64, Tys, Ops.data(), Ops.size(),
6050       cast<MemSDNode>(Node)->getMemOperand(), AN->getSuccessOrdering(),
6051       AN->getFailureOrdering(), AN->getSynchScope());
6052   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
6053   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6054   Results.push_back(Result.getValue(2));
6055 }
6056
6057 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6058                                     SmallVectorImpl<SDValue> &Results,
6059                                     SelectionDAG &DAG,
6060                                     const ARMSubtarget *Subtarget) {
6061   SDLoc DL(N);
6062   SDValue Cycles32, OutChain;
6063
6064   if (Subtarget->hasPerfMon()) {
6065     // Under Power Management extensions, the cycle-count is:
6066     //    mrc p15, #0, <Rt>, c9, c13, #0
6067     SDValue Ops[] = { N->getOperand(0), // Chain
6068                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6069                       DAG.getConstant(15, MVT::i32),
6070                       DAG.getConstant(0, MVT::i32),
6071                       DAG.getConstant(9, MVT::i32),
6072                       DAG.getConstant(13, MVT::i32),
6073                       DAG.getConstant(0, MVT::i32)
6074     };
6075
6076     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6077                            DAG.getVTList(MVT::i32, MVT::Other), &Ops[0],
6078                            array_lengthof(Ops));
6079     OutChain = Cycles32.getValue(1);
6080   } else {
6081     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6082     // there are older ARM CPUs that have implementation-specific ways of
6083     // obtaining this information (FIXME!).
6084     Cycles32 = DAG.getConstant(0, MVT::i32);
6085     OutChain = DAG.getEntryNode();
6086   }
6087
6088
6089   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6090                                  Cycles32, DAG.getConstant(0, MVT::i32));
6091   Results.push_back(Cycles64);
6092   Results.push_back(OutChain);
6093 }
6094
6095 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6096   switch (Op.getOpcode()) {
6097   default: llvm_unreachable("Don't know how to custom lower this!");
6098   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6099   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6100   case ISD::GlobalAddress:
6101     return Subtarget->isTargetMachO() ? LowerGlobalAddressDarwin(Op, DAG) :
6102       LowerGlobalAddressELF(Op, DAG);
6103   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6104   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6105   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6106   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6107   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6108   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6109   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6110   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6111   case ISD::SINT_TO_FP:
6112   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6113   case ISD::FP_TO_SINT:
6114   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6115   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6116   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6117   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6118   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6119   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6120   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6121   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6122                                                                Subtarget);
6123   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6124   case ISD::SHL:
6125   case ISD::SRL:
6126   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6127   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6128   case ISD::SRL_PARTS:
6129   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6130   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6131   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6132   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6133   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6134   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6135   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6136   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6137   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6138   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6139   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6140   case ISD::MUL:           return LowerMUL(Op, DAG);
6141   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6142   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6143   case ISD::ADDC:
6144   case ISD::ADDE:
6145   case ISD::SUBC:
6146   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6147   case ISD::ATOMIC_LOAD:
6148   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6149   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6150   case ISD::SDIVREM:
6151   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6152   }
6153 }
6154
6155 /// ReplaceNodeResults - Replace the results of node with an illegal result
6156 /// type with new values built out of custom code.
6157 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6158                                            SmallVectorImpl<SDValue>&Results,
6159                                            SelectionDAG &DAG) const {
6160   SDValue Res;
6161   switch (N->getOpcode()) {
6162   default:
6163     llvm_unreachable("Don't know how to custom expand this!");
6164   case ISD::BITCAST:
6165     Res = ExpandBITCAST(N, DAG);
6166     break;
6167   case ISD::SRL:
6168   case ISD::SRA:
6169     Res = Expand64BitShift(N, DAG, Subtarget);
6170     break;
6171   case ISD::READCYCLECOUNTER:
6172     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6173     return;
6174   case ISD::ATOMIC_STORE:
6175   case ISD::ATOMIC_LOAD:
6176   case ISD::ATOMIC_LOAD_ADD:
6177   case ISD::ATOMIC_LOAD_AND:
6178   case ISD::ATOMIC_LOAD_NAND:
6179   case ISD::ATOMIC_LOAD_OR:
6180   case ISD::ATOMIC_LOAD_SUB:
6181   case ISD::ATOMIC_LOAD_XOR:
6182   case ISD::ATOMIC_SWAP:
6183   case ISD::ATOMIC_CMP_SWAP:
6184   case ISD::ATOMIC_LOAD_MIN:
6185   case ISD::ATOMIC_LOAD_UMIN:
6186   case ISD::ATOMIC_LOAD_MAX:
6187   case ISD::ATOMIC_LOAD_UMAX:
6188     ReplaceATOMIC_OP_64(N, Results, DAG);
6189     return;
6190   }
6191   if (Res.getNode())
6192     Results.push_back(Res);
6193 }
6194
6195 //===----------------------------------------------------------------------===//
6196 //                           ARM Scheduler Hooks
6197 //===----------------------------------------------------------------------===//
6198
6199 MachineBasicBlock *
6200 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
6201                                      MachineBasicBlock *BB,
6202                                      unsigned Size) const {
6203   unsigned dest    = MI->getOperand(0).getReg();
6204   unsigned ptr     = MI->getOperand(1).getReg();
6205   unsigned oldval  = MI->getOperand(2).getReg();
6206   unsigned newval  = MI->getOperand(3).getReg();
6207   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6208   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(4).getImm());
6209   DebugLoc dl = MI->getDebugLoc();
6210   bool isThumb2 = Subtarget->isThumb2();
6211
6212   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6213   unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
6214     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6215     (const TargetRegisterClass*)&ARM::GPRRegClass);
6216
6217   if (isThumb2) {
6218     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6219     MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
6220     MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
6221   }
6222
6223   unsigned ldrOpc, strOpc;
6224   getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6225
6226   MachineFunction *MF = BB->getParent();
6227   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6228   MachineFunction::iterator It = BB;
6229   ++It; // insert the new blocks after the current block
6230
6231   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6232   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6233   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6234   MF->insert(It, loop1MBB);
6235   MF->insert(It, loop2MBB);
6236   MF->insert(It, exitMBB);
6237
6238   // Transfer the remainder of BB and its successor edges to exitMBB.
6239   exitMBB->splice(exitMBB->begin(), BB,
6240                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6241   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6242
6243   //  thisMBB:
6244   //   ...
6245   //   fallthrough --> loop1MBB
6246   BB->addSuccessor(loop1MBB);
6247
6248   // loop1MBB:
6249   //   ldrex dest, [ptr]
6250   //   cmp dest, oldval
6251   //   bne exitMBB
6252   BB = loop1MBB;
6253   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6254   if (ldrOpc == ARM::t2LDREX)
6255     MIB.addImm(0);
6256   AddDefaultPred(MIB);
6257   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6258                  .addReg(dest).addReg(oldval));
6259   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6260     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6261   BB->addSuccessor(loop2MBB);
6262   BB->addSuccessor(exitMBB);
6263
6264   // loop2MBB:
6265   //   strex scratch, newval, [ptr]
6266   //   cmp scratch, #0
6267   //   bne loop1MBB
6268   BB = loop2MBB;
6269   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
6270   if (strOpc == ARM::t2STREX)
6271     MIB.addImm(0);
6272   AddDefaultPred(MIB);
6273   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6274                  .addReg(scratch).addImm(0));
6275   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6276     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6277   BB->addSuccessor(loop1MBB);
6278   BB->addSuccessor(exitMBB);
6279
6280   //  exitMBB:
6281   //   ...
6282   BB = exitMBB;
6283
6284   MI->eraseFromParent();   // The instruction is gone now.
6285
6286   return BB;
6287 }
6288
6289 MachineBasicBlock *
6290 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6291                                     unsigned Size, unsigned BinOpcode) const {
6292   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6293   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6294
6295   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6296   MachineFunction *MF = BB->getParent();
6297   MachineFunction::iterator It = BB;
6298   ++It;
6299
6300   unsigned dest = MI->getOperand(0).getReg();
6301   unsigned ptr = MI->getOperand(1).getReg();
6302   unsigned incr = MI->getOperand(2).getReg();
6303   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6304   DebugLoc dl = MI->getDebugLoc();
6305   bool isThumb2 = Subtarget->isThumb2();
6306
6307   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6308   if (isThumb2) {
6309     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6310     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6311     MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6312   }
6313
6314   unsigned ldrOpc, strOpc;
6315   getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6316
6317   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6318   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6319   MF->insert(It, loopMBB);
6320   MF->insert(It, exitMBB);
6321
6322   // Transfer the remainder of BB and its successor edges to exitMBB.
6323   exitMBB->splice(exitMBB->begin(), BB,
6324                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6325   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6326
6327   const TargetRegisterClass *TRC = isThumb2 ?
6328     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6329     (const TargetRegisterClass*)&ARM::GPRRegClass;
6330   unsigned scratch = MRI.createVirtualRegister(TRC);
6331   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
6332
6333   //  thisMBB:
6334   //   ...
6335   //   fallthrough --> loopMBB
6336   BB->addSuccessor(loopMBB);
6337
6338   //  loopMBB:
6339   //   ldrex dest, ptr
6340   //   <binop> scratch2, dest, incr
6341   //   strex scratch, scratch2, ptr
6342   //   cmp scratch, #0
6343   //   bne- loopMBB
6344   //   fallthrough --> exitMBB
6345   BB = loopMBB;
6346   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6347   if (ldrOpc == ARM::t2LDREX)
6348     MIB.addImm(0);
6349   AddDefaultPred(MIB);
6350   if (BinOpcode) {
6351     // operand order needs to go the other way for NAND
6352     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
6353       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6354                      addReg(incr).addReg(dest)).addReg(0);
6355     else
6356       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6357                      addReg(dest).addReg(incr)).addReg(0);
6358   }
6359
6360   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6361   if (strOpc == ARM::t2STREX)
6362     MIB.addImm(0);
6363   AddDefaultPred(MIB);
6364   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6365                  .addReg(scratch).addImm(0));
6366   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6367     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6368
6369   BB->addSuccessor(loopMBB);
6370   BB->addSuccessor(exitMBB);
6371
6372   //  exitMBB:
6373   //   ...
6374   BB = exitMBB;
6375
6376   MI->eraseFromParent();   // The instruction is gone now.
6377
6378   return BB;
6379 }
6380
6381 MachineBasicBlock *
6382 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
6383                                           MachineBasicBlock *BB,
6384                                           unsigned Size,
6385                                           bool signExtend,
6386                                           ARMCC::CondCodes Cond) const {
6387   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6388
6389   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6390   MachineFunction *MF = BB->getParent();
6391   MachineFunction::iterator It = BB;
6392   ++It;
6393
6394   unsigned dest = MI->getOperand(0).getReg();
6395   unsigned ptr = MI->getOperand(1).getReg();
6396   unsigned incr = MI->getOperand(2).getReg();
6397   unsigned oldval = dest;
6398   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6399   DebugLoc dl = MI->getDebugLoc();
6400   bool isThumb2 = Subtarget->isThumb2();
6401
6402   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6403   if (isThumb2) {
6404     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6405     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6406     MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6407   }
6408
6409   unsigned ldrOpc, strOpc, extendOpc;
6410   getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6411   switch (Size) {
6412   default: llvm_unreachable("unsupported size for AtomicBinaryMinMax!");
6413   case 1:
6414     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
6415     break;
6416   case 2:
6417     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
6418     break;
6419   case 4:
6420     extendOpc = 0;
6421     break;
6422   }
6423
6424   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6425   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6426   MF->insert(It, loopMBB);
6427   MF->insert(It, exitMBB);
6428
6429   // Transfer the remainder of BB and its successor edges to exitMBB.
6430   exitMBB->splice(exitMBB->begin(), BB,
6431                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6432   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6433
6434   const TargetRegisterClass *TRC = isThumb2 ?
6435     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6436     (const TargetRegisterClass*)&ARM::GPRRegClass;
6437   unsigned scratch = MRI.createVirtualRegister(TRC);
6438   unsigned scratch2 = MRI.createVirtualRegister(TRC);
6439
6440   //  thisMBB:
6441   //   ...
6442   //   fallthrough --> loopMBB
6443   BB->addSuccessor(loopMBB);
6444
6445   //  loopMBB:
6446   //   ldrex dest, ptr
6447   //   (sign extend dest, if required)
6448   //   cmp dest, incr
6449   //   cmov.cond scratch2, incr, dest
6450   //   strex scratch, scratch2, ptr
6451   //   cmp scratch, #0
6452   //   bne- loopMBB
6453   //   fallthrough --> exitMBB
6454   BB = loopMBB;
6455   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6456   if (ldrOpc == ARM::t2LDREX)
6457     MIB.addImm(0);
6458   AddDefaultPred(MIB);
6459
6460   // Sign extend the value, if necessary.
6461   if (signExtend && extendOpc) {
6462     oldval = MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass
6463                                                 : &ARM::GPRnopcRegClass);
6464     if (!isThumb2)
6465       MRI.constrainRegClass(dest, &ARM::GPRnopcRegClass);
6466     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
6467                      .addReg(dest)
6468                      .addImm(0));
6469   }
6470
6471   // Build compare and cmov instructions.
6472   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6473                  .addReg(oldval).addReg(incr));
6474   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
6475          .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
6476
6477   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6478   if (strOpc == ARM::t2STREX)
6479     MIB.addImm(0);
6480   AddDefaultPred(MIB);
6481   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6482                  .addReg(scratch).addImm(0));
6483   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6484     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6485
6486   BB->addSuccessor(loopMBB);
6487   BB->addSuccessor(exitMBB);
6488
6489   //  exitMBB:
6490   //   ...
6491   BB = exitMBB;
6492
6493   MI->eraseFromParent();   // The instruction is gone now.
6494
6495   return BB;
6496 }
6497
6498 MachineBasicBlock *
6499 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
6500                                       unsigned Op1, unsigned Op2,
6501                                       bool NeedsCarry, bool IsCmpxchg,
6502                                       bool IsMinMax, ARMCC::CondCodes CC) const {
6503   // This also handles ATOMIC_SWAP and ATOMIC_STORE, indicated by Op1==0.
6504   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6505
6506   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6507   MachineFunction *MF = BB->getParent();
6508   MachineFunction::iterator It = BB;
6509   ++It;
6510
6511   unsigned destlo = MI->getOperand(0).getReg();
6512   unsigned desthi = MI->getOperand(1).getReg();
6513   unsigned ptr = MI->getOperand(2).getReg();
6514   unsigned vallo = MI->getOperand(3).getReg();
6515   unsigned valhi = MI->getOperand(4).getReg();
6516   AtomicOrdering Ord =
6517       static_cast<AtomicOrdering>(MI->getOperand(IsCmpxchg ? 7 : 5).getImm());
6518   DebugLoc dl = MI->getDebugLoc();
6519   bool isThumb2 = Subtarget->isThumb2();
6520
6521   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6522   if (isThumb2) {
6523     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6524     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6525     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6526     MRI.constrainRegClass(vallo, &ARM::rGPRRegClass);
6527     MRI.constrainRegClass(valhi, &ARM::rGPRRegClass);
6528   }
6529
6530   unsigned ldrOpc, strOpc;
6531   getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6532
6533   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6534   MachineBasicBlock *contBB = 0, *cont2BB = 0;
6535   if (IsCmpxchg || IsMinMax)
6536     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
6537   if (IsCmpxchg)
6538     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
6539   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6540
6541   MF->insert(It, loopMBB);
6542   if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6543   if (IsCmpxchg) MF->insert(It, cont2BB);
6544   MF->insert(It, exitMBB);
6545
6546   // Transfer the remainder of BB and its successor edges to exitMBB.
6547   exitMBB->splice(exitMBB->begin(), BB,
6548                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6549   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6550
6551   const TargetRegisterClass *TRC = isThumb2 ?
6552     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6553     (const TargetRegisterClass*)&ARM::GPRRegClass;
6554   unsigned storesuccess = MRI.createVirtualRegister(TRC);
6555
6556   //  thisMBB:
6557   //   ...
6558   //   fallthrough --> loopMBB
6559   BB->addSuccessor(loopMBB);
6560
6561   //  loopMBB:
6562   //   ldrexd r2, r3, ptr
6563   //   <binopa> r0, r2, incr
6564   //   <binopb> r1, r3, incr
6565   //   strexd storesuccess, r0, r1, ptr
6566   //   cmp storesuccess, #0
6567   //   bne- loopMBB
6568   //   fallthrough --> exitMBB
6569   BB = loopMBB;
6570
6571   // Load
6572   if (isThumb2) {
6573     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6574                        .addReg(destlo, RegState::Define)
6575                        .addReg(desthi, RegState::Define)
6576                        .addReg(ptr));
6577   } else {
6578     unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6579     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6580                        .addReg(GPRPair0, RegState::Define)
6581                        .addReg(ptr));
6582     // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
6583     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6584         .addReg(GPRPair0, 0, ARM::gsub_0);
6585     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6586         .addReg(GPRPair0, 0, ARM::gsub_1);
6587   }
6588
6589   unsigned StoreLo, StoreHi;
6590   if (IsCmpxchg) {
6591     // Add early exit
6592     for (unsigned i = 0; i < 2; i++) {
6593       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6594                                                          ARM::CMPrr))
6595                      .addReg(i == 0 ? destlo : desthi)
6596                      .addReg(i == 0 ? vallo : valhi));
6597       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6598         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6599       BB->addSuccessor(exitMBB);
6600       BB->addSuccessor(i == 0 ? contBB : cont2BB);
6601       BB = (i == 0 ? contBB : cont2BB);
6602     }
6603
6604     // Copy to physregs for strexd
6605     StoreLo = MI->getOperand(5).getReg();
6606     StoreHi = MI->getOperand(6).getReg();
6607   } else if (Op1) {
6608     // Perform binary operation
6609     unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6610     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6611                    .addReg(destlo).addReg(vallo))
6612         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6613     unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6614     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6615                    .addReg(desthi).addReg(valhi))
6616         .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6617
6618     StoreLo = tmpRegLo;
6619     StoreHi = tmpRegHi;
6620   } else {
6621     // Copy to physregs for strexd
6622     StoreLo = vallo;
6623     StoreHi = valhi;
6624   }
6625   if (IsMinMax) {
6626     // Compare and branch to exit block.
6627     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6628       .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6629     BB->addSuccessor(exitMBB);
6630     BB->addSuccessor(contBB);
6631     BB = contBB;
6632     StoreLo = vallo;
6633     StoreHi = valhi;
6634   }
6635
6636   // Store
6637   if (isThumb2) {
6638     MRI.constrainRegClass(StoreLo, &ARM::rGPRRegClass);
6639     MRI.constrainRegClass(StoreHi, &ARM::rGPRRegClass);
6640     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6641                    .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6642   } else {
6643     // Marshal a pair...
6644     unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6645     unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6646     unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6647     BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6648     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6649       .addReg(UndefPair)
6650       .addReg(StoreLo)
6651       .addImm(ARM::gsub_0);
6652     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6653       .addReg(r1)
6654       .addReg(StoreHi)
6655       .addImm(ARM::gsub_1);
6656
6657     // ...and store it
6658     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6659                    .addReg(StorePair).addReg(ptr));
6660   }
6661   // Cmp+jump
6662   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6663                  .addReg(storesuccess).addImm(0));
6664   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6665     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6666
6667   BB->addSuccessor(loopMBB);
6668   BB->addSuccessor(exitMBB);
6669
6670   //  exitMBB:
6671   //   ...
6672   BB = exitMBB;
6673
6674   MI->eraseFromParent();   // The instruction is gone now.
6675
6676   return BB;
6677 }
6678
6679 MachineBasicBlock *
6680 ARMTargetLowering::EmitAtomicLoad64(MachineInstr *MI, MachineBasicBlock *BB) const {
6681
6682   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6683
6684   unsigned destlo = MI->getOperand(0).getReg();
6685   unsigned desthi = MI->getOperand(1).getReg();
6686   unsigned ptr = MI->getOperand(2).getReg();
6687   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6688   DebugLoc dl = MI->getDebugLoc();
6689   bool isThumb2 = Subtarget->isThumb2();
6690
6691   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6692   if (isThumb2) {
6693     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6694     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6695     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6696   }
6697   unsigned ldrOpc, strOpc;
6698   getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6699
6700   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(ldrOpc));
6701
6702   if (isThumb2) {
6703     MIB.addReg(destlo, RegState::Define)
6704        .addReg(desthi, RegState::Define)
6705        .addReg(ptr);
6706
6707   } else {
6708     unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6709     MIB.addReg(GPRPair0, RegState::Define).addReg(ptr);
6710
6711     // Copy GPRPair0 into dest.  (This copy will normally be coalesced.)
6712     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), destlo)
6713       .addReg(GPRPair0, 0, ARM::gsub_0);
6714     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), desthi)
6715       .addReg(GPRPair0, 0, ARM::gsub_1);
6716   }
6717   AddDefaultPred(MIB);
6718
6719   MI->eraseFromParent();   // The instruction is gone now.
6720
6721   return BB;
6722 }
6723
6724 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6725 /// registers the function context.
6726 void ARMTargetLowering::
6727 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6728                        MachineBasicBlock *DispatchBB, int FI) const {
6729   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6730   DebugLoc dl = MI->getDebugLoc();
6731   MachineFunction *MF = MBB->getParent();
6732   MachineRegisterInfo *MRI = &MF->getRegInfo();
6733   MachineConstantPool *MCP = MF->getConstantPool();
6734   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6735   const Function *F = MF->getFunction();
6736
6737   bool isThumb = Subtarget->isThumb();
6738   bool isThumb2 = Subtarget->isThumb2();
6739
6740   unsigned PCLabelId = AFI->createPICLabelUId();
6741   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6742   ARMConstantPoolValue *CPV =
6743     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6744   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6745
6746   const TargetRegisterClass *TRC = isThumb ?
6747     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6748     (const TargetRegisterClass*)&ARM::GPRRegClass;
6749
6750   // Grab constant pool and fixed stack memory operands.
6751   MachineMemOperand *CPMMO =
6752     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6753                              MachineMemOperand::MOLoad, 4, 4);
6754
6755   MachineMemOperand *FIMMOSt =
6756     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6757                              MachineMemOperand::MOStore, 4, 4);
6758
6759   // Load the address of the dispatch MBB into the jump buffer.
6760   if (isThumb2) {
6761     // Incoming value: jbuf
6762     //   ldr.n  r5, LCPI1_1
6763     //   orr    r5, r5, #1
6764     //   add    r5, pc
6765     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6766     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6767     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6768                    .addConstantPoolIndex(CPI)
6769                    .addMemOperand(CPMMO));
6770     // Set the low bit because of thumb mode.
6771     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6772     AddDefaultCC(
6773       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6774                      .addReg(NewVReg1, RegState::Kill)
6775                      .addImm(0x01)));
6776     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6777     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6778       .addReg(NewVReg2, RegState::Kill)
6779       .addImm(PCLabelId);
6780     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6781                    .addReg(NewVReg3, RegState::Kill)
6782                    .addFrameIndex(FI)
6783                    .addImm(36)  // &jbuf[1] :: pc
6784                    .addMemOperand(FIMMOSt));
6785   } else if (isThumb) {
6786     // Incoming value: jbuf
6787     //   ldr.n  r1, LCPI1_4
6788     //   add    r1, pc
6789     //   mov    r2, #1
6790     //   orrs   r1, r2
6791     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6792     //   str    r1, [r2]
6793     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6794     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6795                    .addConstantPoolIndex(CPI)
6796                    .addMemOperand(CPMMO));
6797     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6798     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6799       .addReg(NewVReg1, RegState::Kill)
6800       .addImm(PCLabelId);
6801     // Set the low bit because of thumb mode.
6802     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6803     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6804                    .addReg(ARM::CPSR, RegState::Define)
6805                    .addImm(1));
6806     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6807     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6808                    .addReg(ARM::CPSR, RegState::Define)
6809                    .addReg(NewVReg2, RegState::Kill)
6810                    .addReg(NewVReg3, RegState::Kill));
6811     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6812     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6813                    .addFrameIndex(FI)
6814                    .addImm(36)); // &jbuf[1] :: pc
6815     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6816                    .addReg(NewVReg4, RegState::Kill)
6817                    .addReg(NewVReg5, RegState::Kill)
6818                    .addImm(0)
6819                    .addMemOperand(FIMMOSt));
6820   } else {
6821     // Incoming value: jbuf
6822     //   ldr  r1, LCPI1_1
6823     //   add  r1, pc, r1
6824     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6825     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6826     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6827                    .addConstantPoolIndex(CPI)
6828                    .addImm(0)
6829                    .addMemOperand(CPMMO));
6830     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6831     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6832                    .addReg(NewVReg1, RegState::Kill)
6833                    .addImm(PCLabelId));
6834     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6835                    .addReg(NewVReg2, RegState::Kill)
6836                    .addFrameIndex(FI)
6837                    .addImm(36)  // &jbuf[1] :: pc
6838                    .addMemOperand(FIMMOSt));
6839   }
6840 }
6841
6842 MachineBasicBlock *ARMTargetLowering::
6843 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6844   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6845   DebugLoc dl = MI->getDebugLoc();
6846   MachineFunction *MF = MBB->getParent();
6847   MachineRegisterInfo *MRI = &MF->getRegInfo();
6848   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6849   MachineFrameInfo *MFI = MF->getFrameInfo();
6850   int FI = MFI->getFunctionContextIndex();
6851
6852   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6853     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6854     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6855
6856   // Get a mapping of the call site numbers to all of the landing pads they're
6857   // associated with.
6858   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6859   unsigned MaxCSNum = 0;
6860   MachineModuleInfo &MMI = MF->getMMI();
6861   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6862        ++BB) {
6863     if (!BB->isLandingPad()) continue;
6864
6865     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6866     // pad.
6867     for (MachineBasicBlock::iterator
6868            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6869       if (!II->isEHLabel()) continue;
6870
6871       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6872       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6873
6874       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6875       for (SmallVectorImpl<unsigned>::iterator
6876              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6877            CSI != CSE; ++CSI) {
6878         CallSiteNumToLPad[*CSI].push_back(BB);
6879         MaxCSNum = std::max(MaxCSNum, *CSI);
6880       }
6881       break;
6882     }
6883   }
6884
6885   // Get an ordered list of the machine basic blocks for the jump table.
6886   std::vector<MachineBasicBlock*> LPadList;
6887   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6888   LPadList.reserve(CallSiteNumToLPad.size());
6889   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6890     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6891     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6892            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6893       LPadList.push_back(*II);
6894       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6895     }
6896   }
6897
6898   assert(!LPadList.empty() &&
6899          "No landing pad destinations for the dispatch jump table!");
6900
6901   // Create the jump table and associated information.
6902   MachineJumpTableInfo *JTI =
6903     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6904   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6905   unsigned UId = AFI->createJumpTableUId();
6906   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6907
6908   // Create the MBBs for the dispatch code.
6909
6910   // Shove the dispatch's address into the return slot in the function context.
6911   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6912   DispatchBB->setIsLandingPad();
6913
6914   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6915   unsigned trap_opcode;
6916   if (Subtarget->isThumb())
6917     trap_opcode = ARM::tTRAP;
6918   else
6919     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6920
6921   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6922   DispatchBB->addSuccessor(TrapBB);
6923
6924   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6925   DispatchBB->addSuccessor(DispContBB);
6926
6927   // Insert and MBBs.
6928   MF->insert(MF->end(), DispatchBB);
6929   MF->insert(MF->end(), DispContBB);
6930   MF->insert(MF->end(), TrapBB);
6931
6932   // Insert code into the entry block that creates and registers the function
6933   // context.
6934   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6935
6936   MachineMemOperand *FIMMOLd =
6937     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6938                              MachineMemOperand::MOLoad |
6939                              MachineMemOperand::MOVolatile, 4, 4);
6940
6941   MachineInstrBuilder MIB;
6942   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6943
6944   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6945   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6946
6947   // Add a register mask with no preserved registers.  This results in all
6948   // registers being marked as clobbered.
6949   MIB.addRegMask(RI.getNoPreservedMask());
6950
6951   unsigned NumLPads = LPadList.size();
6952   if (Subtarget->isThumb2()) {
6953     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6954     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6955                    .addFrameIndex(FI)
6956                    .addImm(4)
6957                    .addMemOperand(FIMMOLd));
6958
6959     if (NumLPads < 256) {
6960       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6961                      .addReg(NewVReg1)
6962                      .addImm(LPadList.size()));
6963     } else {
6964       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6965       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6966                      .addImm(NumLPads & 0xFFFF));
6967
6968       unsigned VReg2 = VReg1;
6969       if ((NumLPads & 0xFFFF0000) != 0) {
6970         VReg2 = MRI->createVirtualRegister(TRC);
6971         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6972                        .addReg(VReg1)
6973                        .addImm(NumLPads >> 16));
6974       }
6975
6976       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6977                      .addReg(NewVReg1)
6978                      .addReg(VReg2));
6979     }
6980
6981     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6982       .addMBB(TrapBB)
6983       .addImm(ARMCC::HI)
6984       .addReg(ARM::CPSR);
6985
6986     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6987     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6988                    .addJumpTableIndex(MJTI)
6989                    .addImm(UId));
6990
6991     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6992     AddDefaultCC(
6993       AddDefaultPred(
6994         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6995         .addReg(NewVReg3, RegState::Kill)
6996         .addReg(NewVReg1)
6997         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6998
6999     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7000       .addReg(NewVReg4, RegState::Kill)
7001       .addReg(NewVReg1)
7002       .addJumpTableIndex(MJTI)
7003       .addImm(UId);
7004   } else if (Subtarget->isThumb()) {
7005     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7006     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7007                    .addFrameIndex(FI)
7008                    .addImm(1)
7009                    .addMemOperand(FIMMOLd));
7010
7011     if (NumLPads < 256) {
7012       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7013                      .addReg(NewVReg1)
7014                      .addImm(NumLPads));
7015     } else {
7016       MachineConstantPool *ConstantPool = MF->getConstantPool();
7017       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7018       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7019
7020       // MachineConstantPool wants an explicit alignment.
7021       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7022       if (Align == 0)
7023         Align = getDataLayout()->getTypeAllocSize(C->getType());
7024       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7025
7026       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7027       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7028                      .addReg(VReg1, RegState::Define)
7029                      .addConstantPoolIndex(Idx));
7030       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7031                      .addReg(NewVReg1)
7032                      .addReg(VReg1));
7033     }
7034
7035     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7036       .addMBB(TrapBB)
7037       .addImm(ARMCC::HI)
7038       .addReg(ARM::CPSR);
7039
7040     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7041     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7042                    .addReg(ARM::CPSR, RegState::Define)
7043                    .addReg(NewVReg1)
7044                    .addImm(2));
7045
7046     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7047     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7048                    .addJumpTableIndex(MJTI)
7049                    .addImm(UId));
7050
7051     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7052     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7053                    .addReg(ARM::CPSR, RegState::Define)
7054                    .addReg(NewVReg2, RegState::Kill)
7055                    .addReg(NewVReg3));
7056
7057     MachineMemOperand *JTMMOLd =
7058       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7059                                MachineMemOperand::MOLoad, 4, 4);
7060
7061     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7062     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7063                    .addReg(NewVReg4, RegState::Kill)
7064                    .addImm(0)
7065                    .addMemOperand(JTMMOLd));
7066
7067     unsigned NewVReg6 = NewVReg5;
7068     if (RelocM == Reloc::PIC_) {
7069       NewVReg6 = MRI->createVirtualRegister(TRC);
7070       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7071                      .addReg(ARM::CPSR, RegState::Define)
7072                      .addReg(NewVReg5, RegState::Kill)
7073                      .addReg(NewVReg3));
7074     }
7075
7076     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7077       .addReg(NewVReg6, RegState::Kill)
7078       .addJumpTableIndex(MJTI)
7079       .addImm(UId);
7080   } else {
7081     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7082     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7083                    .addFrameIndex(FI)
7084                    .addImm(4)
7085                    .addMemOperand(FIMMOLd));
7086
7087     if (NumLPads < 256) {
7088       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7089                      .addReg(NewVReg1)
7090                      .addImm(NumLPads));
7091     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7092       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7093       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7094                      .addImm(NumLPads & 0xFFFF));
7095
7096       unsigned VReg2 = VReg1;
7097       if ((NumLPads & 0xFFFF0000) != 0) {
7098         VReg2 = MRI->createVirtualRegister(TRC);
7099         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7100                        .addReg(VReg1)
7101                        .addImm(NumLPads >> 16));
7102       }
7103
7104       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7105                      .addReg(NewVReg1)
7106                      .addReg(VReg2));
7107     } else {
7108       MachineConstantPool *ConstantPool = MF->getConstantPool();
7109       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7110       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7111
7112       // MachineConstantPool wants an explicit alignment.
7113       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7114       if (Align == 0)
7115         Align = getDataLayout()->getTypeAllocSize(C->getType());
7116       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7117
7118       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7119       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7120                      .addReg(VReg1, RegState::Define)
7121                      .addConstantPoolIndex(Idx)
7122                      .addImm(0));
7123       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7124                      .addReg(NewVReg1)
7125                      .addReg(VReg1, RegState::Kill));
7126     }
7127
7128     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7129       .addMBB(TrapBB)
7130       .addImm(ARMCC::HI)
7131       .addReg(ARM::CPSR);
7132
7133     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7134     AddDefaultCC(
7135       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7136                      .addReg(NewVReg1)
7137                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7138     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7139     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7140                    .addJumpTableIndex(MJTI)
7141                    .addImm(UId));
7142
7143     MachineMemOperand *JTMMOLd =
7144       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7145                                MachineMemOperand::MOLoad, 4, 4);
7146     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7147     AddDefaultPred(
7148       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7149       .addReg(NewVReg3, RegState::Kill)
7150       .addReg(NewVReg4)
7151       .addImm(0)
7152       .addMemOperand(JTMMOLd));
7153
7154     if (RelocM == Reloc::PIC_) {
7155       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7156         .addReg(NewVReg5, RegState::Kill)
7157         .addReg(NewVReg4)
7158         .addJumpTableIndex(MJTI)
7159         .addImm(UId);
7160     } else {
7161       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7162         .addReg(NewVReg5, RegState::Kill)
7163         .addJumpTableIndex(MJTI)
7164         .addImm(UId);
7165     }
7166   }
7167
7168   // Add the jump table entries as successors to the MBB.
7169   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7170   for (std::vector<MachineBasicBlock*>::iterator
7171          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7172     MachineBasicBlock *CurMBB = *I;
7173     if (SeenMBBs.insert(CurMBB))
7174       DispContBB->addSuccessor(CurMBB);
7175   }
7176
7177   // N.B. the order the invoke BBs are processed in doesn't matter here.
7178   const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
7179   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7180   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
7181          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
7182     MachineBasicBlock *BB = *I;
7183
7184     // Remove the landing pad successor from the invoke block and replace it
7185     // with the new dispatch block.
7186     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7187                                                   BB->succ_end());
7188     while (!Successors.empty()) {
7189       MachineBasicBlock *SMBB = Successors.pop_back_val();
7190       if (SMBB->isLandingPad()) {
7191         BB->removeSuccessor(SMBB);
7192         MBBLPads.push_back(SMBB);
7193       }
7194     }
7195
7196     BB->addSuccessor(DispatchBB);
7197
7198     // Find the invoke call and mark all of the callee-saved registers as
7199     // 'implicit defined' so that they're spilled. This prevents code from
7200     // moving instructions to before the EH block, where they will never be
7201     // executed.
7202     for (MachineBasicBlock::reverse_iterator
7203            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7204       if (!II->isCall()) continue;
7205
7206       DenseMap<unsigned, bool> DefRegs;
7207       for (MachineInstr::mop_iterator
7208              OI = II->operands_begin(), OE = II->operands_end();
7209            OI != OE; ++OI) {
7210         if (!OI->isReg()) continue;
7211         DefRegs[OI->getReg()] = true;
7212       }
7213
7214       MachineInstrBuilder MIB(*MF, &*II);
7215
7216       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7217         unsigned Reg = SavedRegs[i];
7218         if (Subtarget->isThumb2() &&
7219             !ARM::tGPRRegClass.contains(Reg) &&
7220             !ARM::hGPRRegClass.contains(Reg))
7221           continue;
7222         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7223           continue;
7224         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7225           continue;
7226         if (!DefRegs[Reg])
7227           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7228       }
7229
7230       break;
7231     }
7232   }
7233
7234   // Mark all former landing pads as non-landing pads. The dispatch is the only
7235   // landing pad now.
7236   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7237          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7238     (*I)->setIsLandingPad(false);
7239
7240   // The instruction is gone now.
7241   MI->eraseFromParent();
7242
7243   return MBB;
7244 }
7245
7246 static
7247 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7248   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7249        E = MBB->succ_end(); I != E; ++I)
7250     if (*I != Succ)
7251       return *I;
7252   llvm_unreachable("Expecting a BB with two successors!");
7253 }
7254
7255 /// Return the load opcode for a given load size. If load size >= 8,
7256 /// neon opcode will be returned.
7257 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7258   if (LdSize >= 8)
7259     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7260                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7261   if (IsThumb1)
7262     return LdSize == 4 ? ARM::tLDRi
7263                        : LdSize == 2 ? ARM::tLDRHi
7264                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7265   if (IsThumb2)
7266     return LdSize == 4 ? ARM::t2LDR_POST
7267                        : LdSize == 2 ? ARM::t2LDRH_POST
7268                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7269   return LdSize == 4 ? ARM::LDR_POST_IMM
7270                      : LdSize == 2 ? ARM::LDRH_POST
7271                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7272 }
7273
7274 /// Return the store opcode for a given store size. If store size >= 8,
7275 /// neon opcode will be returned.
7276 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7277   if (StSize >= 8)
7278     return StSize == 16 ? ARM::VST1q32wb_fixed
7279                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7280   if (IsThumb1)
7281     return StSize == 4 ? ARM::tSTRi
7282                        : StSize == 2 ? ARM::tSTRHi
7283                                      : StSize == 1 ? ARM::tSTRBi : 0;
7284   if (IsThumb2)
7285     return StSize == 4 ? ARM::t2STR_POST
7286                        : StSize == 2 ? ARM::t2STRH_POST
7287                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7288   return StSize == 4 ? ARM::STR_POST_IMM
7289                      : StSize == 2 ? ARM::STRH_POST
7290                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7291 }
7292
7293 /// Emit a post-increment load operation with given size. The instructions
7294 /// will be added to BB at Pos.
7295 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7296                        const TargetInstrInfo *TII, DebugLoc dl,
7297                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7298                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7299   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7300   assert(LdOpc != 0 && "Should have a load opcode");
7301   if (LdSize >= 8) {
7302     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7303                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7304                        .addImm(0));
7305   } else if (IsThumb1) {
7306     // load + update AddrIn
7307     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7308                        .addReg(AddrIn).addImm(0));
7309     MachineInstrBuilder MIB =
7310         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7311     MIB = AddDefaultT1CC(MIB);
7312     MIB.addReg(AddrIn).addImm(LdSize);
7313     AddDefaultPred(MIB);
7314   } else if (IsThumb2) {
7315     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7316                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7317                        .addImm(LdSize));
7318   } else { // arm
7319     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7320                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7321                        .addReg(0).addImm(LdSize));
7322   }
7323 }
7324
7325 /// Emit a post-increment store operation with given size. The instructions
7326 /// will be added to BB at Pos.
7327 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7328                        const TargetInstrInfo *TII, DebugLoc dl,
7329                        unsigned StSize, unsigned Data, unsigned AddrIn,
7330                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7331   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7332   assert(StOpc != 0 && "Should have a store opcode");
7333   if (StSize >= 8) {
7334     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7335                        .addReg(AddrIn).addImm(0).addReg(Data));
7336   } else if (IsThumb1) {
7337     // store + update AddrIn
7338     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7339                        .addReg(AddrIn).addImm(0));
7340     MachineInstrBuilder MIB =
7341         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7342     MIB = AddDefaultT1CC(MIB);
7343     MIB.addReg(AddrIn).addImm(StSize);
7344     AddDefaultPred(MIB);
7345   } else if (IsThumb2) {
7346     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7347                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7348   } else { // arm
7349     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7350                        .addReg(Data).addReg(AddrIn).addReg(0)
7351                        .addImm(StSize));
7352   }
7353 }
7354
7355 MachineBasicBlock *
7356 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7357                                    MachineBasicBlock *BB) const {
7358   // This pseudo instruction has 3 operands: dst, src, size
7359   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7360   // Otherwise, we will generate unrolled scalar copies.
7361   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7362   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7363   MachineFunction::iterator It = BB;
7364   ++It;
7365
7366   unsigned dest = MI->getOperand(0).getReg();
7367   unsigned src = MI->getOperand(1).getReg();
7368   unsigned SizeVal = MI->getOperand(2).getImm();
7369   unsigned Align = MI->getOperand(3).getImm();
7370   DebugLoc dl = MI->getDebugLoc();
7371
7372   MachineFunction *MF = BB->getParent();
7373   MachineRegisterInfo &MRI = MF->getRegInfo();
7374   unsigned UnitSize = 0;
7375   const TargetRegisterClass *TRC = 0;
7376   const TargetRegisterClass *VecTRC = 0;
7377
7378   bool IsThumb1 = Subtarget->isThumb1Only();
7379   bool IsThumb2 = Subtarget->isThumb2();
7380
7381   if (Align & 1) {
7382     UnitSize = 1;
7383   } else if (Align & 2) {
7384     UnitSize = 2;
7385   } else {
7386     // Check whether we can use NEON instructions.
7387     if (!MF->getFunction()->getAttributes().
7388           hasAttribute(AttributeSet::FunctionIndex,
7389                        Attribute::NoImplicitFloat) &&
7390         Subtarget->hasNEON()) {
7391       if ((Align % 16 == 0) && SizeVal >= 16)
7392         UnitSize = 16;
7393       else if ((Align % 8 == 0) && SizeVal >= 8)
7394         UnitSize = 8;
7395     }
7396     // Can't use NEON instructions.
7397     if (UnitSize == 0)
7398       UnitSize = 4;
7399   }
7400
7401   // Select the correct opcode and register class for unit size load/store
7402   bool IsNeon = UnitSize >= 8;
7403   TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
7404                                : (const TargetRegisterClass *)&ARM::GPRRegClass;
7405   if (IsNeon)
7406     VecTRC = UnitSize == 16
7407                  ? (const TargetRegisterClass *)&ARM::DPairRegClass
7408                  : UnitSize == 8
7409                        ? (const TargetRegisterClass *)&ARM::DPRRegClass
7410                        : 0;
7411
7412   unsigned BytesLeft = SizeVal % UnitSize;
7413   unsigned LoopSize = SizeVal - BytesLeft;
7414
7415   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7416     // Use LDR and STR to copy.
7417     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7418     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7419     unsigned srcIn = src;
7420     unsigned destIn = dest;
7421     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7422       unsigned srcOut = MRI.createVirtualRegister(TRC);
7423       unsigned destOut = MRI.createVirtualRegister(TRC);
7424       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7425       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7426                  IsThumb1, IsThumb2);
7427       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7428                  IsThumb1, IsThumb2);
7429       srcIn = srcOut;
7430       destIn = destOut;
7431     }
7432
7433     // Handle the leftover bytes with LDRB and STRB.
7434     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7435     // [destOut] = STRB_POST(scratch, destIn, 1)
7436     for (unsigned i = 0; i < BytesLeft; i++) {
7437       unsigned srcOut = MRI.createVirtualRegister(TRC);
7438       unsigned destOut = MRI.createVirtualRegister(TRC);
7439       unsigned scratch = MRI.createVirtualRegister(TRC);
7440       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7441                  IsThumb1, IsThumb2);
7442       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7443                  IsThumb1, IsThumb2);
7444       srcIn = srcOut;
7445       destIn = destOut;
7446     }
7447     MI->eraseFromParent();   // The instruction is gone now.
7448     return BB;
7449   }
7450
7451   // Expand the pseudo op to a loop.
7452   // thisMBB:
7453   //   ...
7454   //   movw varEnd, # --> with thumb2
7455   //   movt varEnd, #
7456   //   ldrcp varEnd, idx --> without thumb2
7457   //   fallthrough --> loopMBB
7458   // loopMBB:
7459   //   PHI varPhi, varEnd, varLoop
7460   //   PHI srcPhi, src, srcLoop
7461   //   PHI destPhi, dst, destLoop
7462   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7463   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7464   //   subs varLoop, varPhi, #UnitSize
7465   //   bne loopMBB
7466   //   fallthrough --> exitMBB
7467   // exitMBB:
7468   //   epilogue to handle left-over bytes
7469   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7470   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7471   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7472   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7473   MF->insert(It, loopMBB);
7474   MF->insert(It, exitMBB);
7475
7476   // Transfer the remainder of BB and its successor edges to exitMBB.
7477   exitMBB->splice(exitMBB->begin(), BB,
7478                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7479   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7480
7481   // Load an immediate to varEnd.
7482   unsigned varEnd = MRI.createVirtualRegister(TRC);
7483   if (IsThumb2) {
7484     unsigned Vtmp = varEnd;
7485     if ((LoopSize & 0xFFFF0000) != 0)
7486       Vtmp = MRI.createVirtualRegister(TRC);
7487     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7488                        .addImm(LoopSize & 0xFFFF));
7489
7490     if ((LoopSize & 0xFFFF0000) != 0)
7491       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7492                          .addReg(Vtmp).addImm(LoopSize >> 16));
7493   } else {
7494     MachineConstantPool *ConstantPool = MF->getConstantPool();
7495     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7496     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7497
7498     // MachineConstantPool wants an explicit alignment.
7499     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7500     if (Align == 0)
7501       Align = getDataLayout()->getTypeAllocSize(C->getType());
7502     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7503
7504     if (IsThumb1)
7505       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7506           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7507     else
7508       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7509           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7510   }
7511   BB->addSuccessor(loopMBB);
7512
7513   // Generate the loop body:
7514   //   varPhi = PHI(varLoop, varEnd)
7515   //   srcPhi = PHI(srcLoop, src)
7516   //   destPhi = PHI(destLoop, dst)
7517   MachineBasicBlock *entryBB = BB;
7518   BB = loopMBB;
7519   unsigned varLoop = MRI.createVirtualRegister(TRC);
7520   unsigned varPhi = MRI.createVirtualRegister(TRC);
7521   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7522   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7523   unsigned destLoop = MRI.createVirtualRegister(TRC);
7524   unsigned destPhi = MRI.createVirtualRegister(TRC);
7525
7526   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7527     .addReg(varLoop).addMBB(loopMBB)
7528     .addReg(varEnd).addMBB(entryBB);
7529   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7530     .addReg(srcLoop).addMBB(loopMBB)
7531     .addReg(src).addMBB(entryBB);
7532   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7533     .addReg(destLoop).addMBB(loopMBB)
7534     .addReg(dest).addMBB(entryBB);
7535
7536   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7537   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7538   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7539   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7540              IsThumb1, IsThumb2);
7541   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7542              IsThumb1, IsThumb2);
7543
7544   // Decrement loop variable by UnitSize.
7545   if (IsThumb1) {
7546     MachineInstrBuilder MIB =
7547         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7548     MIB = AddDefaultT1CC(MIB);
7549     MIB.addReg(varPhi).addImm(UnitSize);
7550     AddDefaultPred(MIB);
7551   } else {
7552     MachineInstrBuilder MIB =
7553         BuildMI(*BB, BB->end(), dl,
7554                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7555     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7556     MIB->getOperand(5).setReg(ARM::CPSR);
7557     MIB->getOperand(5).setIsDef(true);
7558   }
7559   BuildMI(*BB, BB->end(), dl,
7560           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7561       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7562
7563   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7564   BB->addSuccessor(loopMBB);
7565   BB->addSuccessor(exitMBB);
7566
7567   // Add epilogue to handle BytesLeft.
7568   BB = exitMBB;
7569   MachineInstr *StartOfExit = exitMBB->begin();
7570
7571   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7572   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7573   unsigned srcIn = srcLoop;
7574   unsigned destIn = destLoop;
7575   for (unsigned i = 0; i < BytesLeft; i++) {
7576     unsigned srcOut = MRI.createVirtualRegister(TRC);
7577     unsigned destOut = MRI.createVirtualRegister(TRC);
7578     unsigned scratch = MRI.createVirtualRegister(TRC);
7579     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7580                IsThumb1, IsThumb2);
7581     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7582                IsThumb1, IsThumb2);
7583     srcIn = srcOut;
7584     destIn = destOut;
7585   }
7586
7587   MI->eraseFromParent();   // The instruction is gone now.
7588   return BB;
7589 }
7590
7591 MachineBasicBlock *
7592 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7593                                                MachineBasicBlock *BB) const {
7594   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7595   DebugLoc dl = MI->getDebugLoc();
7596   bool isThumb2 = Subtarget->isThumb2();
7597   switch (MI->getOpcode()) {
7598   default: {
7599     MI->dump();
7600     llvm_unreachable("Unexpected instr type to insert");
7601   }
7602   // The Thumb2 pre-indexed stores have the same MI operands, they just
7603   // define them differently in the .td files from the isel patterns, so
7604   // they need pseudos.
7605   case ARM::t2STR_preidx:
7606     MI->setDesc(TII->get(ARM::t2STR_PRE));
7607     return BB;
7608   case ARM::t2STRB_preidx:
7609     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7610     return BB;
7611   case ARM::t2STRH_preidx:
7612     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7613     return BB;
7614
7615   case ARM::STRi_preidx:
7616   case ARM::STRBi_preidx: {
7617     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7618       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7619     // Decode the offset.
7620     unsigned Offset = MI->getOperand(4).getImm();
7621     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7622     Offset = ARM_AM::getAM2Offset(Offset);
7623     if (isSub)
7624       Offset = -Offset;
7625
7626     MachineMemOperand *MMO = *MI->memoperands_begin();
7627     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7628       .addOperand(MI->getOperand(0))  // Rn_wb
7629       .addOperand(MI->getOperand(1))  // Rt
7630       .addOperand(MI->getOperand(2))  // Rn
7631       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7632       .addOperand(MI->getOperand(5))  // pred
7633       .addOperand(MI->getOperand(6))
7634       .addMemOperand(MMO);
7635     MI->eraseFromParent();
7636     return BB;
7637   }
7638   case ARM::STRr_preidx:
7639   case ARM::STRBr_preidx:
7640   case ARM::STRH_preidx: {
7641     unsigned NewOpc;
7642     switch (MI->getOpcode()) {
7643     default: llvm_unreachable("unexpected opcode!");
7644     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7645     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7646     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7647     }
7648     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7649     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7650       MIB.addOperand(MI->getOperand(i));
7651     MI->eraseFromParent();
7652     return BB;
7653   }
7654   case ARM::ATOMIC_LOAD_ADD_I8:
7655      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7656   case ARM::ATOMIC_LOAD_ADD_I16:
7657      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7658   case ARM::ATOMIC_LOAD_ADD_I32:
7659      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7660
7661   case ARM::ATOMIC_LOAD_AND_I8:
7662      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7663   case ARM::ATOMIC_LOAD_AND_I16:
7664      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7665   case ARM::ATOMIC_LOAD_AND_I32:
7666      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7667
7668   case ARM::ATOMIC_LOAD_OR_I8:
7669      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7670   case ARM::ATOMIC_LOAD_OR_I16:
7671      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7672   case ARM::ATOMIC_LOAD_OR_I32:
7673      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7674
7675   case ARM::ATOMIC_LOAD_XOR_I8:
7676      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7677   case ARM::ATOMIC_LOAD_XOR_I16:
7678      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7679   case ARM::ATOMIC_LOAD_XOR_I32:
7680      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7681
7682   case ARM::ATOMIC_LOAD_NAND_I8:
7683      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7684   case ARM::ATOMIC_LOAD_NAND_I16:
7685      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7686   case ARM::ATOMIC_LOAD_NAND_I32:
7687      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7688
7689   case ARM::ATOMIC_LOAD_SUB_I8:
7690      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7691   case ARM::ATOMIC_LOAD_SUB_I16:
7692      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7693   case ARM::ATOMIC_LOAD_SUB_I32:
7694      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7695
7696   case ARM::ATOMIC_LOAD_MIN_I8:
7697      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7698   case ARM::ATOMIC_LOAD_MIN_I16:
7699      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7700   case ARM::ATOMIC_LOAD_MIN_I32:
7701      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7702
7703   case ARM::ATOMIC_LOAD_MAX_I8:
7704      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7705   case ARM::ATOMIC_LOAD_MAX_I16:
7706      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7707   case ARM::ATOMIC_LOAD_MAX_I32:
7708      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7709
7710   case ARM::ATOMIC_LOAD_UMIN_I8:
7711      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7712   case ARM::ATOMIC_LOAD_UMIN_I16:
7713      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7714   case ARM::ATOMIC_LOAD_UMIN_I32:
7715      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7716
7717   case ARM::ATOMIC_LOAD_UMAX_I8:
7718      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7719   case ARM::ATOMIC_LOAD_UMAX_I16:
7720      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7721   case ARM::ATOMIC_LOAD_UMAX_I32:
7722      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7723
7724   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
7725   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7726   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7727
7728   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
7729   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7730   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7731
7732   case ARM::ATOMIC_LOAD_I64:
7733     return EmitAtomicLoad64(MI, BB);
7734
7735   case ARM::ATOMIC_LOAD_ADD_I64:
7736     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7737                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7738                               /*NeedsCarry*/ true);
7739   case ARM::ATOMIC_LOAD_SUB_I64:
7740     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7741                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7742                               /*NeedsCarry*/ true);
7743   case ARM::ATOMIC_LOAD_OR_I64:
7744     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7745                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7746   case ARM::ATOMIC_LOAD_XOR_I64:
7747     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7748                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7749   case ARM::ATOMIC_LOAD_AND_I64:
7750     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7751                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7752   case ARM::ATOMIC_SWAP_I64:
7753     return EmitAtomicBinary64(MI, BB, 0, 0, false);
7754   case ARM::ATOMIC_CMP_SWAP_I64:
7755     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7756                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7757                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7758   case ARM::ATOMIC_LOAD_MIN_I64:
7759     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7760                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7761                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7762                               /*IsMinMax*/ true, ARMCC::LT);
7763   case ARM::ATOMIC_LOAD_MAX_I64:
7764     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7765                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7766                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7767                               /*IsMinMax*/ true, ARMCC::GE);
7768   case ARM::ATOMIC_LOAD_UMIN_I64:
7769     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7770                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7771                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7772                               /*IsMinMax*/ true, ARMCC::LO);
7773   case ARM::ATOMIC_LOAD_UMAX_I64:
7774     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7775                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7776                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7777                               /*IsMinMax*/ true, ARMCC::HS);
7778
7779   case ARM::tMOVCCr_pseudo: {
7780     // To "insert" a SELECT_CC instruction, we actually have to insert the
7781     // diamond control-flow pattern.  The incoming instruction knows the
7782     // destination vreg to set, the condition code register to branch on, the
7783     // true/false values to select between, and a branch opcode to use.
7784     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7785     MachineFunction::iterator It = BB;
7786     ++It;
7787
7788     //  thisMBB:
7789     //  ...
7790     //   TrueVal = ...
7791     //   cmpTY ccX, r1, r2
7792     //   bCC copy1MBB
7793     //   fallthrough --> copy0MBB
7794     MachineBasicBlock *thisMBB  = BB;
7795     MachineFunction *F = BB->getParent();
7796     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7797     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7798     F->insert(It, copy0MBB);
7799     F->insert(It, sinkMBB);
7800
7801     // Transfer the remainder of BB and its successor edges to sinkMBB.
7802     sinkMBB->splice(sinkMBB->begin(), BB,
7803                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7804     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7805
7806     BB->addSuccessor(copy0MBB);
7807     BB->addSuccessor(sinkMBB);
7808
7809     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7810       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7811
7812     //  copy0MBB:
7813     //   %FalseValue = ...
7814     //   # fallthrough to sinkMBB
7815     BB = copy0MBB;
7816
7817     // Update machine-CFG edges
7818     BB->addSuccessor(sinkMBB);
7819
7820     //  sinkMBB:
7821     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7822     //  ...
7823     BB = sinkMBB;
7824     BuildMI(*BB, BB->begin(), dl,
7825             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7826       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7827       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7828
7829     MI->eraseFromParent();   // The pseudo instruction is gone now.
7830     return BB;
7831   }
7832
7833   case ARM::BCCi64:
7834   case ARM::BCCZi64: {
7835     // If there is an unconditional branch to the other successor, remove it.
7836     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7837
7838     // Compare both parts that make up the double comparison separately for
7839     // equality.
7840     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7841
7842     unsigned LHS1 = MI->getOperand(1).getReg();
7843     unsigned LHS2 = MI->getOperand(2).getReg();
7844     if (RHSisZero) {
7845       AddDefaultPred(BuildMI(BB, dl,
7846                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7847                      .addReg(LHS1).addImm(0));
7848       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7849         .addReg(LHS2).addImm(0)
7850         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7851     } else {
7852       unsigned RHS1 = MI->getOperand(3).getReg();
7853       unsigned RHS2 = MI->getOperand(4).getReg();
7854       AddDefaultPred(BuildMI(BB, dl,
7855                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7856                      .addReg(LHS1).addReg(RHS1));
7857       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7858         .addReg(LHS2).addReg(RHS2)
7859         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7860     }
7861
7862     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7863     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7864     if (MI->getOperand(0).getImm() == ARMCC::NE)
7865       std::swap(destMBB, exitMBB);
7866
7867     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7868       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7869     if (isThumb2)
7870       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7871     else
7872       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7873
7874     MI->eraseFromParent();   // The pseudo instruction is gone now.
7875     return BB;
7876   }
7877
7878   case ARM::Int_eh_sjlj_setjmp:
7879   case ARM::Int_eh_sjlj_setjmp_nofp:
7880   case ARM::tInt_eh_sjlj_setjmp:
7881   case ARM::t2Int_eh_sjlj_setjmp:
7882   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7883     EmitSjLjDispatchBlock(MI, BB);
7884     return BB;
7885
7886   case ARM::ABS:
7887   case ARM::t2ABS: {
7888     // To insert an ABS instruction, we have to insert the
7889     // diamond control-flow pattern.  The incoming instruction knows the
7890     // source vreg to test against 0, the destination vreg to set,
7891     // the condition code register to branch on, the
7892     // true/false values to select between, and a branch opcode to use.
7893     // It transforms
7894     //     V1 = ABS V0
7895     // into
7896     //     V2 = MOVS V0
7897     //     BCC                      (branch to SinkBB if V0 >= 0)
7898     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7899     //     SinkBB: V1 = PHI(V2, V3)
7900     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7901     MachineFunction::iterator BBI = BB;
7902     ++BBI;
7903     MachineFunction *Fn = BB->getParent();
7904     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7905     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7906     Fn->insert(BBI, RSBBB);
7907     Fn->insert(BBI, SinkBB);
7908
7909     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7910     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7911     bool isThumb2 = Subtarget->isThumb2();
7912     MachineRegisterInfo &MRI = Fn->getRegInfo();
7913     // In Thumb mode S must not be specified if source register is the SP or
7914     // PC and if destination register is the SP, so restrict register class
7915     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7916       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7917       (const TargetRegisterClass*)&ARM::GPRRegClass);
7918
7919     // Transfer the remainder of BB and its successor edges to sinkMBB.
7920     SinkBB->splice(SinkBB->begin(), BB,
7921                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7922     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7923
7924     BB->addSuccessor(RSBBB);
7925     BB->addSuccessor(SinkBB);
7926
7927     // fall through to SinkMBB
7928     RSBBB->addSuccessor(SinkBB);
7929
7930     // insert a cmp at the end of BB
7931     AddDefaultPred(BuildMI(BB, dl,
7932                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7933                    .addReg(ABSSrcReg).addImm(0));
7934
7935     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7936     BuildMI(BB, dl,
7937       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7938       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7939
7940     // insert rsbri in RSBBB
7941     // Note: BCC and rsbri will be converted into predicated rsbmi
7942     // by if-conversion pass
7943     BuildMI(*RSBBB, RSBBB->begin(), dl,
7944       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7945       .addReg(ABSSrcReg, RegState::Kill)
7946       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7947
7948     // insert PHI in SinkBB,
7949     // reuse ABSDstReg to not change uses of ABS instruction
7950     BuildMI(*SinkBB, SinkBB->begin(), dl,
7951       TII->get(ARM::PHI), ABSDstReg)
7952       .addReg(NewRsbDstReg).addMBB(RSBBB)
7953       .addReg(ABSSrcReg).addMBB(BB);
7954
7955     // remove ABS instruction
7956     MI->eraseFromParent();
7957
7958     // return last added BB
7959     return SinkBB;
7960   }
7961   case ARM::COPY_STRUCT_BYVAL_I32:
7962     ++NumLoopByVals;
7963     return EmitStructByval(MI, BB);
7964   }
7965 }
7966
7967 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7968                                                       SDNode *Node) const {
7969   if (!MI->hasPostISelHook()) {
7970     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7971            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7972     return;
7973   }
7974
7975   const MCInstrDesc *MCID = &MI->getDesc();
7976   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7977   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7978   // operand is still set to noreg. If needed, set the optional operand's
7979   // register to CPSR, and remove the redundant implicit def.
7980   //
7981   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7982
7983   // Rename pseudo opcodes.
7984   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7985   if (NewOpc) {
7986     const ARMBaseInstrInfo *TII =
7987       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7988     MCID = &TII->get(NewOpc);
7989
7990     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7991            "converted opcode should be the same except for cc_out");
7992
7993     MI->setDesc(*MCID);
7994
7995     // Add the optional cc_out operand
7996     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7997   }
7998   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7999
8000   // Any ARM instruction that sets the 's' bit should specify an optional
8001   // "cc_out" operand in the last operand position.
8002   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
8003     assert(!NewOpc && "Optional cc_out operand required");
8004     return;
8005   }
8006   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8007   // since we already have an optional CPSR def.
8008   bool definesCPSR = false;
8009   bool deadCPSR = false;
8010   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
8011        i != e; ++i) {
8012     const MachineOperand &MO = MI->getOperand(i);
8013     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8014       definesCPSR = true;
8015       if (MO.isDead())
8016         deadCPSR = true;
8017       MI->RemoveOperand(i);
8018       break;
8019     }
8020   }
8021   if (!definesCPSR) {
8022     assert(!NewOpc && "Optional cc_out operand required");
8023     return;
8024   }
8025   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8026   if (deadCPSR) {
8027     assert(!MI->getOperand(ccOutIdx).getReg() &&
8028            "expect uninitialized optional cc_out operand");
8029     return;
8030   }
8031
8032   // If this instruction was defined with an optional CPSR def and its dag node
8033   // had a live implicit CPSR def, then activate the optional CPSR def.
8034   MachineOperand &MO = MI->getOperand(ccOutIdx);
8035   MO.setReg(ARM::CPSR);
8036   MO.setIsDef(true);
8037 }
8038
8039 //===----------------------------------------------------------------------===//
8040 //                           ARM Optimization Hooks
8041 //===----------------------------------------------------------------------===//
8042
8043 // Helper function that checks if N is a null or all ones constant.
8044 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8045   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8046   if (!C)
8047     return false;
8048   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8049 }
8050
8051 // Return true if N is conditionally 0 or all ones.
8052 // Detects these expressions where cc is an i1 value:
8053 //
8054 //   (select cc 0, y)   [AllOnes=0]
8055 //   (select cc y, 0)   [AllOnes=0]
8056 //   (zext cc)          [AllOnes=0]
8057 //   (sext cc)          [AllOnes=0/1]
8058 //   (select cc -1, y)  [AllOnes=1]
8059 //   (select cc y, -1)  [AllOnes=1]
8060 //
8061 // Invert is set when N is the null/all ones constant when CC is false.
8062 // OtherOp is set to the alternative value of N.
8063 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8064                                        SDValue &CC, bool &Invert,
8065                                        SDValue &OtherOp,
8066                                        SelectionDAG &DAG) {
8067   switch (N->getOpcode()) {
8068   default: return false;
8069   case ISD::SELECT: {
8070     CC = N->getOperand(0);
8071     SDValue N1 = N->getOperand(1);
8072     SDValue N2 = N->getOperand(2);
8073     if (isZeroOrAllOnes(N1, AllOnes)) {
8074       Invert = false;
8075       OtherOp = N2;
8076       return true;
8077     }
8078     if (isZeroOrAllOnes(N2, AllOnes)) {
8079       Invert = true;
8080       OtherOp = N1;
8081       return true;
8082     }
8083     return false;
8084   }
8085   case ISD::ZERO_EXTEND:
8086     // (zext cc) can never be the all ones value.
8087     if (AllOnes)
8088       return false;
8089     // Fall through.
8090   case ISD::SIGN_EXTEND: {
8091     EVT VT = N->getValueType(0);
8092     CC = N->getOperand(0);
8093     if (CC.getValueType() != MVT::i1)
8094       return false;
8095     Invert = !AllOnes;
8096     if (AllOnes)
8097       // When looking for an AllOnes constant, N is an sext, and the 'other'
8098       // value is 0.
8099       OtherOp = DAG.getConstant(0, VT);
8100     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8101       // When looking for a 0 constant, N can be zext or sext.
8102       OtherOp = DAG.getConstant(1, VT);
8103     else
8104       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
8105     return true;
8106   }
8107   }
8108 }
8109
8110 // Combine a constant select operand into its use:
8111 //
8112 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
8113 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
8114 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
8115 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
8116 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
8117 //
8118 // The transform is rejected if the select doesn't have a constant operand that
8119 // is null, or all ones when AllOnes is set.
8120 //
8121 // Also recognize sext/zext from i1:
8122 //
8123 //   (add (zext cc), x) -> (select cc (add x, 1), x)
8124 //   (add (sext cc), x) -> (select cc (add x, -1), x)
8125 //
8126 // These transformations eventually create predicated instructions.
8127 //
8128 // @param N       The node to transform.
8129 // @param Slct    The N operand that is a select.
8130 // @param OtherOp The other N operand (x above).
8131 // @param DCI     Context.
8132 // @param AllOnes Require the select constant to be all ones instead of null.
8133 // @returns The new node, or SDValue() on failure.
8134 static
8135 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8136                             TargetLowering::DAGCombinerInfo &DCI,
8137                             bool AllOnes = false) {
8138   SelectionDAG &DAG = DCI.DAG;
8139   EVT VT = N->getValueType(0);
8140   SDValue NonConstantVal;
8141   SDValue CCOp;
8142   bool SwapSelectOps;
8143   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8144                                   NonConstantVal, DAG))
8145     return SDValue();
8146
8147   // Slct is now know to be the desired identity constant when CC is true.
8148   SDValue TrueVal = OtherOp;
8149   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8150                                  OtherOp, NonConstantVal);
8151   // Unless SwapSelectOps says CC should be false.
8152   if (SwapSelectOps)
8153     std::swap(TrueVal, FalseVal);
8154
8155   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8156                      CCOp, TrueVal, FalseVal);
8157 }
8158
8159 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8160 static
8161 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8162                                        TargetLowering::DAGCombinerInfo &DCI) {
8163   SDValue N0 = N->getOperand(0);
8164   SDValue N1 = N->getOperand(1);
8165   if (N0.getNode()->hasOneUse()) {
8166     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8167     if (Result.getNode())
8168       return Result;
8169   }
8170   if (N1.getNode()->hasOneUse()) {
8171     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8172     if (Result.getNode())
8173       return Result;
8174   }
8175   return SDValue();
8176 }
8177
8178 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8179 // (only after legalization).
8180 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8181                                  TargetLowering::DAGCombinerInfo &DCI,
8182                                  const ARMSubtarget *Subtarget) {
8183
8184   // Only perform optimization if after legalize, and if NEON is available. We
8185   // also expected both operands to be BUILD_VECTORs.
8186   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8187       || N0.getOpcode() != ISD::BUILD_VECTOR
8188       || N1.getOpcode() != ISD::BUILD_VECTOR)
8189     return SDValue();
8190
8191   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8192   EVT VT = N->getValueType(0);
8193   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8194     return SDValue();
8195
8196   // Check that the vector operands are of the right form.
8197   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8198   // operands, where N is the size of the formed vector.
8199   // Each EXTRACT_VECTOR should have the same input vector and odd or even
8200   // index such that we have a pair wise add pattern.
8201
8202   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8203   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8204     return SDValue();
8205   SDValue Vec = N0->getOperand(0)->getOperand(0);
8206   SDNode *V = Vec.getNode();
8207   unsigned nextIndex = 0;
8208
8209   // For each operands to the ADD which are BUILD_VECTORs,
8210   // check to see if each of their operands are an EXTRACT_VECTOR with
8211   // the same vector and appropriate index.
8212   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8213     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8214         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8215
8216       SDValue ExtVec0 = N0->getOperand(i);
8217       SDValue ExtVec1 = N1->getOperand(i);
8218
8219       // First operand is the vector, verify its the same.
8220       if (V != ExtVec0->getOperand(0).getNode() ||
8221           V != ExtVec1->getOperand(0).getNode())
8222         return SDValue();
8223
8224       // Second is the constant, verify its correct.
8225       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8226       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8227
8228       // For the constant, we want to see all the even or all the odd.
8229       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8230           || C1->getZExtValue() != nextIndex+1)
8231         return SDValue();
8232
8233       // Increment index.
8234       nextIndex+=2;
8235     } else
8236       return SDValue();
8237   }
8238
8239   // Create VPADDL node.
8240   SelectionDAG &DAG = DCI.DAG;
8241   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8242
8243   // Build operand list.
8244   SmallVector<SDValue, 8> Ops;
8245   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
8246                                 TLI.getPointerTy()));
8247
8248   // Input is the vector.
8249   Ops.push_back(Vec);
8250
8251   // Get widened type and narrowed type.
8252   MVT widenType;
8253   unsigned numElem = VT.getVectorNumElements();
8254   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8255     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8256     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8257     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8258     default:
8259       llvm_unreachable("Invalid vector element type for padd optimization.");
8260   }
8261
8262   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
8263                             widenType, &Ops[0], Ops.size());
8264   return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, tmp);
8265 }
8266
8267 static SDValue findMUL_LOHI(SDValue V) {
8268   if (V->getOpcode() == ISD::UMUL_LOHI ||
8269       V->getOpcode() == ISD::SMUL_LOHI)
8270     return V;
8271   return SDValue();
8272 }
8273
8274 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8275                                      TargetLowering::DAGCombinerInfo &DCI,
8276                                      const ARMSubtarget *Subtarget) {
8277
8278   if (Subtarget->isThumb1Only()) return SDValue();
8279
8280   // Only perform the checks after legalize when the pattern is available.
8281   if (DCI.isBeforeLegalize()) return SDValue();
8282
8283   // Look for multiply add opportunities.
8284   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8285   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8286   // a glue link from the first add to the second add.
8287   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8288   // a S/UMLAL instruction.
8289   //          loAdd   UMUL_LOHI
8290   //            \    / :lo    \ :hi
8291   //             \  /          \          [no multiline comment]
8292   //              ADDC         |  hiAdd
8293   //                 \ :glue  /  /
8294   //                  \      /  /
8295   //                    ADDE
8296   //
8297   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8298   SDValue AddcOp0 = AddcNode->getOperand(0);
8299   SDValue AddcOp1 = AddcNode->getOperand(1);
8300
8301   // Check if the two operands are from the same mul_lohi node.
8302   if (AddcOp0.getNode() == AddcOp1.getNode())
8303     return SDValue();
8304
8305   assert(AddcNode->getNumValues() == 2 &&
8306          AddcNode->getValueType(0) == MVT::i32 &&
8307          "Expect ADDC with two result values. First: i32");
8308
8309   // Check that we have a glued ADDC node.
8310   if (AddcNode->getValueType(1) != MVT::Glue)
8311     return SDValue();
8312
8313   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8314   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8315       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8316       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8317       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8318     return SDValue();
8319
8320   // Look for the glued ADDE.
8321   SDNode* AddeNode = AddcNode->getGluedUser();
8322   if (AddeNode == NULL)
8323     return SDValue();
8324
8325   // Make sure it is really an ADDE.
8326   if (AddeNode->getOpcode() != ISD::ADDE)
8327     return SDValue();
8328
8329   assert(AddeNode->getNumOperands() == 3 &&
8330          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8331          "ADDE node has the wrong inputs");
8332
8333   // Check for the triangle shape.
8334   SDValue AddeOp0 = AddeNode->getOperand(0);
8335   SDValue AddeOp1 = AddeNode->getOperand(1);
8336
8337   // Make sure that the ADDE operands are not coming from the same node.
8338   if (AddeOp0.getNode() == AddeOp1.getNode())
8339     return SDValue();
8340
8341   // Find the MUL_LOHI node walking up ADDE's operands.
8342   bool IsLeftOperandMUL = false;
8343   SDValue MULOp = findMUL_LOHI(AddeOp0);
8344   if (MULOp == SDValue())
8345    MULOp = findMUL_LOHI(AddeOp1);
8346   else
8347     IsLeftOperandMUL = true;
8348   if (MULOp == SDValue())
8349      return SDValue();
8350
8351   // Figure out the right opcode.
8352   unsigned Opc = MULOp->getOpcode();
8353   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8354
8355   // Figure out the high and low input values to the MLAL node.
8356   SDValue* HiMul = &MULOp;
8357   SDValue* HiAdd = NULL;
8358   SDValue* LoMul = NULL;
8359   SDValue* LowAdd = NULL;
8360
8361   if (IsLeftOperandMUL)
8362     HiAdd = &AddeOp1;
8363   else
8364     HiAdd = &AddeOp0;
8365
8366
8367   if (AddcOp0->getOpcode() == Opc) {
8368     LoMul = &AddcOp0;
8369     LowAdd = &AddcOp1;
8370   }
8371   if (AddcOp1->getOpcode() == Opc) {
8372     LoMul = &AddcOp1;
8373     LowAdd = &AddcOp0;
8374   }
8375
8376   if (LoMul == NULL)
8377     return SDValue();
8378
8379   if (LoMul->getNode() != HiMul->getNode())
8380     return SDValue();
8381
8382   // Create the merged node.
8383   SelectionDAG &DAG = DCI.DAG;
8384
8385   // Build operand list.
8386   SmallVector<SDValue, 8> Ops;
8387   Ops.push_back(LoMul->getOperand(0));
8388   Ops.push_back(LoMul->getOperand(1));
8389   Ops.push_back(*LowAdd);
8390   Ops.push_back(*HiAdd);
8391
8392   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8393                                  DAG.getVTList(MVT::i32, MVT::i32),
8394                                  &Ops[0], Ops.size());
8395
8396   // Replace the ADDs' nodes uses by the MLA node's values.
8397   SDValue HiMLALResult(MLALNode.getNode(), 1);
8398   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8399
8400   SDValue LoMLALResult(MLALNode.getNode(), 0);
8401   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8402
8403   // Return original node to notify the driver to stop replacing.
8404   SDValue resNode(AddcNode, 0);
8405   return resNode;
8406 }
8407
8408 /// PerformADDCCombine - Target-specific dag combine transform from
8409 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8410 static SDValue PerformADDCCombine(SDNode *N,
8411                                  TargetLowering::DAGCombinerInfo &DCI,
8412                                  const ARMSubtarget *Subtarget) {
8413
8414   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8415
8416 }
8417
8418 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8419 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8420 /// called with the default operands, and if that fails, with commuted
8421 /// operands.
8422 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8423                                           TargetLowering::DAGCombinerInfo &DCI,
8424                                           const ARMSubtarget *Subtarget){
8425
8426   // Attempt to create vpaddl for this add.
8427   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8428   if (Result.getNode())
8429     return Result;
8430
8431   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8432   if (N0.getNode()->hasOneUse()) {
8433     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8434     if (Result.getNode()) return Result;
8435   }
8436   return SDValue();
8437 }
8438
8439 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8440 ///
8441 static SDValue PerformADDCombine(SDNode *N,
8442                                  TargetLowering::DAGCombinerInfo &DCI,
8443                                  const ARMSubtarget *Subtarget) {
8444   SDValue N0 = N->getOperand(0);
8445   SDValue N1 = N->getOperand(1);
8446
8447   // First try with the default operand order.
8448   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8449   if (Result.getNode())
8450     return Result;
8451
8452   // If that didn't work, try again with the operands commuted.
8453   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8454 }
8455
8456 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8457 ///
8458 static SDValue PerformSUBCombine(SDNode *N,
8459                                  TargetLowering::DAGCombinerInfo &DCI) {
8460   SDValue N0 = N->getOperand(0);
8461   SDValue N1 = N->getOperand(1);
8462
8463   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8464   if (N1.getNode()->hasOneUse()) {
8465     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8466     if (Result.getNode()) return Result;
8467   }
8468
8469   return SDValue();
8470 }
8471
8472 /// PerformVMULCombine
8473 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8474 /// special multiplier accumulator forwarding.
8475 ///   vmul d3, d0, d2
8476 ///   vmla d3, d1, d2
8477 /// is faster than
8478 ///   vadd d3, d0, d1
8479 ///   vmul d3, d3, d2
8480 //  However, for (A + B) * (A + B),
8481 //    vadd d2, d0, d1
8482 //    vmul d3, d0, d2
8483 //    vmla d3, d1, d2
8484 //  is slower than
8485 //    vadd d2, d0, d1
8486 //    vmul d3, d2, d2
8487 static SDValue PerformVMULCombine(SDNode *N,
8488                                   TargetLowering::DAGCombinerInfo &DCI,
8489                                   const ARMSubtarget *Subtarget) {
8490   if (!Subtarget->hasVMLxForwarding())
8491     return SDValue();
8492
8493   SelectionDAG &DAG = DCI.DAG;
8494   SDValue N0 = N->getOperand(0);
8495   SDValue N1 = N->getOperand(1);
8496   unsigned Opcode = N0.getOpcode();
8497   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8498       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8499     Opcode = N1.getOpcode();
8500     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8501         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8502       return SDValue();
8503     std::swap(N0, N1);
8504   }
8505
8506   if (N0 == N1)
8507     return SDValue();
8508
8509   EVT VT = N->getValueType(0);
8510   SDLoc DL(N);
8511   SDValue N00 = N0->getOperand(0);
8512   SDValue N01 = N0->getOperand(1);
8513   return DAG.getNode(Opcode, DL, VT,
8514                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8515                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8516 }
8517
8518 static SDValue PerformMULCombine(SDNode *N,
8519                                  TargetLowering::DAGCombinerInfo &DCI,
8520                                  const ARMSubtarget *Subtarget) {
8521   SelectionDAG &DAG = DCI.DAG;
8522
8523   if (Subtarget->isThumb1Only())
8524     return SDValue();
8525
8526   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8527     return SDValue();
8528
8529   EVT VT = N->getValueType(0);
8530   if (VT.is64BitVector() || VT.is128BitVector())
8531     return PerformVMULCombine(N, DCI, Subtarget);
8532   if (VT != MVT::i32)
8533     return SDValue();
8534
8535   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8536   if (!C)
8537     return SDValue();
8538
8539   int64_t MulAmt = C->getSExtValue();
8540   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8541
8542   ShiftAmt = ShiftAmt & (32 - 1);
8543   SDValue V = N->getOperand(0);
8544   SDLoc DL(N);
8545
8546   SDValue Res;
8547   MulAmt >>= ShiftAmt;
8548
8549   if (MulAmt >= 0) {
8550     if (isPowerOf2_32(MulAmt - 1)) {
8551       // (mul x, 2^N + 1) => (add (shl x, N), x)
8552       Res = DAG.getNode(ISD::ADD, DL, VT,
8553                         V,
8554                         DAG.getNode(ISD::SHL, DL, VT,
8555                                     V,
8556                                     DAG.getConstant(Log2_32(MulAmt - 1),
8557                                                     MVT::i32)));
8558     } else if (isPowerOf2_32(MulAmt + 1)) {
8559       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8560       Res = DAG.getNode(ISD::SUB, DL, VT,
8561                         DAG.getNode(ISD::SHL, DL, VT,
8562                                     V,
8563                                     DAG.getConstant(Log2_32(MulAmt + 1),
8564                                                     MVT::i32)),
8565                         V);
8566     } else
8567       return SDValue();
8568   } else {
8569     uint64_t MulAmtAbs = -MulAmt;
8570     if (isPowerOf2_32(MulAmtAbs + 1)) {
8571       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8572       Res = DAG.getNode(ISD::SUB, DL, VT,
8573                         V,
8574                         DAG.getNode(ISD::SHL, DL, VT,
8575                                     V,
8576                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8577                                                     MVT::i32)));
8578     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8579       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8580       Res = DAG.getNode(ISD::ADD, DL, VT,
8581                         V,
8582                         DAG.getNode(ISD::SHL, DL, VT,
8583                                     V,
8584                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8585                                                     MVT::i32)));
8586       Res = DAG.getNode(ISD::SUB, DL, VT,
8587                         DAG.getConstant(0, MVT::i32),Res);
8588
8589     } else
8590       return SDValue();
8591   }
8592
8593   if (ShiftAmt != 0)
8594     Res = DAG.getNode(ISD::SHL, DL, VT,
8595                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8596
8597   // Do not add new nodes to DAG combiner worklist.
8598   DCI.CombineTo(N, Res, false);
8599   return SDValue();
8600 }
8601
8602 static SDValue PerformANDCombine(SDNode *N,
8603                                  TargetLowering::DAGCombinerInfo &DCI,
8604                                  const ARMSubtarget *Subtarget) {
8605
8606   // Attempt to use immediate-form VBIC
8607   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8608   SDLoc dl(N);
8609   EVT VT = N->getValueType(0);
8610   SelectionDAG &DAG = DCI.DAG;
8611
8612   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8613     return SDValue();
8614
8615   APInt SplatBits, SplatUndef;
8616   unsigned SplatBitSize;
8617   bool HasAnyUndefs;
8618   if (BVN &&
8619       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8620     if (SplatBitSize <= 64) {
8621       EVT VbicVT;
8622       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8623                                       SplatUndef.getZExtValue(), SplatBitSize,
8624                                       DAG, VbicVT, VT.is128BitVector(),
8625                                       OtherModImm);
8626       if (Val.getNode()) {
8627         SDValue Input =
8628           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8629         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8630         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8631       }
8632     }
8633   }
8634
8635   if (!Subtarget->isThumb1Only()) {
8636     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8637     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8638     if (Result.getNode())
8639       return Result;
8640   }
8641
8642   return SDValue();
8643 }
8644
8645 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8646 static SDValue PerformORCombine(SDNode *N,
8647                                 TargetLowering::DAGCombinerInfo &DCI,
8648                                 const ARMSubtarget *Subtarget) {
8649   // Attempt to use immediate-form VORR
8650   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8651   SDLoc dl(N);
8652   EVT VT = N->getValueType(0);
8653   SelectionDAG &DAG = DCI.DAG;
8654
8655   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8656     return SDValue();
8657
8658   APInt SplatBits, SplatUndef;
8659   unsigned SplatBitSize;
8660   bool HasAnyUndefs;
8661   if (BVN && Subtarget->hasNEON() &&
8662       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8663     if (SplatBitSize <= 64) {
8664       EVT VorrVT;
8665       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8666                                       SplatUndef.getZExtValue(), SplatBitSize,
8667                                       DAG, VorrVT, VT.is128BitVector(),
8668                                       OtherModImm);
8669       if (Val.getNode()) {
8670         SDValue Input =
8671           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8672         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8673         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8674       }
8675     }
8676   }
8677
8678   if (!Subtarget->isThumb1Only()) {
8679     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8680     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8681     if (Result.getNode())
8682       return Result;
8683   }
8684
8685   // The code below optimizes (or (and X, Y), Z).
8686   // The AND operand needs to have a single user to make these optimizations
8687   // profitable.
8688   SDValue N0 = N->getOperand(0);
8689   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8690     return SDValue();
8691   SDValue N1 = N->getOperand(1);
8692
8693   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8694   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8695       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8696     APInt SplatUndef;
8697     unsigned SplatBitSize;
8698     bool HasAnyUndefs;
8699
8700     APInt SplatBits0, SplatBits1;
8701     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8702     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8703     // Ensure that the second operand of both ands are constants
8704     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8705                                       HasAnyUndefs) && !HasAnyUndefs) {
8706         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8707                                           HasAnyUndefs) && !HasAnyUndefs) {
8708             // Ensure that the bit width of the constants are the same and that
8709             // the splat arguments are logical inverses as per the pattern we
8710             // are trying to simplify.
8711             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8712                 SplatBits0 == ~SplatBits1) {
8713                 // Canonicalize the vector type to make instruction selection
8714                 // simpler.
8715                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8716                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8717                                              N0->getOperand(1),
8718                                              N0->getOperand(0),
8719                                              N1->getOperand(0));
8720                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8721             }
8722         }
8723     }
8724   }
8725
8726   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8727   // reasonable.
8728
8729   // BFI is only available on V6T2+
8730   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8731     return SDValue();
8732
8733   SDLoc DL(N);
8734   // 1) or (and A, mask), val => ARMbfi A, val, mask
8735   //      iff (val & mask) == val
8736   //
8737   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8738   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8739   //          && mask == ~mask2
8740   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8741   //          && ~mask == mask2
8742   //  (i.e., copy a bitfield value into another bitfield of the same width)
8743
8744   if (VT != MVT::i32)
8745     return SDValue();
8746
8747   SDValue N00 = N0.getOperand(0);
8748
8749   // The value and the mask need to be constants so we can verify this is
8750   // actually a bitfield set. If the mask is 0xffff, we can do better
8751   // via a movt instruction, so don't use BFI in that case.
8752   SDValue MaskOp = N0.getOperand(1);
8753   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8754   if (!MaskC)
8755     return SDValue();
8756   unsigned Mask = MaskC->getZExtValue();
8757   if (Mask == 0xffff)
8758     return SDValue();
8759   SDValue Res;
8760   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8761   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8762   if (N1C) {
8763     unsigned Val = N1C->getZExtValue();
8764     if ((Val & ~Mask) != Val)
8765       return SDValue();
8766
8767     if (ARM::isBitFieldInvertedMask(Mask)) {
8768       Val >>= countTrailingZeros(~Mask);
8769
8770       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8771                         DAG.getConstant(Val, MVT::i32),
8772                         DAG.getConstant(Mask, MVT::i32));
8773
8774       // Do not add new nodes to DAG combiner worklist.
8775       DCI.CombineTo(N, Res, false);
8776       return SDValue();
8777     }
8778   } else if (N1.getOpcode() == ISD::AND) {
8779     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8780     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8781     if (!N11C)
8782       return SDValue();
8783     unsigned Mask2 = N11C->getZExtValue();
8784
8785     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8786     // as is to match.
8787     if (ARM::isBitFieldInvertedMask(Mask) &&
8788         (Mask == ~Mask2)) {
8789       // The pack halfword instruction works better for masks that fit it,
8790       // so use that when it's available.
8791       if (Subtarget->hasT2ExtractPack() &&
8792           (Mask == 0xffff || Mask == 0xffff0000))
8793         return SDValue();
8794       // 2a
8795       unsigned amt = countTrailingZeros(Mask2);
8796       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8797                         DAG.getConstant(amt, MVT::i32));
8798       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8799                         DAG.getConstant(Mask, MVT::i32));
8800       // Do not add new nodes to DAG combiner worklist.
8801       DCI.CombineTo(N, Res, false);
8802       return SDValue();
8803     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8804                (~Mask == Mask2)) {
8805       // The pack halfword instruction works better for masks that fit it,
8806       // so use that when it's available.
8807       if (Subtarget->hasT2ExtractPack() &&
8808           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8809         return SDValue();
8810       // 2b
8811       unsigned lsb = countTrailingZeros(Mask);
8812       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8813                         DAG.getConstant(lsb, MVT::i32));
8814       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8815                         DAG.getConstant(Mask2, MVT::i32));
8816       // Do not add new nodes to DAG combiner worklist.
8817       DCI.CombineTo(N, Res, false);
8818       return SDValue();
8819     }
8820   }
8821
8822   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8823       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8824       ARM::isBitFieldInvertedMask(~Mask)) {
8825     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8826     // where lsb(mask) == #shamt and masked bits of B are known zero.
8827     SDValue ShAmt = N00.getOperand(1);
8828     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8829     unsigned LSB = countTrailingZeros(Mask);
8830     if (ShAmtC != LSB)
8831       return SDValue();
8832
8833     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8834                       DAG.getConstant(~Mask, MVT::i32));
8835
8836     // Do not add new nodes to DAG combiner worklist.
8837     DCI.CombineTo(N, Res, false);
8838   }
8839
8840   return SDValue();
8841 }
8842
8843 static SDValue PerformXORCombine(SDNode *N,
8844                                  TargetLowering::DAGCombinerInfo &DCI,
8845                                  const ARMSubtarget *Subtarget) {
8846   EVT VT = N->getValueType(0);
8847   SelectionDAG &DAG = DCI.DAG;
8848
8849   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8850     return SDValue();
8851
8852   if (!Subtarget->isThumb1Only()) {
8853     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8854     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8855     if (Result.getNode())
8856       return Result;
8857   }
8858
8859   return SDValue();
8860 }
8861
8862 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8863 /// the bits being cleared by the AND are not demanded by the BFI.
8864 static SDValue PerformBFICombine(SDNode *N,
8865                                  TargetLowering::DAGCombinerInfo &DCI) {
8866   SDValue N1 = N->getOperand(1);
8867   if (N1.getOpcode() == ISD::AND) {
8868     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8869     if (!N11C)
8870       return SDValue();
8871     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8872     unsigned LSB = countTrailingZeros(~InvMask);
8873     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8874     unsigned Mask = (1 << Width)-1;
8875     unsigned Mask2 = N11C->getZExtValue();
8876     if ((Mask & (~Mask2)) == 0)
8877       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8878                              N->getOperand(0), N1.getOperand(0),
8879                              N->getOperand(2));
8880   }
8881   return SDValue();
8882 }
8883
8884 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8885 /// ARMISD::VMOVRRD.
8886 static SDValue PerformVMOVRRDCombine(SDNode *N,
8887                                      TargetLowering::DAGCombinerInfo &DCI) {
8888   // vmovrrd(vmovdrr x, y) -> x,y
8889   SDValue InDouble = N->getOperand(0);
8890   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8891     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8892
8893   // vmovrrd(load f64) -> (load i32), (load i32)
8894   SDNode *InNode = InDouble.getNode();
8895   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8896       InNode->getValueType(0) == MVT::f64 &&
8897       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8898       !cast<LoadSDNode>(InNode)->isVolatile()) {
8899     // TODO: Should this be done for non-FrameIndex operands?
8900     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8901
8902     SelectionDAG &DAG = DCI.DAG;
8903     SDLoc DL(LD);
8904     SDValue BasePtr = LD->getBasePtr();
8905     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8906                                  LD->getPointerInfo(), LD->isVolatile(),
8907                                  LD->isNonTemporal(), LD->isInvariant(),
8908                                  LD->getAlignment());
8909
8910     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8911                                     DAG.getConstant(4, MVT::i32));
8912     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8913                                  LD->getPointerInfo(), LD->isVolatile(),
8914                                  LD->isNonTemporal(), LD->isInvariant(),
8915                                  std::min(4U, LD->getAlignment() / 2));
8916
8917     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8918     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8919     DCI.RemoveFromWorklist(LD);
8920     DAG.DeleteNode(LD);
8921     return Result;
8922   }
8923
8924   return SDValue();
8925 }
8926
8927 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8928 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8929 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8930   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8931   SDValue Op0 = N->getOperand(0);
8932   SDValue Op1 = N->getOperand(1);
8933   if (Op0.getOpcode() == ISD::BITCAST)
8934     Op0 = Op0.getOperand(0);
8935   if (Op1.getOpcode() == ISD::BITCAST)
8936     Op1 = Op1.getOperand(0);
8937   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8938       Op0.getNode() == Op1.getNode() &&
8939       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8940     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8941                        N->getValueType(0), Op0.getOperand(0));
8942   return SDValue();
8943 }
8944
8945 /// PerformSTORECombine - Target-specific dag combine xforms for
8946 /// ISD::STORE.
8947 static SDValue PerformSTORECombine(SDNode *N,
8948                                    TargetLowering::DAGCombinerInfo &DCI) {
8949   StoreSDNode *St = cast<StoreSDNode>(N);
8950   if (St->isVolatile())
8951     return SDValue();
8952
8953   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8954   // pack all of the elements in one place.  Next, store to memory in fewer
8955   // chunks.
8956   SDValue StVal = St->getValue();
8957   EVT VT = StVal.getValueType();
8958   if (St->isTruncatingStore() && VT.isVector()) {
8959     SelectionDAG &DAG = DCI.DAG;
8960     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8961     EVT StVT = St->getMemoryVT();
8962     unsigned NumElems = VT.getVectorNumElements();
8963     assert(StVT != VT && "Cannot truncate to the same type");
8964     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8965     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8966
8967     // From, To sizes and ElemCount must be pow of two
8968     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8969
8970     // We are going to use the original vector elt for storing.
8971     // Accumulated smaller vector elements must be a multiple of the store size.
8972     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8973
8974     unsigned SizeRatio  = FromEltSz / ToEltSz;
8975     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8976
8977     // Create a type on which we perform the shuffle.
8978     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8979                                      NumElems*SizeRatio);
8980     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8981
8982     SDLoc DL(St);
8983     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8984     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8985     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8986
8987     // Can't shuffle using an illegal type.
8988     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8989
8990     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8991                                 DAG.getUNDEF(WideVec.getValueType()),
8992                                 ShuffleVec.data());
8993     // At this point all of the data is stored at the bottom of the
8994     // register. We now need to save it to mem.
8995
8996     // Find the largest store unit
8997     MVT StoreType = MVT::i8;
8998     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8999          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
9000       MVT Tp = (MVT::SimpleValueType)tp;
9001       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9002         StoreType = Tp;
9003     }
9004     // Didn't find a legal store type.
9005     if (!TLI.isTypeLegal(StoreType))
9006       return SDValue();
9007
9008     // Bitcast the original vector into a vector of store-size units
9009     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9010             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9011     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9012     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9013     SmallVector<SDValue, 8> Chains;
9014     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
9015                                         TLI.getPointerTy());
9016     SDValue BasePtr = St->getBasePtr();
9017
9018     // Perform one or more big stores into memory.
9019     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9020     for (unsigned I = 0; I < E; I++) {
9021       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9022                                    StoreType, ShuffWide,
9023                                    DAG.getIntPtrConstant(I));
9024       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9025                                 St->getPointerInfo(), St->isVolatile(),
9026                                 St->isNonTemporal(), St->getAlignment());
9027       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9028                             Increment);
9029       Chains.push_back(Ch);
9030     }
9031     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
9032                        Chains.size());
9033   }
9034
9035   if (!ISD::isNormalStore(St))
9036     return SDValue();
9037
9038   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9039   // ARM stores of arguments in the same cache line.
9040   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9041       StVal.getNode()->hasOneUse()) {
9042     SelectionDAG  &DAG = DCI.DAG;
9043     SDLoc DL(St);
9044     SDValue BasePtr = St->getBasePtr();
9045     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9046                                   StVal.getNode()->getOperand(0), BasePtr,
9047                                   St->getPointerInfo(), St->isVolatile(),
9048                                   St->isNonTemporal(), St->getAlignment());
9049
9050     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9051                                     DAG.getConstant(4, MVT::i32));
9052     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
9053                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9054                         St->isNonTemporal(),
9055                         std::min(4U, St->getAlignment() / 2));
9056   }
9057
9058   if (StVal.getValueType() != MVT::i64 ||
9059       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9060     return SDValue();
9061
9062   // Bitcast an i64 store extracted from a vector to f64.
9063   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9064   SelectionDAG &DAG = DCI.DAG;
9065   SDLoc dl(StVal);
9066   SDValue IntVec = StVal.getOperand(0);
9067   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9068                                  IntVec.getValueType().getVectorNumElements());
9069   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9070   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9071                                Vec, StVal.getOperand(1));
9072   dl = SDLoc(N);
9073   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9074   // Make the DAGCombiner fold the bitcasts.
9075   DCI.AddToWorklist(Vec.getNode());
9076   DCI.AddToWorklist(ExtElt.getNode());
9077   DCI.AddToWorklist(V.getNode());
9078   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9079                       St->getPointerInfo(), St->isVolatile(),
9080                       St->isNonTemporal(), St->getAlignment(),
9081                       St->getTBAAInfo());
9082 }
9083
9084 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9085 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
9086 /// i64 vector to have f64 elements, since the value can then be loaded
9087 /// directly into a VFP register.
9088 static bool hasNormalLoadOperand(SDNode *N) {
9089   unsigned NumElts = N->getValueType(0).getVectorNumElements();
9090   for (unsigned i = 0; i < NumElts; ++i) {
9091     SDNode *Elt = N->getOperand(i).getNode();
9092     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9093       return true;
9094   }
9095   return false;
9096 }
9097
9098 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9099 /// ISD::BUILD_VECTOR.
9100 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9101                                           TargetLowering::DAGCombinerInfo &DCI){
9102   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9103   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
9104   // into a pair of GPRs, which is fine when the value is used as a scalar,
9105   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9106   SelectionDAG &DAG = DCI.DAG;
9107   if (N->getNumOperands() == 2) {
9108     SDValue RV = PerformVMOVDRRCombine(N, DAG);
9109     if (RV.getNode())
9110       return RV;
9111   }
9112
9113   // Load i64 elements as f64 values so that type legalization does not split
9114   // them up into i32 values.
9115   EVT VT = N->getValueType(0);
9116   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9117     return SDValue();
9118   SDLoc dl(N);
9119   SmallVector<SDValue, 8> Ops;
9120   unsigned NumElts = VT.getVectorNumElements();
9121   for (unsigned i = 0; i < NumElts; ++i) {
9122     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9123     Ops.push_back(V);
9124     // Make the DAGCombiner fold the bitcast.
9125     DCI.AddToWorklist(V.getNode());
9126   }
9127   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9128   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
9129   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9130 }
9131
9132 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9133 static SDValue
9134 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9135   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9136   // At that time, we may have inserted bitcasts from integer to float.
9137   // If these bitcasts have survived DAGCombine, change the lowering of this
9138   // BUILD_VECTOR in something more vector friendly, i.e., that does not
9139   // force to use floating point types.
9140
9141   // Make sure we can change the type of the vector.
9142   // This is possible iff:
9143   // 1. The vector is only used in a bitcast to a integer type. I.e.,
9144   //    1.1. Vector is used only once.
9145   //    1.2. Use is a bit convert to an integer type.
9146   // 2. The size of its operands are 32-bits (64-bits are not legal).
9147   EVT VT = N->getValueType(0);
9148   EVT EltVT = VT.getVectorElementType();
9149
9150   // Check 1.1. and 2.
9151   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9152     return SDValue();
9153
9154   // By construction, the input type must be float.
9155   assert(EltVT == MVT::f32 && "Unexpected type!");
9156
9157   // Check 1.2.
9158   SDNode *Use = *N->use_begin();
9159   if (Use->getOpcode() != ISD::BITCAST ||
9160       Use->getValueType(0).isFloatingPoint())
9161     return SDValue();
9162
9163   // Check profitability.
9164   // Model is, if more than half of the relevant operands are bitcast from
9165   // i32, turn the build_vector into a sequence of insert_vector_elt.
9166   // Relevant operands are everything that is not statically
9167   // (i.e., at compile time) bitcasted.
9168   unsigned NumOfBitCastedElts = 0;
9169   unsigned NumElts = VT.getVectorNumElements();
9170   unsigned NumOfRelevantElts = NumElts;
9171   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9172     SDValue Elt = N->getOperand(Idx);
9173     if (Elt->getOpcode() == ISD::BITCAST) {
9174       // Assume only bit cast to i32 will go away.
9175       if (Elt->getOperand(0).getValueType() == MVT::i32)
9176         ++NumOfBitCastedElts;
9177     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9178       // Constants are statically casted, thus do not count them as
9179       // relevant operands.
9180       --NumOfRelevantElts;
9181   }
9182
9183   // Check if more than half of the elements require a non-free bitcast.
9184   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9185     return SDValue();
9186
9187   SelectionDAG &DAG = DCI.DAG;
9188   // Create the new vector type.
9189   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9190   // Check if the type is legal.
9191   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9192   if (!TLI.isTypeLegal(VecVT))
9193     return SDValue();
9194
9195   // Combine:
9196   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9197   // => BITCAST INSERT_VECTOR_ELT
9198   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9199   //                      (BITCAST EN), N.
9200   SDValue Vec = DAG.getUNDEF(VecVT);
9201   SDLoc dl(N);
9202   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9203     SDValue V = N->getOperand(Idx);
9204     if (V.getOpcode() == ISD::UNDEF)
9205       continue;
9206     if (V.getOpcode() == ISD::BITCAST &&
9207         V->getOperand(0).getValueType() == MVT::i32)
9208       // Fold obvious case.
9209       V = V.getOperand(0);
9210     else {
9211       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 
9212       // Make the DAGCombiner fold the bitcasts.
9213       DCI.AddToWorklist(V.getNode());
9214     }
9215     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
9216     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9217   }
9218   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9219   // Make the DAGCombiner fold the bitcasts.
9220   DCI.AddToWorklist(Vec.getNode());
9221   return Vec;
9222 }
9223
9224 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9225 /// ISD::INSERT_VECTOR_ELT.
9226 static SDValue PerformInsertEltCombine(SDNode *N,
9227                                        TargetLowering::DAGCombinerInfo &DCI) {
9228   // Bitcast an i64 load inserted into a vector to f64.
9229   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9230   EVT VT = N->getValueType(0);
9231   SDNode *Elt = N->getOperand(1).getNode();
9232   if (VT.getVectorElementType() != MVT::i64 ||
9233       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9234     return SDValue();
9235
9236   SelectionDAG &DAG = DCI.DAG;
9237   SDLoc dl(N);
9238   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9239                                  VT.getVectorNumElements());
9240   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9241   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9242   // Make the DAGCombiner fold the bitcasts.
9243   DCI.AddToWorklist(Vec.getNode());
9244   DCI.AddToWorklist(V.getNode());
9245   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9246                                Vec, V, N->getOperand(2));
9247   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9248 }
9249
9250 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9251 /// ISD::VECTOR_SHUFFLE.
9252 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9253   // The LLVM shufflevector instruction does not require the shuffle mask
9254   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9255   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
9256   // operands do not match the mask length, they are extended by concatenating
9257   // them with undef vectors.  That is probably the right thing for other
9258   // targets, but for NEON it is better to concatenate two double-register
9259   // size vector operands into a single quad-register size vector.  Do that
9260   // transformation here:
9261   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
9262   //   shuffle(concat(v1, v2), undef)
9263   SDValue Op0 = N->getOperand(0);
9264   SDValue Op1 = N->getOperand(1);
9265   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9266       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9267       Op0.getNumOperands() != 2 ||
9268       Op1.getNumOperands() != 2)
9269     return SDValue();
9270   SDValue Concat0Op1 = Op0.getOperand(1);
9271   SDValue Concat1Op1 = Op1.getOperand(1);
9272   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9273       Concat1Op1.getOpcode() != ISD::UNDEF)
9274     return SDValue();
9275   // Skip the transformation if any of the types are illegal.
9276   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9277   EVT VT = N->getValueType(0);
9278   if (!TLI.isTypeLegal(VT) ||
9279       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9280       !TLI.isTypeLegal(Concat1Op1.getValueType()))
9281     return SDValue();
9282
9283   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9284                                   Op0.getOperand(0), Op1.getOperand(0));
9285   // Translate the shuffle mask.
9286   SmallVector<int, 16> NewMask;
9287   unsigned NumElts = VT.getVectorNumElements();
9288   unsigned HalfElts = NumElts/2;
9289   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9290   for (unsigned n = 0; n < NumElts; ++n) {
9291     int MaskElt = SVN->getMaskElt(n);
9292     int NewElt = -1;
9293     if (MaskElt < (int)HalfElts)
9294       NewElt = MaskElt;
9295     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9296       NewElt = HalfElts + MaskElt - NumElts;
9297     NewMask.push_back(NewElt);
9298   }
9299   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9300                               DAG.getUNDEF(VT), NewMask.data());
9301 }
9302
9303 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
9304 /// NEON load/store intrinsics to merge base address updates.
9305 static SDValue CombineBaseUpdate(SDNode *N,
9306                                  TargetLowering::DAGCombinerInfo &DCI) {
9307   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9308     return SDValue();
9309
9310   SelectionDAG &DAG = DCI.DAG;
9311   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9312                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9313   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
9314   SDValue Addr = N->getOperand(AddrOpIdx);
9315
9316   // Search for a use of the address operand that is an increment.
9317   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9318          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9319     SDNode *User = *UI;
9320     if (User->getOpcode() != ISD::ADD ||
9321         UI.getUse().getResNo() != Addr.getResNo())
9322       continue;
9323
9324     // Check that the add is independent of the load/store.  Otherwise, folding
9325     // it would create a cycle.
9326     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9327       continue;
9328
9329     // Find the new opcode for the updating load/store.
9330     bool isLoad = true;
9331     bool isLaneOp = false;
9332     unsigned NewOpc = 0;
9333     unsigned NumVecs = 0;
9334     if (isIntrinsic) {
9335       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9336       switch (IntNo) {
9337       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9338       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9339         NumVecs = 1; break;
9340       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9341         NumVecs = 2; break;
9342       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9343         NumVecs = 3; break;
9344       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9345         NumVecs = 4; break;
9346       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9347         NumVecs = 2; isLaneOp = true; break;
9348       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9349         NumVecs = 3; isLaneOp = true; break;
9350       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9351         NumVecs = 4; isLaneOp = true; break;
9352       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9353         NumVecs = 1; isLoad = false; break;
9354       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9355         NumVecs = 2; isLoad = false; break;
9356       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9357         NumVecs = 3; isLoad = false; break;
9358       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9359         NumVecs = 4; isLoad = false; break;
9360       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9361         NumVecs = 2; isLoad = false; isLaneOp = true; break;
9362       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9363         NumVecs = 3; isLoad = false; isLaneOp = true; break;
9364       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9365         NumVecs = 4; isLoad = false; isLaneOp = true; break;
9366       }
9367     } else {
9368       isLaneOp = true;
9369       switch (N->getOpcode()) {
9370       default: llvm_unreachable("unexpected opcode for Neon base update");
9371       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9372       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9373       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9374       }
9375     }
9376
9377     // Find the size of memory referenced by the load/store.
9378     EVT VecTy;
9379     if (isLoad)
9380       VecTy = N->getValueType(0);
9381     else
9382       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9383     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9384     if (isLaneOp)
9385       NumBytes /= VecTy.getVectorNumElements();
9386
9387     // If the increment is a constant, it must match the memory ref size.
9388     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9389     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9390       uint64_t IncVal = CInc->getZExtValue();
9391       if (IncVal != NumBytes)
9392         continue;
9393     } else if (NumBytes >= 3 * 16) {
9394       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9395       // separate instructions that make it harder to use a non-constant update.
9396       continue;
9397     }
9398
9399     // Create the new updating load/store node.
9400     EVT Tys[6];
9401     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
9402     unsigned n;
9403     for (n = 0; n < NumResultVecs; ++n)
9404       Tys[n] = VecTy;
9405     Tys[n++] = MVT::i32;
9406     Tys[n] = MVT::Other;
9407     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
9408     SmallVector<SDValue, 8> Ops;
9409     Ops.push_back(N->getOperand(0)); // incoming chain
9410     Ops.push_back(N->getOperand(AddrOpIdx));
9411     Ops.push_back(Inc);
9412     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
9413       Ops.push_back(N->getOperand(i));
9414     }
9415     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9416     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9417                                            Ops.data(), Ops.size(),
9418                                            MemInt->getMemoryVT(),
9419                                            MemInt->getMemOperand());
9420
9421     // Update the uses.
9422     std::vector<SDValue> NewResults;
9423     for (unsigned i = 0; i < NumResultVecs; ++i) {
9424       NewResults.push_back(SDValue(UpdN.getNode(), i));
9425     }
9426     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9427     DCI.CombineTo(N, NewResults);
9428     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9429
9430     break;
9431   }
9432   return SDValue();
9433 }
9434
9435 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9436 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9437 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9438 /// return true.
9439 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9440   SelectionDAG &DAG = DCI.DAG;
9441   EVT VT = N->getValueType(0);
9442   // vldN-dup instructions only support 64-bit vectors for N > 1.
9443   if (!VT.is64BitVector())
9444     return false;
9445
9446   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9447   SDNode *VLD = N->getOperand(0).getNode();
9448   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9449     return false;
9450   unsigned NumVecs = 0;
9451   unsigned NewOpc = 0;
9452   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9453   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9454     NumVecs = 2;
9455     NewOpc = ARMISD::VLD2DUP;
9456   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9457     NumVecs = 3;
9458     NewOpc = ARMISD::VLD3DUP;
9459   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9460     NumVecs = 4;
9461     NewOpc = ARMISD::VLD4DUP;
9462   } else {
9463     return false;
9464   }
9465
9466   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9467   // numbers match the load.
9468   unsigned VLDLaneNo =
9469     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9470   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9471        UI != UE; ++UI) {
9472     // Ignore uses of the chain result.
9473     if (UI.getUse().getResNo() == NumVecs)
9474       continue;
9475     SDNode *User = *UI;
9476     if (User->getOpcode() != ARMISD::VDUPLANE ||
9477         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9478       return false;
9479   }
9480
9481   // Create the vldN-dup node.
9482   EVT Tys[5];
9483   unsigned n;
9484   for (n = 0; n < NumVecs; ++n)
9485     Tys[n] = VT;
9486   Tys[n] = MVT::Other;
9487   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
9488   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9489   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9490   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9491                                            Ops, 2, VLDMemInt->getMemoryVT(),
9492                                            VLDMemInt->getMemOperand());
9493
9494   // Update the uses.
9495   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9496        UI != UE; ++UI) {
9497     unsigned ResNo = UI.getUse().getResNo();
9498     // Ignore uses of the chain result.
9499     if (ResNo == NumVecs)
9500       continue;
9501     SDNode *User = *UI;
9502     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9503   }
9504
9505   // Now the vldN-lane intrinsic is dead except for its chain result.
9506   // Update uses of the chain.
9507   std::vector<SDValue> VLDDupResults;
9508   for (unsigned n = 0; n < NumVecs; ++n)
9509     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9510   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9511   DCI.CombineTo(VLD, VLDDupResults);
9512
9513   return true;
9514 }
9515
9516 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9517 /// ARMISD::VDUPLANE.
9518 static SDValue PerformVDUPLANECombine(SDNode *N,
9519                                       TargetLowering::DAGCombinerInfo &DCI) {
9520   SDValue Op = N->getOperand(0);
9521
9522   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9523   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9524   if (CombineVLDDUP(N, DCI))
9525     return SDValue(N, 0);
9526
9527   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9528   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9529   while (Op.getOpcode() == ISD::BITCAST)
9530     Op = Op.getOperand(0);
9531   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9532     return SDValue();
9533
9534   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9535   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9536   // The canonical VMOV for a zero vector uses a 32-bit element size.
9537   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9538   unsigned EltBits;
9539   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9540     EltSize = 8;
9541   EVT VT = N->getValueType(0);
9542   if (EltSize > VT.getVectorElementType().getSizeInBits())
9543     return SDValue();
9544
9545   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9546 }
9547
9548 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9549 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9550 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9551 {
9552   integerPart cN;
9553   integerPart c0 = 0;
9554   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9555        I != E; I++) {
9556     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9557     if (!C)
9558       return false;
9559
9560     bool isExact;
9561     APFloat APF = C->getValueAPF();
9562     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9563         != APFloat::opOK || !isExact)
9564       return false;
9565
9566     c0 = (I == 0) ? cN : c0;
9567     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9568       return false;
9569   }
9570   C = c0;
9571   return true;
9572 }
9573
9574 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9575 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9576 /// when the VMUL has a constant operand that is a power of 2.
9577 ///
9578 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9579 ///  vmul.f32        d16, d17, d16
9580 ///  vcvt.s32.f32    d16, d16
9581 /// becomes:
9582 ///  vcvt.s32.f32    d16, d16, #3
9583 static SDValue PerformVCVTCombine(SDNode *N,
9584                                   TargetLowering::DAGCombinerInfo &DCI,
9585                                   const ARMSubtarget *Subtarget) {
9586   SelectionDAG &DAG = DCI.DAG;
9587   SDValue Op = N->getOperand(0);
9588
9589   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9590       Op.getOpcode() != ISD::FMUL)
9591     return SDValue();
9592
9593   uint64_t C;
9594   SDValue N0 = Op->getOperand(0);
9595   SDValue ConstVec = Op->getOperand(1);
9596   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9597
9598   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9599       !isConstVecPow2(ConstVec, isSigned, C))
9600     return SDValue();
9601
9602   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9603   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9604   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9605     // These instructions only exist converting from f32 to i32. We can handle
9606     // smaller integers by generating an extra truncate, but larger ones would
9607     // be lossy.
9608     return SDValue();
9609   }
9610
9611   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9612     Intrinsic::arm_neon_vcvtfp2fxu;
9613   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9614   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9615                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9616                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9617                                  DAG.getConstant(Log2_64(C), MVT::i32));
9618
9619   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9620     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9621
9622   return FixConv;
9623 }
9624
9625 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9626 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9627 /// when the VDIV has a constant operand that is a power of 2.
9628 ///
9629 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9630 ///  vcvt.f32.s32    d16, d16
9631 ///  vdiv.f32        d16, d17, d16
9632 /// becomes:
9633 ///  vcvt.f32.s32    d16, d16, #3
9634 static SDValue PerformVDIVCombine(SDNode *N,
9635                                   TargetLowering::DAGCombinerInfo &DCI,
9636                                   const ARMSubtarget *Subtarget) {
9637   SelectionDAG &DAG = DCI.DAG;
9638   SDValue Op = N->getOperand(0);
9639   unsigned OpOpcode = Op.getNode()->getOpcode();
9640
9641   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9642       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9643     return SDValue();
9644
9645   uint64_t C;
9646   SDValue ConstVec = N->getOperand(1);
9647   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9648
9649   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9650       !isConstVecPow2(ConstVec, isSigned, C))
9651     return SDValue();
9652
9653   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9654   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9655   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9656     // These instructions only exist converting from i32 to f32. We can handle
9657     // smaller integers by generating an extra extend, but larger ones would
9658     // be lossy.
9659     return SDValue();
9660   }
9661
9662   SDValue ConvInput = Op.getOperand(0);
9663   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9664   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9665     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9666                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9667                             ConvInput);
9668
9669   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9670     Intrinsic::arm_neon_vcvtfxu2fp;
9671   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9672                      Op.getValueType(),
9673                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9674                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9675 }
9676
9677 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9678 /// operand of a vector shift operation, where all the elements of the
9679 /// build_vector must have the same constant integer value.
9680 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9681   // Ignore bit_converts.
9682   while (Op.getOpcode() == ISD::BITCAST)
9683     Op = Op.getOperand(0);
9684   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9685   APInt SplatBits, SplatUndef;
9686   unsigned SplatBitSize;
9687   bool HasAnyUndefs;
9688   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9689                                       HasAnyUndefs, ElementBits) ||
9690       SplatBitSize > ElementBits)
9691     return false;
9692   Cnt = SplatBits.getSExtValue();
9693   return true;
9694 }
9695
9696 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9697 /// operand of a vector shift left operation.  That value must be in the range:
9698 ///   0 <= Value < ElementBits for a left shift; or
9699 ///   0 <= Value <= ElementBits for a long left shift.
9700 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9701   assert(VT.isVector() && "vector shift count is not a vector type");
9702   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9703   if (! getVShiftImm(Op, ElementBits, Cnt))
9704     return false;
9705   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9706 }
9707
9708 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9709 /// operand of a vector shift right operation.  For a shift opcode, the value
9710 /// is positive, but for an intrinsic the value count must be negative. The
9711 /// absolute value must be in the range:
9712 ///   1 <= |Value| <= ElementBits for a right shift; or
9713 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9714 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9715                          int64_t &Cnt) {
9716   assert(VT.isVector() && "vector shift count is not a vector type");
9717   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9718   if (! getVShiftImm(Op, ElementBits, Cnt))
9719     return false;
9720   if (isIntrinsic)
9721     Cnt = -Cnt;
9722   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9723 }
9724
9725 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9726 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9727   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9728   switch (IntNo) {
9729   default:
9730     // Don't do anything for most intrinsics.
9731     break;
9732
9733   // Vector shifts: check for immediate versions and lower them.
9734   // Note: This is done during DAG combining instead of DAG legalizing because
9735   // the build_vectors for 64-bit vector element shift counts are generally
9736   // not legal, and it is hard to see their values after they get legalized to
9737   // loads from a constant pool.
9738   case Intrinsic::arm_neon_vshifts:
9739   case Intrinsic::arm_neon_vshiftu:
9740   case Intrinsic::arm_neon_vrshifts:
9741   case Intrinsic::arm_neon_vrshiftu:
9742   case Intrinsic::arm_neon_vrshiftn:
9743   case Intrinsic::arm_neon_vqshifts:
9744   case Intrinsic::arm_neon_vqshiftu:
9745   case Intrinsic::arm_neon_vqshiftsu:
9746   case Intrinsic::arm_neon_vqshiftns:
9747   case Intrinsic::arm_neon_vqshiftnu:
9748   case Intrinsic::arm_neon_vqshiftnsu:
9749   case Intrinsic::arm_neon_vqrshiftns:
9750   case Intrinsic::arm_neon_vqrshiftnu:
9751   case Intrinsic::arm_neon_vqrshiftnsu: {
9752     EVT VT = N->getOperand(1).getValueType();
9753     int64_t Cnt;
9754     unsigned VShiftOpc = 0;
9755
9756     switch (IntNo) {
9757     case Intrinsic::arm_neon_vshifts:
9758     case Intrinsic::arm_neon_vshiftu:
9759       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9760         VShiftOpc = ARMISD::VSHL;
9761         break;
9762       }
9763       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9764         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9765                      ARMISD::VSHRs : ARMISD::VSHRu);
9766         break;
9767       }
9768       return SDValue();
9769
9770     case Intrinsic::arm_neon_vrshifts:
9771     case Intrinsic::arm_neon_vrshiftu:
9772       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9773         break;
9774       return SDValue();
9775
9776     case Intrinsic::arm_neon_vqshifts:
9777     case Intrinsic::arm_neon_vqshiftu:
9778       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9779         break;
9780       return SDValue();
9781
9782     case Intrinsic::arm_neon_vqshiftsu:
9783       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9784         break;
9785       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9786
9787     case Intrinsic::arm_neon_vrshiftn:
9788     case Intrinsic::arm_neon_vqshiftns:
9789     case Intrinsic::arm_neon_vqshiftnu:
9790     case Intrinsic::arm_neon_vqshiftnsu:
9791     case Intrinsic::arm_neon_vqrshiftns:
9792     case Intrinsic::arm_neon_vqrshiftnu:
9793     case Intrinsic::arm_neon_vqrshiftnsu:
9794       // Narrowing shifts require an immediate right shift.
9795       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9796         break;
9797       llvm_unreachable("invalid shift count for narrowing vector shift "
9798                        "intrinsic");
9799
9800     default:
9801       llvm_unreachable("unhandled vector shift");
9802     }
9803
9804     switch (IntNo) {
9805     case Intrinsic::arm_neon_vshifts:
9806     case Intrinsic::arm_neon_vshiftu:
9807       // Opcode already set above.
9808       break;
9809     case Intrinsic::arm_neon_vrshifts:
9810       VShiftOpc = ARMISD::VRSHRs; break;
9811     case Intrinsic::arm_neon_vrshiftu:
9812       VShiftOpc = ARMISD::VRSHRu; break;
9813     case Intrinsic::arm_neon_vrshiftn:
9814       VShiftOpc = ARMISD::VRSHRN; break;
9815     case Intrinsic::arm_neon_vqshifts:
9816       VShiftOpc = ARMISD::VQSHLs; break;
9817     case Intrinsic::arm_neon_vqshiftu:
9818       VShiftOpc = ARMISD::VQSHLu; break;
9819     case Intrinsic::arm_neon_vqshiftsu:
9820       VShiftOpc = ARMISD::VQSHLsu; break;
9821     case Intrinsic::arm_neon_vqshiftns:
9822       VShiftOpc = ARMISD::VQSHRNs; break;
9823     case Intrinsic::arm_neon_vqshiftnu:
9824       VShiftOpc = ARMISD::VQSHRNu; break;
9825     case Intrinsic::arm_neon_vqshiftnsu:
9826       VShiftOpc = ARMISD::VQSHRNsu; break;
9827     case Intrinsic::arm_neon_vqrshiftns:
9828       VShiftOpc = ARMISD::VQRSHRNs; break;
9829     case Intrinsic::arm_neon_vqrshiftnu:
9830       VShiftOpc = ARMISD::VQRSHRNu; break;
9831     case Intrinsic::arm_neon_vqrshiftnsu:
9832       VShiftOpc = ARMISD::VQRSHRNsu; break;
9833     }
9834
9835     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9836                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9837   }
9838
9839   case Intrinsic::arm_neon_vshiftins: {
9840     EVT VT = N->getOperand(1).getValueType();
9841     int64_t Cnt;
9842     unsigned VShiftOpc = 0;
9843
9844     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9845       VShiftOpc = ARMISD::VSLI;
9846     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9847       VShiftOpc = ARMISD::VSRI;
9848     else {
9849       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9850     }
9851
9852     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9853                        N->getOperand(1), N->getOperand(2),
9854                        DAG.getConstant(Cnt, MVT::i32));
9855   }
9856
9857   case Intrinsic::arm_neon_vqrshifts:
9858   case Intrinsic::arm_neon_vqrshiftu:
9859     // No immediate versions of these to check for.
9860     break;
9861   }
9862
9863   return SDValue();
9864 }
9865
9866 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9867 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9868 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9869 /// vector element shift counts are generally not legal, and it is hard to see
9870 /// their values after they get legalized to loads from a constant pool.
9871 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9872                                    const ARMSubtarget *ST) {
9873   EVT VT = N->getValueType(0);
9874   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9875     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9876     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9877     SDValue N1 = N->getOperand(1);
9878     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9879       SDValue N0 = N->getOperand(0);
9880       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9881           DAG.MaskedValueIsZero(N0.getOperand(0),
9882                                 APInt::getHighBitsSet(32, 16)))
9883         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9884     }
9885   }
9886
9887   // Nothing to be done for scalar shifts.
9888   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9889   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9890     return SDValue();
9891
9892   assert(ST->hasNEON() && "unexpected vector shift");
9893   int64_t Cnt;
9894
9895   switch (N->getOpcode()) {
9896   default: llvm_unreachable("unexpected shift opcode");
9897
9898   case ISD::SHL:
9899     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9900       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9901                          DAG.getConstant(Cnt, MVT::i32));
9902     break;
9903
9904   case ISD::SRA:
9905   case ISD::SRL:
9906     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9907       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9908                             ARMISD::VSHRs : ARMISD::VSHRu);
9909       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9910                          DAG.getConstant(Cnt, MVT::i32));
9911     }
9912   }
9913   return SDValue();
9914 }
9915
9916 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9917 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9918 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9919                                     const ARMSubtarget *ST) {
9920   SDValue N0 = N->getOperand(0);
9921
9922   // Check for sign- and zero-extensions of vector extract operations of 8-
9923   // and 16-bit vector elements.  NEON supports these directly.  They are
9924   // handled during DAG combining because type legalization will promote them
9925   // to 32-bit types and it is messy to recognize the operations after that.
9926   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9927     SDValue Vec = N0.getOperand(0);
9928     SDValue Lane = N0.getOperand(1);
9929     EVT VT = N->getValueType(0);
9930     EVT EltVT = N0.getValueType();
9931     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9932
9933     if (VT == MVT::i32 &&
9934         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9935         TLI.isTypeLegal(Vec.getValueType()) &&
9936         isa<ConstantSDNode>(Lane)) {
9937
9938       unsigned Opc = 0;
9939       switch (N->getOpcode()) {
9940       default: llvm_unreachable("unexpected opcode");
9941       case ISD::SIGN_EXTEND:
9942         Opc = ARMISD::VGETLANEs;
9943         break;
9944       case ISD::ZERO_EXTEND:
9945       case ISD::ANY_EXTEND:
9946         Opc = ARMISD::VGETLANEu;
9947         break;
9948       }
9949       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9950     }
9951   }
9952
9953   return SDValue();
9954 }
9955
9956 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9957 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9958 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9959                                        const ARMSubtarget *ST) {
9960   // If the target supports NEON, try to use vmax/vmin instructions for f32
9961   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9962   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9963   // a NaN; only do the transformation when it matches that behavior.
9964
9965   // For now only do this when using NEON for FP operations; if using VFP, it
9966   // is not obvious that the benefit outweighs the cost of switching to the
9967   // NEON pipeline.
9968   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9969       N->getValueType(0) != MVT::f32)
9970     return SDValue();
9971
9972   SDValue CondLHS = N->getOperand(0);
9973   SDValue CondRHS = N->getOperand(1);
9974   SDValue LHS = N->getOperand(2);
9975   SDValue RHS = N->getOperand(3);
9976   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9977
9978   unsigned Opcode = 0;
9979   bool IsReversed;
9980   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9981     IsReversed = false; // x CC y ? x : y
9982   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9983     IsReversed = true ; // x CC y ? y : x
9984   } else {
9985     return SDValue();
9986   }
9987
9988   bool IsUnordered;
9989   switch (CC) {
9990   default: break;
9991   case ISD::SETOLT:
9992   case ISD::SETOLE:
9993   case ISD::SETLT:
9994   case ISD::SETLE:
9995   case ISD::SETULT:
9996   case ISD::SETULE:
9997     // If LHS is NaN, an ordered comparison will be false and the result will
9998     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9999     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
10000     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
10001     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10002       break;
10003     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
10004     // will return -0, so vmin can only be used for unsafe math or if one of
10005     // the operands is known to be nonzero.
10006     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
10007         !DAG.getTarget().Options.UnsafeFPMath &&
10008         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10009       break;
10010     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
10011     break;
10012
10013   case ISD::SETOGT:
10014   case ISD::SETOGE:
10015   case ISD::SETGT:
10016   case ISD::SETGE:
10017   case ISD::SETUGT:
10018   case ISD::SETUGE:
10019     // If LHS is NaN, an ordered comparison will be false and the result will
10020     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
10021     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
10022     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
10023     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10024       break;
10025     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
10026     // will return +0, so vmax can only be used for unsafe math or if one of
10027     // the operands is known to be nonzero.
10028     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
10029         !DAG.getTarget().Options.UnsafeFPMath &&
10030         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10031       break;
10032     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
10033     break;
10034   }
10035
10036   if (!Opcode)
10037     return SDValue();
10038   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
10039 }
10040
10041 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10042 SDValue
10043 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10044   SDValue Cmp = N->getOperand(4);
10045   if (Cmp.getOpcode() != ARMISD::CMPZ)
10046     // Only looking at EQ and NE cases.
10047     return SDValue();
10048
10049   EVT VT = N->getValueType(0);
10050   SDLoc dl(N);
10051   SDValue LHS = Cmp.getOperand(0);
10052   SDValue RHS = Cmp.getOperand(1);
10053   SDValue FalseVal = N->getOperand(0);
10054   SDValue TrueVal = N->getOperand(1);
10055   SDValue ARMcc = N->getOperand(2);
10056   ARMCC::CondCodes CC =
10057     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10058
10059   // Simplify
10060   //   mov     r1, r0
10061   //   cmp     r1, x
10062   //   mov     r0, y
10063   //   moveq   r0, x
10064   // to
10065   //   cmp     r0, x
10066   //   movne   r0, y
10067   //
10068   //   mov     r1, r0
10069   //   cmp     r1, x
10070   //   mov     r0, x
10071   //   movne   r0, y
10072   // to
10073   //   cmp     r0, x
10074   //   movne   r0, y
10075   /// FIXME: Turn this into a target neutral optimization?
10076   SDValue Res;
10077   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10078     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10079                       N->getOperand(3), Cmp);
10080   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10081     SDValue ARMcc;
10082     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10083     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10084                       N->getOperand(3), NewCmp);
10085   }
10086
10087   if (Res.getNode()) {
10088     APInt KnownZero, KnownOne;
10089     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
10090     // Capture demanded bits information that would be otherwise lost.
10091     if (KnownZero == 0xfffffffe)
10092       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10093                         DAG.getValueType(MVT::i1));
10094     else if (KnownZero == 0xffffff00)
10095       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10096                         DAG.getValueType(MVT::i8));
10097     else if (KnownZero == 0xffff0000)
10098       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10099                         DAG.getValueType(MVT::i16));
10100   }
10101
10102   return Res;
10103 }
10104
10105 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10106                                              DAGCombinerInfo &DCI) const {
10107   switch (N->getOpcode()) {
10108   default: break;
10109   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
10110   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
10111   case ISD::SUB:        return PerformSUBCombine(N, DCI);
10112   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
10113   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
10114   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
10115   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
10116   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
10117   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
10118   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10119   case ISD::STORE:      return PerformSTORECombine(N, DCI);
10120   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
10121   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10122   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10123   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10124   case ISD::FP_TO_SINT:
10125   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10126   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
10127   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10128   case ISD::SHL:
10129   case ISD::SRA:
10130   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10131   case ISD::SIGN_EXTEND:
10132   case ISD::ZERO_EXTEND:
10133   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10134   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
10135   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10136   case ARMISD::VLD2DUP:
10137   case ARMISD::VLD3DUP:
10138   case ARMISD::VLD4DUP:
10139     return CombineBaseUpdate(N, DCI);
10140   case ARMISD::BUILD_VECTOR:
10141     return PerformARMBUILD_VECTORCombine(N, DCI);
10142   case ISD::INTRINSIC_VOID:
10143   case ISD::INTRINSIC_W_CHAIN:
10144     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10145     case Intrinsic::arm_neon_vld1:
10146     case Intrinsic::arm_neon_vld2:
10147     case Intrinsic::arm_neon_vld3:
10148     case Intrinsic::arm_neon_vld4:
10149     case Intrinsic::arm_neon_vld2lane:
10150     case Intrinsic::arm_neon_vld3lane:
10151     case Intrinsic::arm_neon_vld4lane:
10152     case Intrinsic::arm_neon_vst1:
10153     case Intrinsic::arm_neon_vst2:
10154     case Intrinsic::arm_neon_vst3:
10155     case Intrinsic::arm_neon_vst4:
10156     case Intrinsic::arm_neon_vst2lane:
10157     case Intrinsic::arm_neon_vst3lane:
10158     case Intrinsic::arm_neon_vst4lane:
10159       return CombineBaseUpdate(N, DCI);
10160     default: break;
10161     }
10162     break;
10163   }
10164   return SDValue();
10165 }
10166
10167 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10168                                                           EVT VT) const {
10169   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10170 }
10171
10172 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, unsigned,
10173                                                       bool *Fast) const {
10174   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10175   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10176
10177   switch (VT.getSimpleVT().SimpleTy) {
10178   default:
10179     return false;
10180   case MVT::i8:
10181   case MVT::i16:
10182   case MVT::i32: {
10183     // Unaligned access can use (for example) LRDB, LRDH, LDR
10184     if (AllowsUnaligned) {
10185       if (Fast)
10186         *Fast = Subtarget->hasV7Ops();
10187       return true;
10188     }
10189     return false;
10190   }
10191   case MVT::f64:
10192   case MVT::v2f64: {
10193     // For any little-endian targets with neon, we can support unaligned ld/st
10194     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10195     // A big-endian target may also explicitly support unaligned accesses
10196     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
10197       if (Fast)
10198         *Fast = true;
10199       return true;
10200     }
10201     return false;
10202   }
10203   }
10204 }
10205
10206 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10207                        unsigned AlignCheck) {
10208   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10209           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10210 }
10211
10212 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10213                                            unsigned DstAlign, unsigned SrcAlign,
10214                                            bool IsMemset, bool ZeroMemset,
10215                                            bool MemcpyStrSrc,
10216                                            MachineFunction &MF) const {
10217   const Function *F = MF.getFunction();
10218
10219   // See if we can use NEON instructions for this...
10220   if ((!IsMemset || ZeroMemset) &&
10221       Subtarget->hasNEON() &&
10222       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
10223                                        Attribute::NoImplicitFloat)) {
10224     bool Fast;
10225     if (Size >= 16 &&
10226         (memOpAlign(SrcAlign, DstAlign, 16) ||
10227          (allowsUnalignedMemoryAccesses(MVT::v2f64, 0, &Fast) && Fast))) {
10228       return MVT::v2f64;
10229     } else if (Size >= 8 &&
10230                (memOpAlign(SrcAlign, DstAlign, 8) ||
10231                 (allowsUnalignedMemoryAccesses(MVT::f64, 0, &Fast) && Fast))) {
10232       return MVT::f64;
10233     }
10234   }
10235
10236   // Lowering to i32/i16 if the size permits.
10237   if (Size >= 4)
10238     return MVT::i32;
10239   else if (Size >= 2)
10240     return MVT::i16;
10241
10242   // Let the target-independent logic figure it out.
10243   return MVT::Other;
10244 }
10245
10246 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10247   if (Val.getOpcode() != ISD::LOAD)
10248     return false;
10249
10250   EVT VT1 = Val.getValueType();
10251   if (!VT1.isSimple() || !VT1.isInteger() ||
10252       !VT2.isSimple() || !VT2.isInteger())
10253     return false;
10254
10255   switch (VT1.getSimpleVT().SimpleTy) {
10256   default: break;
10257   case MVT::i1:
10258   case MVT::i8:
10259   case MVT::i16:
10260     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10261     return true;
10262   }
10263
10264   return false;
10265 }
10266
10267 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10268   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10269     return false;
10270
10271   if (!isTypeLegal(EVT::getEVT(Ty1)))
10272     return false;
10273
10274   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10275
10276   // Assuming the caller doesn't have a zeroext or signext return parameter,
10277   // truncation all the way down to i1 is valid.
10278   return true;
10279 }
10280
10281
10282 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10283   if (V < 0)
10284     return false;
10285
10286   unsigned Scale = 1;
10287   switch (VT.getSimpleVT().SimpleTy) {
10288   default: return false;
10289   case MVT::i1:
10290   case MVT::i8:
10291     // Scale == 1;
10292     break;
10293   case MVT::i16:
10294     // Scale == 2;
10295     Scale = 2;
10296     break;
10297   case MVT::i32:
10298     // Scale == 4;
10299     Scale = 4;
10300     break;
10301   }
10302
10303   if ((V & (Scale - 1)) != 0)
10304     return false;
10305   V /= Scale;
10306   return V == (V & ((1LL << 5) - 1));
10307 }
10308
10309 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10310                                       const ARMSubtarget *Subtarget) {
10311   bool isNeg = false;
10312   if (V < 0) {
10313     isNeg = true;
10314     V = - V;
10315   }
10316
10317   switch (VT.getSimpleVT().SimpleTy) {
10318   default: return false;
10319   case MVT::i1:
10320   case MVT::i8:
10321   case MVT::i16:
10322   case MVT::i32:
10323     // + imm12 or - imm8
10324     if (isNeg)
10325       return V == (V & ((1LL << 8) - 1));
10326     return V == (V & ((1LL << 12) - 1));
10327   case MVT::f32:
10328   case MVT::f64:
10329     // Same as ARM mode. FIXME: NEON?
10330     if (!Subtarget->hasVFP2())
10331       return false;
10332     if ((V & 3) != 0)
10333       return false;
10334     V >>= 2;
10335     return V == (V & ((1LL << 8) - 1));
10336   }
10337 }
10338
10339 /// isLegalAddressImmediate - Return true if the integer value can be used
10340 /// as the offset of the target addressing mode for load / store of the
10341 /// given type.
10342 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10343                                     const ARMSubtarget *Subtarget) {
10344   if (V == 0)
10345     return true;
10346
10347   if (!VT.isSimple())
10348     return false;
10349
10350   if (Subtarget->isThumb1Only())
10351     return isLegalT1AddressImmediate(V, VT);
10352   else if (Subtarget->isThumb2())
10353     return isLegalT2AddressImmediate(V, VT, Subtarget);
10354
10355   // ARM mode.
10356   if (V < 0)
10357     V = - V;
10358   switch (VT.getSimpleVT().SimpleTy) {
10359   default: return false;
10360   case MVT::i1:
10361   case MVT::i8:
10362   case MVT::i32:
10363     // +- imm12
10364     return V == (V & ((1LL << 12) - 1));
10365   case MVT::i16:
10366     // +- imm8
10367     return V == (V & ((1LL << 8) - 1));
10368   case MVT::f32:
10369   case MVT::f64:
10370     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10371       return false;
10372     if ((V & 3) != 0)
10373       return false;
10374     V >>= 2;
10375     return V == (V & ((1LL << 8) - 1));
10376   }
10377 }
10378
10379 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10380                                                       EVT VT) const {
10381   int Scale = AM.Scale;
10382   if (Scale < 0)
10383     return false;
10384
10385   switch (VT.getSimpleVT().SimpleTy) {
10386   default: return false;
10387   case MVT::i1:
10388   case MVT::i8:
10389   case MVT::i16:
10390   case MVT::i32:
10391     if (Scale == 1)
10392       return true;
10393     // r + r << imm
10394     Scale = Scale & ~1;
10395     return Scale == 2 || Scale == 4 || Scale == 8;
10396   case MVT::i64:
10397     // r + r
10398     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10399       return true;
10400     return false;
10401   case MVT::isVoid:
10402     // Note, we allow "void" uses (basically, uses that aren't loads or
10403     // stores), because arm allows folding a scale into many arithmetic
10404     // operations.  This should be made more precise and revisited later.
10405
10406     // Allow r << imm, but the imm has to be a multiple of two.
10407     if (Scale & 1) return false;
10408     return isPowerOf2_32(Scale);
10409   }
10410 }
10411
10412 /// isLegalAddressingMode - Return true if the addressing mode represented
10413 /// by AM is legal for this target, for a load/store of the specified type.
10414 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10415                                               Type *Ty) const {
10416   EVT VT = getValueType(Ty, true);
10417   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10418     return false;
10419
10420   // Can never fold addr of global into load/store.
10421   if (AM.BaseGV)
10422     return false;
10423
10424   switch (AM.Scale) {
10425   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10426     break;
10427   case 1:
10428     if (Subtarget->isThumb1Only())
10429       return false;
10430     // FALL THROUGH.
10431   default:
10432     // ARM doesn't support any R+R*scale+imm addr modes.
10433     if (AM.BaseOffs)
10434       return false;
10435
10436     if (!VT.isSimple())
10437       return false;
10438
10439     if (Subtarget->isThumb2())
10440       return isLegalT2ScaledAddressingMode(AM, VT);
10441
10442     int Scale = AM.Scale;
10443     switch (VT.getSimpleVT().SimpleTy) {
10444     default: return false;
10445     case MVT::i1:
10446     case MVT::i8:
10447     case MVT::i32:
10448       if (Scale < 0) Scale = -Scale;
10449       if (Scale == 1)
10450         return true;
10451       // r + r << imm
10452       return isPowerOf2_32(Scale & ~1);
10453     case MVT::i16:
10454     case MVT::i64:
10455       // r + r
10456       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10457         return true;
10458       return false;
10459
10460     case MVT::isVoid:
10461       // Note, we allow "void" uses (basically, uses that aren't loads or
10462       // stores), because arm allows folding a scale into many arithmetic
10463       // operations.  This should be made more precise and revisited later.
10464
10465       // Allow r << imm, but the imm has to be a multiple of two.
10466       if (Scale & 1) return false;
10467       return isPowerOf2_32(Scale);
10468     }
10469   }
10470   return true;
10471 }
10472
10473 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10474 /// icmp immediate, that is the target has icmp instructions which can compare
10475 /// a register against the immediate without having to materialize the
10476 /// immediate into a register.
10477 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10478   // Thumb2 and ARM modes can use cmn for negative immediates.
10479   if (!Subtarget->isThumb())
10480     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10481   if (Subtarget->isThumb2())
10482     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10483   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10484   return Imm >= 0 && Imm <= 255;
10485 }
10486
10487 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10488 /// *or sub* immediate, that is the target has add or sub instructions which can
10489 /// add a register with the immediate without having to materialize the
10490 /// immediate into a register.
10491 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10492   // Same encoding for add/sub, just flip the sign.
10493   int64_t AbsImm = llvm::abs64(Imm);
10494   if (!Subtarget->isThumb())
10495     return ARM_AM::getSOImmVal(AbsImm) != -1;
10496   if (Subtarget->isThumb2())
10497     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10498   // Thumb1 only has 8-bit unsigned immediate.
10499   return AbsImm >= 0 && AbsImm <= 255;
10500 }
10501
10502 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10503                                       bool isSEXTLoad, SDValue &Base,
10504                                       SDValue &Offset, bool &isInc,
10505                                       SelectionDAG &DAG) {
10506   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10507     return false;
10508
10509   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10510     // AddressingMode 3
10511     Base = Ptr->getOperand(0);
10512     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10513       int RHSC = (int)RHS->getZExtValue();
10514       if (RHSC < 0 && RHSC > -256) {
10515         assert(Ptr->getOpcode() == ISD::ADD);
10516         isInc = false;
10517         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10518         return true;
10519       }
10520     }
10521     isInc = (Ptr->getOpcode() == ISD::ADD);
10522     Offset = Ptr->getOperand(1);
10523     return true;
10524   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10525     // AddressingMode 2
10526     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10527       int RHSC = (int)RHS->getZExtValue();
10528       if (RHSC < 0 && RHSC > -0x1000) {
10529         assert(Ptr->getOpcode() == ISD::ADD);
10530         isInc = false;
10531         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10532         Base = Ptr->getOperand(0);
10533         return true;
10534       }
10535     }
10536
10537     if (Ptr->getOpcode() == ISD::ADD) {
10538       isInc = true;
10539       ARM_AM::ShiftOpc ShOpcVal=
10540         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10541       if (ShOpcVal != ARM_AM::no_shift) {
10542         Base = Ptr->getOperand(1);
10543         Offset = Ptr->getOperand(0);
10544       } else {
10545         Base = Ptr->getOperand(0);
10546         Offset = Ptr->getOperand(1);
10547       }
10548       return true;
10549     }
10550
10551     isInc = (Ptr->getOpcode() == ISD::ADD);
10552     Base = Ptr->getOperand(0);
10553     Offset = Ptr->getOperand(1);
10554     return true;
10555   }
10556
10557   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10558   return false;
10559 }
10560
10561 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10562                                      bool isSEXTLoad, SDValue &Base,
10563                                      SDValue &Offset, bool &isInc,
10564                                      SelectionDAG &DAG) {
10565   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10566     return false;
10567
10568   Base = Ptr->getOperand(0);
10569   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10570     int RHSC = (int)RHS->getZExtValue();
10571     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10572       assert(Ptr->getOpcode() == ISD::ADD);
10573       isInc = false;
10574       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10575       return true;
10576     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10577       isInc = Ptr->getOpcode() == ISD::ADD;
10578       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10579       return true;
10580     }
10581   }
10582
10583   return false;
10584 }
10585
10586 /// getPreIndexedAddressParts - returns true by value, base pointer and
10587 /// offset pointer and addressing mode by reference if the node's address
10588 /// can be legally represented as pre-indexed load / store address.
10589 bool
10590 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10591                                              SDValue &Offset,
10592                                              ISD::MemIndexedMode &AM,
10593                                              SelectionDAG &DAG) const {
10594   if (Subtarget->isThumb1Only())
10595     return false;
10596
10597   EVT VT;
10598   SDValue Ptr;
10599   bool isSEXTLoad = false;
10600   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10601     Ptr = LD->getBasePtr();
10602     VT  = LD->getMemoryVT();
10603     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10604   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10605     Ptr = ST->getBasePtr();
10606     VT  = ST->getMemoryVT();
10607   } else
10608     return false;
10609
10610   bool isInc;
10611   bool isLegal = false;
10612   if (Subtarget->isThumb2())
10613     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10614                                        Offset, isInc, DAG);
10615   else
10616     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10617                                         Offset, isInc, DAG);
10618   if (!isLegal)
10619     return false;
10620
10621   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10622   return true;
10623 }
10624
10625 /// getPostIndexedAddressParts - returns true by value, base pointer and
10626 /// offset pointer and addressing mode by reference if this node can be
10627 /// combined with a load / store to form a post-indexed load / store.
10628 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10629                                                    SDValue &Base,
10630                                                    SDValue &Offset,
10631                                                    ISD::MemIndexedMode &AM,
10632                                                    SelectionDAG &DAG) const {
10633   if (Subtarget->isThumb1Only())
10634     return false;
10635
10636   EVT VT;
10637   SDValue Ptr;
10638   bool isSEXTLoad = false;
10639   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10640     VT  = LD->getMemoryVT();
10641     Ptr = LD->getBasePtr();
10642     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10643   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10644     VT  = ST->getMemoryVT();
10645     Ptr = ST->getBasePtr();
10646   } else
10647     return false;
10648
10649   bool isInc;
10650   bool isLegal = false;
10651   if (Subtarget->isThumb2())
10652     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10653                                        isInc, DAG);
10654   else
10655     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10656                                         isInc, DAG);
10657   if (!isLegal)
10658     return false;
10659
10660   if (Ptr != Base) {
10661     // Swap base ptr and offset to catch more post-index load / store when
10662     // it's legal. In Thumb2 mode, offset must be an immediate.
10663     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10664         !Subtarget->isThumb2())
10665       std::swap(Base, Offset);
10666
10667     // Post-indexed load / store update the base pointer.
10668     if (Ptr != Base)
10669       return false;
10670   }
10671
10672   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10673   return true;
10674 }
10675
10676 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10677                                                        APInt &KnownZero,
10678                                                        APInt &KnownOne,
10679                                                        const SelectionDAG &DAG,
10680                                                        unsigned Depth) const {
10681   unsigned BitWidth = KnownOne.getBitWidth();
10682   KnownZero = KnownOne = APInt(BitWidth, 0);
10683   switch (Op.getOpcode()) {
10684   default: break;
10685   case ARMISD::ADDC:
10686   case ARMISD::ADDE:
10687   case ARMISD::SUBC:
10688   case ARMISD::SUBE:
10689     // These nodes' second result is a boolean
10690     if (Op.getResNo() == 0)
10691       break;
10692     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10693     break;
10694   case ARMISD::CMOV: {
10695     // Bits are known zero/one if known on the LHS and RHS.
10696     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10697     if (KnownZero == 0 && KnownOne == 0) return;
10698
10699     APInt KnownZeroRHS, KnownOneRHS;
10700     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10701     KnownZero &= KnownZeroRHS;
10702     KnownOne  &= KnownOneRHS;
10703     return;
10704   }
10705   }
10706 }
10707
10708 //===----------------------------------------------------------------------===//
10709 //                           ARM Inline Assembly Support
10710 //===----------------------------------------------------------------------===//
10711
10712 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10713   // Looking for "rev" which is V6+.
10714   if (!Subtarget->hasV6Ops())
10715     return false;
10716
10717   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10718   std::string AsmStr = IA->getAsmString();
10719   SmallVector<StringRef, 4> AsmPieces;
10720   SplitString(AsmStr, AsmPieces, ";\n");
10721
10722   switch (AsmPieces.size()) {
10723   default: return false;
10724   case 1:
10725     AsmStr = AsmPieces[0];
10726     AsmPieces.clear();
10727     SplitString(AsmStr, AsmPieces, " \t,");
10728
10729     // rev $0, $1
10730     if (AsmPieces.size() == 3 &&
10731         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10732         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10733       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10734       if (Ty && Ty->getBitWidth() == 32)
10735         return IntrinsicLowering::LowerToByteSwap(CI);
10736     }
10737     break;
10738   }
10739
10740   return false;
10741 }
10742
10743 /// getConstraintType - Given a constraint letter, return the type of
10744 /// constraint it is for this target.
10745 ARMTargetLowering::ConstraintType
10746 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10747   if (Constraint.size() == 1) {
10748     switch (Constraint[0]) {
10749     default:  break;
10750     case 'l': return C_RegisterClass;
10751     case 'w': return C_RegisterClass;
10752     case 'h': return C_RegisterClass;
10753     case 'x': return C_RegisterClass;
10754     case 't': return C_RegisterClass;
10755     case 'j': return C_Other; // Constant for movw.
10756       // An address with a single base register. Due to the way we
10757       // currently handle addresses it is the same as an 'r' memory constraint.
10758     case 'Q': return C_Memory;
10759     }
10760   } else if (Constraint.size() == 2) {
10761     switch (Constraint[0]) {
10762     default: break;
10763     // All 'U+' constraints are addresses.
10764     case 'U': return C_Memory;
10765     }
10766   }
10767   return TargetLowering::getConstraintType(Constraint);
10768 }
10769
10770 /// Examine constraint type and operand type and determine a weight value.
10771 /// This object must already have been set up with the operand type
10772 /// and the current alternative constraint selected.
10773 TargetLowering::ConstraintWeight
10774 ARMTargetLowering::getSingleConstraintMatchWeight(
10775     AsmOperandInfo &info, const char *constraint) const {
10776   ConstraintWeight weight = CW_Invalid;
10777   Value *CallOperandVal = info.CallOperandVal;
10778     // If we don't have a value, we can't do a match,
10779     // but allow it at the lowest weight.
10780   if (CallOperandVal == NULL)
10781     return CW_Default;
10782   Type *type = CallOperandVal->getType();
10783   // Look at the constraint type.
10784   switch (*constraint) {
10785   default:
10786     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10787     break;
10788   case 'l':
10789     if (type->isIntegerTy()) {
10790       if (Subtarget->isThumb())
10791         weight = CW_SpecificReg;
10792       else
10793         weight = CW_Register;
10794     }
10795     break;
10796   case 'w':
10797     if (type->isFloatingPointTy())
10798       weight = CW_Register;
10799     break;
10800   }
10801   return weight;
10802 }
10803
10804 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10805 RCPair
10806 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10807                                                 MVT VT) const {
10808   if (Constraint.size() == 1) {
10809     // GCC ARM Constraint Letters
10810     switch (Constraint[0]) {
10811     case 'l': // Low regs or general regs.
10812       if (Subtarget->isThumb())
10813         return RCPair(0U, &ARM::tGPRRegClass);
10814       return RCPair(0U, &ARM::GPRRegClass);
10815     case 'h': // High regs or no regs.
10816       if (Subtarget->isThumb())
10817         return RCPair(0U, &ARM::hGPRRegClass);
10818       break;
10819     case 'r':
10820       return RCPair(0U, &ARM::GPRRegClass);
10821     case 'w':
10822       if (VT == MVT::Other)
10823         break;
10824       if (VT == MVT::f32)
10825         return RCPair(0U, &ARM::SPRRegClass);
10826       if (VT.getSizeInBits() == 64)
10827         return RCPair(0U, &ARM::DPRRegClass);
10828       if (VT.getSizeInBits() == 128)
10829         return RCPair(0U, &ARM::QPRRegClass);
10830       break;
10831     case 'x':
10832       if (VT == MVT::Other)
10833         break;
10834       if (VT == MVT::f32)
10835         return RCPair(0U, &ARM::SPR_8RegClass);
10836       if (VT.getSizeInBits() == 64)
10837         return RCPair(0U, &ARM::DPR_8RegClass);
10838       if (VT.getSizeInBits() == 128)
10839         return RCPair(0U, &ARM::QPR_8RegClass);
10840       break;
10841     case 't':
10842       if (VT == MVT::f32)
10843         return RCPair(0U, &ARM::SPRRegClass);
10844       break;
10845     }
10846   }
10847   if (StringRef("{cc}").equals_lower(Constraint))
10848     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10849
10850   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10851 }
10852
10853 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10854 /// vector.  If it is invalid, don't add anything to Ops.
10855 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10856                                                      std::string &Constraint,
10857                                                      std::vector<SDValue>&Ops,
10858                                                      SelectionDAG &DAG) const {
10859   SDValue Result(0, 0);
10860
10861   // Currently only support length 1 constraints.
10862   if (Constraint.length() != 1) return;
10863
10864   char ConstraintLetter = Constraint[0];
10865   switch (ConstraintLetter) {
10866   default: break;
10867   case 'j':
10868   case 'I': case 'J': case 'K': case 'L':
10869   case 'M': case 'N': case 'O':
10870     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10871     if (!C)
10872       return;
10873
10874     int64_t CVal64 = C->getSExtValue();
10875     int CVal = (int) CVal64;
10876     // None of these constraints allow values larger than 32 bits.  Check
10877     // that the value fits in an int.
10878     if (CVal != CVal64)
10879       return;
10880
10881     switch (ConstraintLetter) {
10882       case 'j':
10883         // Constant suitable for movw, must be between 0 and
10884         // 65535.
10885         if (Subtarget->hasV6T2Ops())
10886           if (CVal >= 0 && CVal <= 65535)
10887             break;
10888         return;
10889       case 'I':
10890         if (Subtarget->isThumb1Only()) {
10891           // This must be a constant between 0 and 255, for ADD
10892           // immediates.
10893           if (CVal >= 0 && CVal <= 255)
10894             break;
10895         } else if (Subtarget->isThumb2()) {
10896           // A constant that can be used as an immediate value in a
10897           // data-processing instruction.
10898           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10899             break;
10900         } else {
10901           // A constant that can be used as an immediate value in a
10902           // data-processing instruction.
10903           if (ARM_AM::getSOImmVal(CVal) != -1)
10904             break;
10905         }
10906         return;
10907
10908       case 'J':
10909         if (Subtarget->isThumb()) {  // FIXME thumb2
10910           // This must be a constant between -255 and -1, for negated ADD
10911           // immediates. This can be used in GCC with an "n" modifier that
10912           // prints the negated value, for use with SUB instructions. It is
10913           // not useful otherwise but is implemented for compatibility.
10914           if (CVal >= -255 && CVal <= -1)
10915             break;
10916         } else {
10917           // This must be a constant between -4095 and 4095. It is not clear
10918           // what this constraint is intended for. Implemented for
10919           // compatibility with GCC.
10920           if (CVal >= -4095 && CVal <= 4095)
10921             break;
10922         }
10923         return;
10924
10925       case 'K':
10926         if (Subtarget->isThumb1Only()) {
10927           // A 32-bit value where only one byte has a nonzero value. Exclude
10928           // zero to match GCC. This constraint is used by GCC internally for
10929           // constants that can be loaded with a move/shift combination.
10930           // It is not useful otherwise but is implemented for compatibility.
10931           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10932             break;
10933         } else if (Subtarget->isThumb2()) {
10934           // A constant whose bitwise inverse can be used as an immediate
10935           // value in a data-processing instruction. This can be used in GCC
10936           // with a "B" modifier that prints the inverted value, for use with
10937           // BIC and MVN instructions. It is not useful otherwise but is
10938           // implemented for compatibility.
10939           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10940             break;
10941         } else {
10942           // A constant whose bitwise inverse can be used as an immediate
10943           // value in a data-processing instruction. This can be used in GCC
10944           // with a "B" modifier that prints the inverted value, for use with
10945           // BIC and MVN instructions. It is not useful otherwise but is
10946           // implemented for compatibility.
10947           if (ARM_AM::getSOImmVal(~CVal) != -1)
10948             break;
10949         }
10950         return;
10951
10952       case 'L':
10953         if (Subtarget->isThumb1Only()) {
10954           // This must be a constant between -7 and 7,
10955           // for 3-operand ADD/SUB immediate instructions.
10956           if (CVal >= -7 && CVal < 7)
10957             break;
10958         } else if (Subtarget->isThumb2()) {
10959           // A constant whose negation can be used as an immediate value in a
10960           // data-processing instruction. This can be used in GCC with an "n"
10961           // modifier that prints the negated value, for use with SUB
10962           // instructions. It is not useful otherwise but is implemented for
10963           // compatibility.
10964           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10965             break;
10966         } else {
10967           // A constant whose negation can be used as an immediate value in a
10968           // data-processing instruction. This can be used in GCC with an "n"
10969           // modifier that prints the negated value, for use with SUB
10970           // instructions. It is not useful otherwise but is implemented for
10971           // compatibility.
10972           if (ARM_AM::getSOImmVal(-CVal) != -1)
10973             break;
10974         }
10975         return;
10976
10977       case 'M':
10978         if (Subtarget->isThumb()) { // FIXME thumb2
10979           // This must be a multiple of 4 between 0 and 1020, for
10980           // ADD sp + immediate.
10981           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10982             break;
10983         } else {
10984           // A power of two or a constant between 0 and 32.  This is used in
10985           // GCC for the shift amount on shifted register operands, but it is
10986           // useful in general for any shift amounts.
10987           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10988             break;
10989         }
10990         return;
10991
10992       case 'N':
10993         if (Subtarget->isThumb()) {  // FIXME thumb2
10994           // This must be a constant between 0 and 31, for shift amounts.
10995           if (CVal >= 0 && CVal <= 31)
10996             break;
10997         }
10998         return;
10999
11000       case 'O':
11001         if (Subtarget->isThumb()) {  // FIXME thumb2
11002           // This must be a multiple of 4 between -508 and 508, for
11003           // ADD/SUB sp = sp + immediate.
11004           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11005             break;
11006         }
11007         return;
11008     }
11009     Result = DAG.getTargetConstant(CVal, Op.getValueType());
11010     break;
11011   }
11012
11013   if (Result.getNode()) {
11014     Ops.push_back(Result);
11015     return;
11016   }
11017   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11018 }
11019
11020 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11021   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
11022   unsigned Opcode = Op->getOpcode();
11023   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11024       "Invalid opcode for Div/Rem lowering");
11025   bool isSigned = (Opcode == ISD::SDIVREM);
11026   EVT VT = Op->getValueType(0);
11027   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11028
11029   RTLIB::Libcall LC;
11030   switch (VT.getSimpleVT().SimpleTy) {
11031   default: llvm_unreachable("Unexpected request for libcall!");
11032   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
11033   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11034   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11035   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11036   }
11037
11038   SDValue InChain = DAG.getEntryNode();
11039
11040   TargetLowering::ArgListTy Args;
11041   TargetLowering::ArgListEntry Entry;
11042   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
11043     EVT ArgVT = Op->getOperand(i).getValueType();
11044     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11045     Entry.Node = Op->getOperand(i);
11046     Entry.Ty = ArgTy;
11047     Entry.isSExt = isSigned;
11048     Entry.isZExt = !isSigned;
11049     Args.push_back(Entry);
11050   }
11051
11052   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11053                                          getPointerTy());
11054
11055   Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
11056
11057   SDLoc dl(Op);
11058   TargetLowering::
11059   CallLoweringInfo CLI(InChain, RetTy, isSigned, !isSigned, false, true,
11060                     0, getLibcallCallingConv(LC), /*isTailCall=*/false,
11061                     /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
11062                     Callee, Args, DAG, dl);
11063   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11064
11065   return CallInfo.first;
11066 }
11067
11068 bool
11069 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11070   // The ARM target isn't yet aware of offsets.
11071   return false;
11072 }
11073
11074 bool ARM::isBitFieldInvertedMask(unsigned v) {
11075   if (v == 0xffffffff)
11076     return false;
11077
11078   // there can be 1's on either or both "outsides", all the "inside"
11079   // bits must be 0's
11080   unsigned TO = CountTrailingOnes_32(v);
11081   unsigned LO = CountLeadingOnes_32(v);
11082   v = (v >> TO) << TO;
11083   v = (v << LO) >> LO;
11084   return v == 0;
11085 }
11086
11087 /// isFPImmLegal - Returns true if the target can instruction select the
11088 /// specified FP immediate natively. If false, the legalizer will
11089 /// materialize the FP immediate as a load from a constant pool.
11090 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11091   if (!Subtarget->hasVFP3())
11092     return false;
11093   if (VT == MVT::f32)
11094     return ARM_AM::getFP32Imm(Imm) != -1;
11095   if (VT == MVT::f64)
11096     return ARM_AM::getFP64Imm(Imm) != -1;
11097   return false;
11098 }
11099
11100 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11101 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11102 /// specified in the intrinsic calls.
11103 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11104                                            const CallInst &I,
11105                                            unsigned Intrinsic) const {
11106   switch (Intrinsic) {
11107   case Intrinsic::arm_neon_vld1:
11108   case Intrinsic::arm_neon_vld2:
11109   case Intrinsic::arm_neon_vld3:
11110   case Intrinsic::arm_neon_vld4:
11111   case Intrinsic::arm_neon_vld2lane:
11112   case Intrinsic::arm_neon_vld3lane:
11113   case Intrinsic::arm_neon_vld4lane: {
11114     Info.opc = ISD::INTRINSIC_W_CHAIN;
11115     // Conservatively set memVT to the entire set of vectors loaded.
11116     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
11117     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11118     Info.ptrVal = I.getArgOperand(0);
11119     Info.offset = 0;
11120     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11121     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11122     Info.vol = false; // volatile loads with NEON intrinsics not supported
11123     Info.readMem = true;
11124     Info.writeMem = false;
11125     return true;
11126   }
11127   case Intrinsic::arm_neon_vst1:
11128   case Intrinsic::arm_neon_vst2:
11129   case Intrinsic::arm_neon_vst3:
11130   case Intrinsic::arm_neon_vst4:
11131   case Intrinsic::arm_neon_vst2lane:
11132   case Intrinsic::arm_neon_vst3lane:
11133   case Intrinsic::arm_neon_vst4lane: {
11134     Info.opc = ISD::INTRINSIC_VOID;
11135     // Conservatively set memVT to the entire set of vectors stored.
11136     unsigned NumElts = 0;
11137     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11138       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11139       if (!ArgTy->isVectorTy())
11140         break;
11141       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
11142     }
11143     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11144     Info.ptrVal = I.getArgOperand(0);
11145     Info.offset = 0;
11146     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11147     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11148     Info.vol = false; // volatile stores with NEON intrinsics not supported
11149     Info.readMem = false;
11150     Info.writeMem = true;
11151     return true;
11152   }
11153   case Intrinsic::arm_ldaex:
11154   case Intrinsic::arm_ldrex: {
11155     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11156     Info.opc = ISD::INTRINSIC_W_CHAIN;
11157     Info.memVT = MVT::getVT(PtrTy->getElementType());
11158     Info.ptrVal = I.getArgOperand(0);
11159     Info.offset = 0;
11160     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11161     Info.vol = true;
11162     Info.readMem = true;
11163     Info.writeMem = false;
11164     return true;
11165   }
11166   case Intrinsic::arm_stlex:
11167   case Intrinsic::arm_strex: {
11168     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11169     Info.opc = ISD::INTRINSIC_W_CHAIN;
11170     Info.memVT = MVT::getVT(PtrTy->getElementType());
11171     Info.ptrVal = I.getArgOperand(1);
11172     Info.offset = 0;
11173     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11174     Info.vol = true;
11175     Info.readMem = false;
11176     Info.writeMem = true;
11177     return true;
11178   }
11179   case Intrinsic::arm_stlexd:
11180   case Intrinsic::arm_strexd: {
11181     Info.opc = ISD::INTRINSIC_W_CHAIN;
11182     Info.memVT = MVT::i64;
11183     Info.ptrVal = I.getArgOperand(2);
11184     Info.offset = 0;
11185     Info.align = 8;
11186     Info.vol = true;
11187     Info.readMem = false;
11188     Info.writeMem = true;
11189     return true;
11190   }
11191   case Intrinsic::arm_ldaexd:
11192   case Intrinsic::arm_ldrexd: {
11193     Info.opc = ISD::INTRINSIC_W_CHAIN;
11194     Info.memVT = MVT::i64;
11195     Info.ptrVal = I.getArgOperand(0);
11196     Info.offset = 0;
11197     Info.align = 8;
11198     Info.vol = true;
11199     Info.readMem = true;
11200     Info.writeMem = false;
11201     return true;
11202   }
11203   default:
11204     break;
11205   }
11206
11207   return false;
11208 }
11209
11210 /// \brief Returns true if it is beneficial to convert a load of a constant
11211 /// to just the constant itself.
11212 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11213                                                           Type *Ty) const {
11214   assert(Ty->isIntegerTy());
11215
11216   unsigned Bits = Ty->getPrimitiveSizeInBits();
11217   if (Bits == 0 || Bits > 32)
11218     return false;
11219   return true;
11220 }