ARM: enable tail call optimisation on Thumb 2
[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 "ARM.h"
18 #include "ARMCallingConv.h"
19 #include "ARMConstantPoolValue.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "ARMPerfectShuffle.h"
22 #include "ARMSubtarget.h"
23 #include "ARMTargetMachine.h"
24 #include "ARMTargetObjectFile.h"
25 #include "MCTargetDesc/ARMAddressingModes.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/IntrinsicLowering.h"
30 #include "llvm/CodeGen/MachineBasicBlock.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalValue.h"
41 #include "llvm/IR/Instruction.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/IR/Type.h"
45 #include "llvm/MC/MCSectionMachO.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include <utility>
52 using namespace llvm;
53
54 STATISTIC(NumTailCalls, "Number of tail calls");
55 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
56 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
57
58 // This option should go away when tail calls fully work.
59 static cl::opt<bool>
60 EnableARMTailCalls("arm-tail-calls", cl::Hidden,
61   cl::desc("Generate tail calls (TEMPORARY OPTION)."),
62   cl::init(false));
63
64 cl::opt<bool>
65 EnableARMLongCalls("arm-long-calls", cl::Hidden,
66   cl::desc("Generate calls via indirect call instructions"),
67   cl::init(false));
68
69 static cl::opt<bool>
70 ARMInterworking("arm-interworking", cl::Hidden,
71   cl::desc("Enable / disable ARM interworking (for debugging only)"),
72   cl::init(true));
73
74 namespace {
75   class ARMCCState : public CCState {
76   public:
77     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
78                const TargetMachine &TM, SmallVectorImpl<CCValAssign> &locs,
79                LLVMContext &C, ParmContext PC)
80         : CCState(CC, isVarArg, MF, TM, locs, C) {
81       assert(((PC == Call) || (PC == Prologue)) &&
82              "ARMCCState users must specify whether their context is call"
83              "or prologue generation.");
84       CallOrPrologue = PC;
85     }
86   };
87 }
88
89 // The APCS parameter registers.
90 static const uint16_t GPRArgRegs[] = {
91   ARM::R0, ARM::R1, ARM::R2, ARM::R3
92 };
93
94 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
95                                        MVT PromotedBitwiseVT) {
96   if (VT != PromotedLdStVT) {
97     setOperationAction(ISD::LOAD, VT, Promote);
98     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
99
100     setOperationAction(ISD::STORE, VT, Promote);
101     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
102   }
103
104   MVT ElemTy = VT.getVectorElementType();
105   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
106     setOperationAction(ISD::SETCC, VT, Custom);
107   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
108   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
109   if (ElemTy == MVT::i32) {
110     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
111     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
112     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
113     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
114   } else {
115     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
116     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
117     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
118     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
119   }
120   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
121   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
122   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
123   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
124   setOperationAction(ISD::SELECT,            VT, Expand);
125   setOperationAction(ISD::SELECT_CC,         VT, Expand);
126   setOperationAction(ISD::VSELECT,           VT, Expand);
127   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
128   if (VT.isInteger()) {
129     setOperationAction(ISD::SHL, VT, Custom);
130     setOperationAction(ISD::SRA, VT, Custom);
131     setOperationAction(ISD::SRL, VT, Custom);
132   }
133
134   // Promote all bit-wise operations.
135   if (VT.isInteger() && VT != PromotedBitwiseVT) {
136     setOperationAction(ISD::AND, VT, Promote);
137     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
138     setOperationAction(ISD::OR,  VT, Promote);
139     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
140     setOperationAction(ISD::XOR, VT, Promote);
141     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
142   }
143
144   // Neon does not support vector divide/remainder operations.
145   setOperationAction(ISD::SDIV, VT, Expand);
146   setOperationAction(ISD::UDIV, VT, Expand);
147   setOperationAction(ISD::FDIV, VT, Expand);
148   setOperationAction(ISD::SREM, VT, Expand);
149   setOperationAction(ISD::UREM, VT, Expand);
150   setOperationAction(ISD::FREM, VT, Expand);
151 }
152
153 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
154   addRegisterClass(VT, &ARM::DPRRegClass);
155   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
156 }
157
158 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
159   addRegisterClass(VT, &ARM::DPairRegClass);
160   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
161 }
162
163 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
164   if (TM.getSubtarget<ARMSubtarget>().isTargetMachO())
165     return new TargetLoweringObjectFileMachO();
166
167   return new ARMElfTargetObjectFile();
168 }
169
170 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
171     : TargetLowering(TM, createTLOF(TM)) {
172   Subtarget = &TM.getSubtarget<ARMSubtarget>();
173   RegInfo = TM.getRegisterInfo();
174   Itins = TM.getInstrItineraryData();
175
176   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
177
178   if (Subtarget->isTargetMachO()) {
179     // Uses VFP for Thumb libfuncs if available.
180     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
181         Subtarget->hasARMOps()) {
182       // Single-precision floating-point arithmetic.
183       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
184       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
185       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
186       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
187
188       // Double-precision floating-point arithmetic.
189       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
190       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
191       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
192       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
193
194       // Single-precision comparisons.
195       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
196       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
197       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
198       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
199       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
200       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
201       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
202       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
203
204       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
205       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
206       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
207       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
208       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
209       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
210       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
211       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
212
213       // Double-precision comparisons.
214       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
215       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
216       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
217       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
218       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
219       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
220       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
221       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
222
223       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
224       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
225       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
226       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
227       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
228       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
229       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
230       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
231
232       // Floating-point to integer conversions.
233       // i64 conversions are done via library routines even when generating VFP
234       // instructions, so use the same ones.
235       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
236       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
237       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
238       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
239
240       // Conversions between floating types.
241       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
242       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
243
244       // Integer to floating-point conversions.
245       // i64 conversions are done via library routines even when generating VFP
246       // instructions, so use the same ones.
247       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
248       // e.g., __floatunsidf vs. __floatunssidfvfp.
249       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
250       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
251       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
252       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
253     }
254   }
255
256   // These libcalls are not available in 32-bit.
257   setLibcallName(RTLIB::SHL_I128, 0);
258   setLibcallName(RTLIB::SRL_I128, 0);
259   setLibcallName(RTLIB::SRA_I128, 0);
260
261   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO()) {
262     // Double-precision floating-point arithmetic helper functions
263     // RTABI chapter 4.1.2, Table 2
264     setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
265     setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
266     setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
267     setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
268     setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
269     setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
270     setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
271     setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
272
273     // Double-precision floating-point comparison helper functions
274     // RTABI chapter 4.1.2, Table 3
275     setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
276     setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
277     setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
278     setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
279     setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
280     setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
281     setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
282     setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
283     setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
284     setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
285     setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
286     setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
287     setLibcallName(RTLIB::UO_F64,  "__aeabi_dcmpun");
288     setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
289     setLibcallName(RTLIB::O_F64,   "__aeabi_dcmpun");
290     setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
291     setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
292     setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
293     setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
294     setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
295     setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
296     setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
297     setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
298     setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
299
300     // Single-precision floating-point arithmetic helper functions
301     // RTABI chapter 4.1.2, Table 4
302     setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
303     setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
304     setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
305     setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
306     setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
307     setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
308     setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
309     setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
310
311     // Single-precision floating-point comparison helper functions
312     // RTABI chapter 4.1.2, Table 5
313     setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
314     setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
315     setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
316     setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
317     setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
318     setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
319     setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
320     setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
321     setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
322     setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
323     setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
324     setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
325     setLibcallName(RTLIB::UO_F32,  "__aeabi_fcmpun");
326     setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
327     setLibcallName(RTLIB::O_F32,   "__aeabi_fcmpun");
328     setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
329     setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
330     setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
331     setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
332     setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
333     setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
334     setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
335     setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
336     setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
337
338     // Floating-point to integer conversions.
339     // RTABI chapter 4.1.2, Table 6
340     setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
341     setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
342     setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
343     setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
344     setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
345     setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
346     setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
347     setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
348     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
349     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
350     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
351     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
352     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
353     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
354     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
355     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
356
357     // Conversions between floating types.
358     // RTABI chapter 4.1.2, Table 7
359     setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
360     setLibcallName(RTLIB::FPEXT_F32_F64,   "__aeabi_f2d");
361     setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
362     setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
363
364     // Integer to floating-point conversions.
365     // RTABI chapter 4.1.2, Table 8
366     setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
367     setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
368     setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
369     setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
370     setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
371     setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
372     setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
373     setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
374     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
375     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
376     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
377     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
378     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
379     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
380     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
381     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
382
383     // Long long helper functions
384     // RTABI chapter 4.2, Table 9
385     setLibcallName(RTLIB::MUL_I64,  "__aeabi_lmul");
386     setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
387     setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
388     setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
389     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
390     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
391     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
392     setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
393     setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
394     setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
395
396     // Integer division functions
397     // RTABI chapter 4.3.1
398     setLibcallName(RTLIB::SDIV_I8,  "__aeabi_idiv");
399     setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
400     setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
401     setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
402     setLibcallName(RTLIB::UDIV_I8,  "__aeabi_uidiv");
403     setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
404     setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
405     setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
406     setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
407     setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
408     setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
409     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
410     setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
411     setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
412     setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
413     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
414
415     // Memory operations
416     // RTABI chapter 4.3.4
417     setLibcallName(RTLIB::MEMCPY,  "__aeabi_memcpy");
418     setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
419     setLibcallName(RTLIB::MEMSET,  "__aeabi_memset");
420     setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
421     setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
422     setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
423   }
424
425   // Use divmod compiler-rt calls for iOS 5.0 and later.
426   if (Subtarget->getTargetTriple().isiOS() &&
427       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
428     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
429     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
430   }
431
432   if (Subtarget->isThumb1Only())
433     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
434   else
435     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
436   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
437       !Subtarget->isThumb1Only()) {
438     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
439     if (!Subtarget->isFPOnlySP())
440       addRegisterClass(MVT::f64, &ARM::DPRRegClass);
441
442     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
443   }
444
445   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
446        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
447     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
448          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
449       setTruncStoreAction((MVT::SimpleValueType)VT,
450                           (MVT::SimpleValueType)InnerVT, Expand);
451     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
452     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
453     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
454   }
455
456   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
457   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
458
459   if (Subtarget->hasNEON()) {
460     addDRTypeForNEON(MVT::v2f32);
461     addDRTypeForNEON(MVT::v8i8);
462     addDRTypeForNEON(MVT::v4i16);
463     addDRTypeForNEON(MVT::v2i32);
464     addDRTypeForNEON(MVT::v1i64);
465
466     addQRTypeForNEON(MVT::v4f32);
467     addQRTypeForNEON(MVT::v2f64);
468     addQRTypeForNEON(MVT::v16i8);
469     addQRTypeForNEON(MVT::v8i16);
470     addQRTypeForNEON(MVT::v4i32);
471     addQRTypeForNEON(MVT::v2i64);
472
473     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
474     // neither Neon nor VFP support any arithmetic operations on it.
475     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
476     // supported for v4f32.
477     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
478     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
479     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
480     // FIXME: Code duplication: FDIV and FREM are expanded always, see
481     // ARMTargetLowering::addTypeForNEON method for details.
482     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
483     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
484     // FIXME: Create unittest.
485     // In another words, find a way when "copysign" appears in DAG with vector
486     // operands.
487     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
488     // FIXME: Code duplication: SETCC has custom operation action, see
489     // ARMTargetLowering::addTypeForNEON method for details.
490     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
491     // FIXME: Create unittest for FNEG and for FABS.
492     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
493     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
494     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
495     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
496     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
497     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
498     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
499     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
500     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
501     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
502     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
503     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
504     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
505     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
506     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
507     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
508     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
509     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
510     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
511
512     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
513     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
514     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
515     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
516     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
517     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
518     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
519     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
520     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
521     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
522     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
523     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
524     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
525     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
526     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
527
528     // Mark v2f32 intrinsics.
529     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
530     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
531     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
532     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
533     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
534     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
535     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
536     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
537     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
538     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
539     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
540     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
541     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
542     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
543     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
544
545     // Neon does not support some operations on v1i64 and v2i64 types.
546     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
547     // Custom handling for some quad-vector types to detect VMULL.
548     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
549     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
550     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
551     // Custom handling for some vector types to avoid expensive expansions
552     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
553     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
554     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
555     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
556     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
557     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
558     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
559     // a destination type that is wider than the source, and nor does
560     // it have a FP_TO_[SU]INT instruction with a narrower destination than
561     // source.
562     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
563     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
564     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
565     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
566
567     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
568     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
569
570     // NEON does not have single instruction CTPOP for vectors with element
571     // types wider than 8-bits.  However, custom lowering can leverage the
572     // v8i8/v16i8 vcnt instruction.
573     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
574     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
575     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
576     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
577
578     // NEON only has FMA instructions as of VFP4.
579     if (!Subtarget->hasVFP4()) {
580       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
581       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
582     }
583
584     setTargetDAGCombine(ISD::INTRINSIC_VOID);
585     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
586     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
587     setTargetDAGCombine(ISD::SHL);
588     setTargetDAGCombine(ISD::SRL);
589     setTargetDAGCombine(ISD::SRA);
590     setTargetDAGCombine(ISD::SIGN_EXTEND);
591     setTargetDAGCombine(ISD::ZERO_EXTEND);
592     setTargetDAGCombine(ISD::ANY_EXTEND);
593     setTargetDAGCombine(ISD::SELECT_CC);
594     setTargetDAGCombine(ISD::BUILD_VECTOR);
595     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
596     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
597     setTargetDAGCombine(ISD::STORE);
598     setTargetDAGCombine(ISD::FP_TO_SINT);
599     setTargetDAGCombine(ISD::FP_TO_UINT);
600     setTargetDAGCombine(ISD::FDIV);
601
602     // It is legal to extload from v4i8 to v4i16 or v4i32.
603     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
604                   MVT::v4i16, MVT::v2i16,
605                   MVT::v2i32};
606     for (unsigned i = 0; i < 6; ++i) {
607       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
608       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
609       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
610     }
611   }
612
613   // ARM and Thumb2 support UMLAL/SMLAL.
614   if (!Subtarget->isThumb1Only())
615     setTargetDAGCombine(ISD::ADDC);
616
617
618   computeRegisterProperties();
619
620   // ARM does not have f32 extending load.
621   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
622
623   // ARM does not have i1 sign extending load.
624   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
625
626   // ARM supports all 4 flavors of integer indexed load / store.
627   if (!Subtarget->isThumb1Only()) {
628     for (unsigned im = (unsigned)ISD::PRE_INC;
629          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
630       setIndexedLoadAction(im,  MVT::i1,  Legal);
631       setIndexedLoadAction(im,  MVT::i8,  Legal);
632       setIndexedLoadAction(im,  MVT::i16, Legal);
633       setIndexedLoadAction(im,  MVT::i32, Legal);
634       setIndexedStoreAction(im, MVT::i1,  Legal);
635       setIndexedStoreAction(im, MVT::i8,  Legal);
636       setIndexedStoreAction(im, MVT::i16, Legal);
637       setIndexedStoreAction(im, MVT::i32, Legal);
638     }
639   }
640
641   // i64 operation support.
642   setOperationAction(ISD::MUL,     MVT::i64, Expand);
643   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
644   if (Subtarget->isThumb1Only()) {
645     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
646     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
647   }
648   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
649       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
650     setOperationAction(ISD::MULHS, MVT::i32, Expand);
651
652   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
653   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
654   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
655   setOperationAction(ISD::SRL,       MVT::i64, Custom);
656   setOperationAction(ISD::SRA,       MVT::i64, Custom);
657
658   if (!Subtarget->isThumb1Only()) {
659     // FIXME: We should do this for Thumb1 as well.
660     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
661     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
662     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
663     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
664   }
665
666   // ARM does not have ROTL.
667   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
668   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
669   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
670   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
671     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
672
673   // These just redirect to CTTZ and CTLZ on ARM.
674   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
675   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
676
677   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
678
679   // Only ARMv6 has BSWAP.
680   if (!Subtarget->hasV6Ops())
681     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
682
683   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
684       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
685     // These are expanded into libcalls if the cpu doesn't have HW divider.
686     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
687     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
688   }
689
690   // FIXME: Also set divmod for SREM on EABI
691   setOperationAction(ISD::SREM,  MVT::i32, Expand);
692   setOperationAction(ISD::UREM,  MVT::i32, Expand);
693   // Register based DivRem for AEABI (RTABI 4.2)
694   if (Subtarget->isTargetAEABI()) {
695     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
696     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
697     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
698     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
699     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
700     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
701     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
702     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
703
704     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
705     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
706     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
707     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
708     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
709     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
710     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
711     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
712
713     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
714     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
715   } else {
716     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
717     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
718   }
719
720   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
721   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
722   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
723   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
724   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
725
726   setOperationAction(ISD::TRAP, MVT::Other, Legal);
727
728   // Use the default implementation.
729   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
730   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
731   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
732   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
733   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
734   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
735
736   if (!Subtarget->isTargetMachO()) {
737     // Non-MachO platforms may return values in these registers via the
738     // personality function.
739     setExceptionPointerRegister(ARM::R0);
740     setExceptionSelectorRegister(ARM::R1);
741   }
742
743   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
744   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
745   // the default expansion.
746   if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
747     // ATOMIC_FENCE needs custom lowering; the other 32-bit ones are legal and
748     // handled normally.
749     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
750     // Custom lowering for 64-bit ops
751     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i64, Custom);
752     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i64, Custom);
753     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i64, Custom);
754     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i64, Custom);
755     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i64, Custom);
756     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i64, Custom);
757     setOperationAction(ISD::ATOMIC_LOAD_MIN,  MVT::i64, Custom);
758     setOperationAction(ISD::ATOMIC_LOAD_MAX,  MVT::i64, Custom);
759     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
760     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
761     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
762     // On v8, we have particularly efficient implementations of atomic fences
763     // if they can be combined with nearby atomic loads and stores.
764     if (!Subtarget->hasV8Ops()) {
765       // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
766       setInsertFencesForAtomic(true);
767     }
768     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
769   } else {
770     // If there's anything we can use as a barrier, go through custom lowering
771     // for ATOMIC_FENCE.
772     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
773                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
774
775     // Set them all for expansion, which will force libcalls.
776     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
777     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
778     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
779     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
780     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
781     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
782     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
783     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
784     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
785     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
786     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
787     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
788     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
789     // Unordered/Monotonic case.
790     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
791     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
792   }
793
794   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
795
796   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
797   if (!Subtarget->hasV6Ops()) {
798     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
799     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
800   }
801   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
802
803   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
804       !Subtarget->isThumb1Only()) {
805     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
806     // iff target supports vfp2.
807     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
808     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
809   }
810
811   // We want to custom lower some of our intrinsics.
812   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
813   if (Subtarget->isTargetDarwin()) {
814     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
815     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
816     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
817   }
818
819   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
820   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
821   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
822   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
823   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
824   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
825   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
826   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
827   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
828
829   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
830   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
831   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
832   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
833   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
834
835   // We don't support sin/cos/fmod/copysign/pow
836   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
837   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
838   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
839   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
840   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
841   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
842   setOperationAction(ISD::FREM,      MVT::f64, Expand);
843   setOperationAction(ISD::FREM,      MVT::f32, Expand);
844   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
845       !Subtarget->isThumb1Only()) {
846     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
847     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
848   }
849   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
850   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
851
852   if (!Subtarget->hasVFP4()) {
853     setOperationAction(ISD::FMA, MVT::f64, Expand);
854     setOperationAction(ISD::FMA, MVT::f32, Expand);
855   }
856
857   // Various VFP goodness
858   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
859     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
860     if (Subtarget->hasVFP2()) {
861       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
862       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
863       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
864       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
865     }
866     // Special handling for half-precision FP.
867     if (!Subtarget->hasFP16()) {
868       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
869       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
870     }
871   }
872       
873   // Combine sin / cos into one node or libcall if possible.
874   if (Subtarget->hasSinCos()) {
875     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
876     setLibcallName(RTLIB::SINCOS_F64, "sincos");
877     if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
878       // For iOS, we don't want to the normal expansion of a libcall to
879       // sincos. We want to issue a libcall to __sincos_stret.
880       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
881       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
882     }
883   }
884
885   // We have target-specific dag combine patterns for the following nodes:
886   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
887   setTargetDAGCombine(ISD::ADD);
888   setTargetDAGCombine(ISD::SUB);
889   setTargetDAGCombine(ISD::MUL);
890   setTargetDAGCombine(ISD::AND);
891   setTargetDAGCombine(ISD::OR);
892   setTargetDAGCombine(ISD::XOR);
893
894   if (Subtarget->hasV6Ops())
895     setTargetDAGCombine(ISD::SRL);
896
897   setStackPointerRegisterToSaveRestore(ARM::SP);
898
899   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
900       !Subtarget->hasVFP2())
901     setSchedulingPreference(Sched::RegPressure);
902   else
903     setSchedulingPreference(Sched::Hybrid);
904
905   //// temporary - rewrite interface to use type
906   MaxStoresPerMemset = 8;
907   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
908   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
909   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
910   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
911   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
912
913   // On ARM arguments smaller than 4 bytes are extended, so all arguments
914   // are at least 4 bytes aligned.
915   setMinStackArgumentAlignment(4);
916
917   // Prefer likely predicted branches to selects on out-of-order cores.
918   PredictableSelectIsExpensive = Subtarget->isLikeA9();
919
920   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
921 }
922
923 static void getExclusiveOperation(unsigned Size, AtomicOrdering Ord,
924                                   bool isThumb2, unsigned &LdrOpc,
925                                   unsigned &StrOpc) {
926   static const unsigned LoadBares[4][2] =  {{ARM::LDREXB, ARM::t2LDREXB},
927                                             {ARM::LDREXH, ARM::t2LDREXH},
928                                             {ARM::LDREX,  ARM::t2LDREX},
929                                             {ARM::LDREXD, ARM::t2LDREXD}};
930   static const unsigned LoadAcqs[4][2] =   {{ARM::LDAEXB, ARM::t2LDAEXB},
931                                             {ARM::LDAEXH, ARM::t2LDAEXH},
932                                             {ARM::LDAEX,  ARM::t2LDAEX},
933                                             {ARM::LDAEXD, ARM::t2LDAEXD}};
934   static const unsigned StoreBares[4][2] = {{ARM::STREXB, ARM::t2STREXB},
935                                             {ARM::STREXH, ARM::t2STREXH},
936                                             {ARM::STREX,  ARM::t2STREX},
937                                             {ARM::STREXD, ARM::t2STREXD}};
938   static const unsigned StoreRels[4][2] =  {{ARM::STLEXB, ARM::t2STLEXB},
939                                             {ARM::STLEXH, ARM::t2STLEXH},
940                                             {ARM::STLEX,  ARM::t2STLEX},
941                                             {ARM::STLEXD, ARM::t2STLEXD}};
942
943   const unsigned (*LoadOps)[2], (*StoreOps)[2];
944   if (Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent)
945     LoadOps = LoadAcqs;
946   else
947     LoadOps = LoadBares;
948
949   if (Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent)
950     StoreOps = StoreRels;
951   else
952     StoreOps = StoreBares;
953
954   assert(isPowerOf2_32(Size) && Size <= 8 &&
955          "unsupported size for atomic binary op!");
956
957   LdrOpc = LoadOps[Log2_32(Size)][isThumb2];
958   StrOpc = StoreOps[Log2_32(Size)][isThumb2];
959 }
960
961 // FIXME: It might make sense to define the representative register class as the
962 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
963 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
964 // SPR's representative would be DPR_VFP2. This should work well if register
965 // pressure tracking were modified such that a register use would increment the
966 // pressure of the register class's representative and all of it's super
967 // classes' representatives transitively. We have not implemented this because
968 // of the difficulty prior to coalescing of modeling operand register classes
969 // due to the common occurrence of cross class copies and subregister insertions
970 // and extractions.
971 std::pair<const TargetRegisterClass*, uint8_t>
972 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
973   const TargetRegisterClass *RRC = 0;
974   uint8_t Cost = 1;
975   switch (VT.SimpleTy) {
976   default:
977     return TargetLowering::findRepresentativeClass(VT);
978   // Use DPR as representative register class for all floating point
979   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
980   // the cost is 1 for both f32 and f64.
981   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
982   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
983     RRC = &ARM::DPRRegClass;
984     // When NEON is used for SP, only half of the register file is available
985     // because operations that define both SP and DP results will be constrained
986     // to the VFP2 class (D0-D15). We currently model this constraint prior to
987     // coalescing by double-counting the SP regs. See the FIXME above.
988     if (Subtarget->useNEONForSinglePrecisionFP())
989       Cost = 2;
990     break;
991   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
992   case MVT::v4f32: case MVT::v2f64:
993     RRC = &ARM::DPRRegClass;
994     Cost = 2;
995     break;
996   case MVT::v4i64:
997     RRC = &ARM::DPRRegClass;
998     Cost = 4;
999     break;
1000   case MVT::v8i64:
1001     RRC = &ARM::DPRRegClass;
1002     Cost = 8;
1003     break;
1004   }
1005   return std::make_pair(RRC, Cost);
1006 }
1007
1008 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1009   switch (Opcode) {
1010   default: return 0;
1011   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1012   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1013   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1014   case ARMISD::CALL:          return "ARMISD::CALL";
1015   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1016   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1017   case ARMISD::tCALL:         return "ARMISD::tCALL";
1018   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1019   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1020   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1021   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1022   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1023   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1024   case ARMISD::CMP:           return "ARMISD::CMP";
1025   case ARMISD::CMN:           return "ARMISD::CMN";
1026   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1027   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1028   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1029   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1030   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1031
1032   case ARMISD::CMOV:          return "ARMISD::CMOV";
1033
1034   case ARMISD::RBIT:          return "ARMISD::RBIT";
1035
1036   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
1037   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
1038   case ARMISD::SITOF:         return "ARMISD::SITOF";
1039   case ARMISD::UITOF:         return "ARMISD::UITOF";
1040
1041   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1042   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1043   case ARMISD::RRX:           return "ARMISD::RRX";
1044
1045   case ARMISD::ADDC:          return "ARMISD::ADDC";
1046   case ARMISD::ADDE:          return "ARMISD::ADDE";
1047   case ARMISD::SUBC:          return "ARMISD::SUBC";
1048   case ARMISD::SUBE:          return "ARMISD::SUBE";
1049
1050   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1051   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1052
1053   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1054   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1055
1056   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1057
1058   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1059
1060   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1061
1062   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1063
1064   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1065
1066   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1067   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1068   case ARMISD::VCGE:          return "ARMISD::VCGE";
1069   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1070   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1071   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1072   case ARMISD::VCGT:          return "ARMISD::VCGT";
1073   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1074   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1075   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1076   case ARMISD::VTST:          return "ARMISD::VTST";
1077
1078   case ARMISD::VSHL:          return "ARMISD::VSHL";
1079   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1080   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1081   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1082   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1083   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1084   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1085   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1086   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1087   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1088   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1089   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1090   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1091   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1092   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1093   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1094   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1095   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1096   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1097   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1098   case ARMISD::VDUP:          return "ARMISD::VDUP";
1099   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1100   case ARMISD::VEXT:          return "ARMISD::VEXT";
1101   case ARMISD::VREV64:        return "ARMISD::VREV64";
1102   case ARMISD::VREV32:        return "ARMISD::VREV32";
1103   case ARMISD::VREV16:        return "ARMISD::VREV16";
1104   case ARMISD::VZIP:          return "ARMISD::VZIP";
1105   case ARMISD::VUZP:          return "ARMISD::VUZP";
1106   case ARMISD::VTRN:          return "ARMISD::VTRN";
1107   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1108   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1109   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1110   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1111   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1112   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1113   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1114   case ARMISD::FMAX:          return "ARMISD::FMAX";
1115   case ARMISD::FMIN:          return "ARMISD::FMIN";
1116   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1117   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1118   case ARMISD::BFI:           return "ARMISD::BFI";
1119   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1120   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1121   case ARMISD::VBSL:          return "ARMISD::VBSL";
1122   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1123   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1124   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1125   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1126   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1127   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1128   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1129   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1130   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1131   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1132   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1133   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1134   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1135   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1136   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1137   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1138   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1139   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1140   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1141   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1142   }
1143 }
1144
1145 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1146   if (!VT.isVector()) return getPointerTy();
1147   return VT.changeVectorElementTypeToInteger();
1148 }
1149
1150 /// getRegClassFor - Return the register class that should be used for the
1151 /// specified value type.
1152 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1153   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1154   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1155   // load / store 4 to 8 consecutive D registers.
1156   if (Subtarget->hasNEON()) {
1157     if (VT == MVT::v4i64)
1158       return &ARM::QQPRRegClass;
1159     if (VT == MVT::v8i64)
1160       return &ARM::QQQQPRRegClass;
1161   }
1162   return TargetLowering::getRegClassFor(VT);
1163 }
1164
1165 // Create a fast isel object.
1166 FastISel *
1167 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1168                                   const TargetLibraryInfo *libInfo) const {
1169   return ARM::createFastISel(funcInfo, libInfo);
1170 }
1171
1172 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1173 /// be used for loads / stores from the global.
1174 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1175   return (Subtarget->isThumb1Only() ? 127 : 4095);
1176 }
1177
1178 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1179   unsigned NumVals = N->getNumValues();
1180   if (!NumVals)
1181     return Sched::RegPressure;
1182
1183   for (unsigned i = 0; i != NumVals; ++i) {
1184     EVT VT = N->getValueType(i);
1185     if (VT == MVT::Glue || VT == MVT::Other)
1186       continue;
1187     if (VT.isFloatingPoint() || VT.isVector())
1188       return Sched::ILP;
1189   }
1190
1191   if (!N->isMachineOpcode())
1192     return Sched::RegPressure;
1193
1194   // Load are scheduled for latency even if there instruction itinerary
1195   // is not available.
1196   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1197   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1198
1199   if (MCID.getNumDefs() == 0)
1200     return Sched::RegPressure;
1201   if (!Itins->isEmpty() &&
1202       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1203     return Sched::ILP;
1204
1205   return Sched::RegPressure;
1206 }
1207
1208 //===----------------------------------------------------------------------===//
1209 // Lowering Code
1210 //===----------------------------------------------------------------------===//
1211
1212 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1213 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1214   switch (CC) {
1215   default: llvm_unreachable("Unknown condition code!");
1216   case ISD::SETNE:  return ARMCC::NE;
1217   case ISD::SETEQ:  return ARMCC::EQ;
1218   case ISD::SETGT:  return ARMCC::GT;
1219   case ISD::SETGE:  return ARMCC::GE;
1220   case ISD::SETLT:  return ARMCC::LT;
1221   case ISD::SETLE:  return ARMCC::LE;
1222   case ISD::SETUGT: return ARMCC::HI;
1223   case ISD::SETUGE: return ARMCC::HS;
1224   case ISD::SETULT: return ARMCC::LO;
1225   case ISD::SETULE: return ARMCC::LS;
1226   }
1227 }
1228
1229 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1230 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1231                         ARMCC::CondCodes &CondCode2) {
1232   CondCode2 = ARMCC::AL;
1233   switch (CC) {
1234   default: llvm_unreachable("Unknown FP condition!");
1235   case ISD::SETEQ:
1236   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1237   case ISD::SETGT:
1238   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1239   case ISD::SETGE:
1240   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1241   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1242   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1243   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1244   case ISD::SETO:   CondCode = ARMCC::VC; break;
1245   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1246   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1247   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1248   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1249   case ISD::SETLT:
1250   case ISD::SETULT: CondCode = ARMCC::LT; break;
1251   case ISD::SETLE:
1252   case ISD::SETULE: CondCode = ARMCC::LE; break;
1253   case ISD::SETNE:
1254   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1255   }
1256 }
1257
1258 //===----------------------------------------------------------------------===//
1259 //                      Calling Convention Implementation
1260 //===----------------------------------------------------------------------===//
1261
1262 #include "ARMGenCallingConv.inc"
1263
1264 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1265 /// given CallingConvention value.
1266 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1267                                                  bool Return,
1268                                                  bool isVarArg) const {
1269   switch (CC) {
1270   default:
1271     llvm_unreachable("Unsupported calling convention");
1272   case CallingConv::Fast:
1273     if (Subtarget->hasVFP2() && !isVarArg) {
1274       if (!Subtarget->isAAPCS_ABI())
1275         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1276       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1277       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1278     }
1279     // Fallthrough
1280   case CallingConv::C: {
1281     // Use target triple & subtarget features to do actual dispatch.
1282     if (!Subtarget->isAAPCS_ABI())
1283       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1284     else if (Subtarget->hasVFP2() &&
1285              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1286              !isVarArg)
1287       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1288     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1289   }
1290   case CallingConv::ARM_AAPCS_VFP:
1291     if (!isVarArg)
1292       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1293     // Fallthrough
1294   case CallingConv::ARM_AAPCS:
1295     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1296   case CallingConv::ARM_APCS:
1297     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1298   case CallingConv::GHC:
1299     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1300   }
1301 }
1302
1303 /// LowerCallResult - Lower the result values of a call into the
1304 /// appropriate copies out of appropriate physical registers.
1305 SDValue
1306 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1307                                    CallingConv::ID CallConv, bool isVarArg,
1308                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1309                                    SDLoc dl, SelectionDAG &DAG,
1310                                    SmallVectorImpl<SDValue> &InVals,
1311                                    bool isThisReturn, SDValue ThisVal) const {
1312
1313   // Assign locations to each value returned by this call.
1314   SmallVector<CCValAssign, 16> RVLocs;
1315   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1316                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1317   CCInfo.AnalyzeCallResult(Ins,
1318                            CCAssignFnForNode(CallConv, /* Return*/ true,
1319                                              isVarArg));
1320
1321   // Copy all of the result registers out of their specified physreg.
1322   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1323     CCValAssign VA = RVLocs[i];
1324
1325     // Pass 'this' value directly from the argument to return value, to avoid
1326     // reg unit interference
1327     if (i == 0 && isThisReturn) {
1328       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1329              "unexpected return calling convention register assignment");
1330       InVals.push_back(ThisVal);
1331       continue;
1332     }
1333
1334     SDValue Val;
1335     if (VA.needsCustom()) {
1336       // Handle f64 or half of a v2f64.
1337       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1338                                       InFlag);
1339       Chain = Lo.getValue(1);
1340       InFlag = Lo.getValue(2);
1341       VA = RVLocs[++i]; // skip ahead to next loc
1342       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1343                                       InFlag);
1344       Chain = Hi.getValue(1);
1345       InFlag = Hi.getValue(2);
1346       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1347
1348       if (VA.getLocVT() == MVT::v2f64) {
1349         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1350         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1351                           DAG.getConstant(0, MVT::i32));
1352
1353         VA = RVLocs[++i]; // skip ahead to next loc
1354         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1355         Chain = Lo.getValue(1);
1356         InFlag = Lo.getValue(2);
1357         VA = RVLocs[++i]; // skip ahead to next loc
1358         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1359         Chain = Hi.getValue(1);
1360         InFlag = Hi.getValue(2);
1361         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1362         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1363                           DAG.getConstant(1, MVT::i32));
1364       }
1365     } else {
1366       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1367                                InFlag);
1368       Chain = Val.getValue(1);
1369       InFlag = Val.getValue(2);
1370     }
1371
1372     switch (VA.getLocInfo()) {
1373     default: llvm_unreachable("Unknown loc info!");
1374     case CCValAssign::Full: break;
1375     case CCValAssign::BCvt:
1376       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1377       break;
1378     }
1379
1380     InVals.push_back(Val);
1381   }
1382
1383   return Chain;
1384 }
1385
1386 /// LowerMemOpCallTo - Store the argument to the stack.
1387 SDValue
1388 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1389                                     SDValue StackPtr, SDValue Arg,
1390                                     SDLoc dl, SelectionDAG &DAG,
1391                                     const CCValAssign &VA,
1392                                     ISD::ArgFlagsTy Flags) const {
1393   unsigned LocMemOffset = VA.getLocMemOffset();
1394   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1395   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1396   return DAG.getStore(Chain, dl, Arg, PtrOff,
1397                       MachinePointerInfo::getStack(LocMemOffset),
1398                       false, false, 0);
1399 }
1400
1401 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1402                                          SDValue Chain, SDValue &Arg,
1403                                          RegsToPassVector &RegsToPass,
1404                                          CCValAssign &VA, CCValAssign &NextVA,
1405                                          SDValue &StackPtr,
1406                                          SmallVectorImpl<SDValue> &MemOpChains,
1407                                          ISD::ArgFlagsTy Flags) const {
1408
1409   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1410                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1411   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1412
1413   if (NextVA.isRegLoc())
1414     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1415   else {
1416     assert(NextVA.isMemLoc());
1417     if (StackPtr.getNode() == 0)
1418       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1419
1420     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1421                                            dl, DAG, NextVA,
1422                                            Flags));
1423   }
1424 }
1425
1426 /// LowerCall - Lowering a call into a callseq_start <-
1427 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1428 /// nodes.
1429 SDValue
1430 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1431                              SmallVectorImpl<SDValue> &InVals) const {
1432   SelectionDAG &DAG                     = CLI.DAG;
1433   SDLoc &dl                          = CLI.DL;
1434   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1435   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1436   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1437   SDValue Chain                         = CLI.Chain;
1438   SDValue Callee                        = CLI.Callee;
1439   bool &isTailCall                      = CLI.IsTailCall;
1440   CallingConv::ID CallConv              = CLI.CallConv;
1441   bool doesNotRet                       = CLI.DoesNotReturn;
1442   bool isVarArg                         = CLI.IsVarArg;
1443
1444   MachineFunction &MF = DAG.getMachineFunction();
1445   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1446   bool isThisReturn   = false;
1447   bool isSibCall      = false;
1448   // Disable tail calls if they're not supported.
1449   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1450     isTailCall = false;
1451   if (isTailCall) {
1452     // Check if it's really possible to do a tail call.
1453     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1454                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1455                                                    Outs, OutVals, Ins, DAG);
1456     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1457     // detected sibcalls.
1458     if (isTailCall) {
1459       ++NumTailCalls;
1460       isSibCall = true;
1461     }
1462   }
1463
1464   // Analyze operands of the call, assigning locations to each operand.
1465   SmallVector<CCValAssign, 16> ArgLocs;
1466   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1467                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1468   CCInfo.AnalyzeCallOperands(Outs,
1469                              CCAssignFnForNode(CallConv, /* Return*/ false,
1470                                                isVarArg));
1471
1472   // Get a count of how many bytes are to be pushed on the stack.
1473   unsigned NumBytes = CCInfo.getNextStackOffset();
1474
1475   // For tail calls, memory operands are available in our caller's stack.
1476   if (isSibCall)
1477     NumBytes = 0;
1478
1479   // Adjust the stack pointer for the new arguments...
1480   // These operations are automatically eliminated by the prolog/epilog pass
1481   if (!isSibCall)
1482     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1483                                  dl);
1484
1485   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1486
1487   RegsToPassVector RegsToPass;
1488   SmallVector<SDValue, 8> MemOpChains;
1489
1490   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1491   // of tail call optimization, arguments are handled later.
1492   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1493        i != e;
1494        ++i, ++realArgIdx) {
1495     CCValAssign &VA = ArgLocs[i];
1496     SDValue Arg = OutVals[realArgIdx];
1497     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1498     bool isByVal = Flags.isByVal();
1499
1500     // Promote the value if needed.
1501     switch (VA.getLocInfo()) {
1502     default: llvm_unreachable("Unknown loc info!");
1503     case CCValAssign::Full: break;
1504     case CCValAssign::SExt:
1505       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1506       break;
1507     case CCValAssign::ZExt:
1508       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1509       break;
1510     case CCValAssign::AExt:
1511       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1512       break;
1513     case CCValAssign::BCvt:
1514       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1515       break;
1516     }
1517
1518     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1519     if (VA.needsCustom()) {
1520       if (VA.getLocVT() == MVT::v2f64) {
1521         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1522                                   DAG.getConstant(0, MVT::i32));
1523         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1524                                   DAG.getConstant(1, MVT::i32));
1525
1526         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1527                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1528
1529         VA = ArgLocs[++i]; // skip ahead to next loc
1530         if (VA.isRegLoc()) {
1531           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1532                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1533         } else {
1534           assert(VA.isMemLoc());
1535
1536           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1537                                                  dl, DAG, VA, Flags));
1538         }
1539       } else {
1540         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1541                          StackPtr, MemOpChains, Flags);
1542       }
1543     } else if (VA.isRegLoc()) {
1544       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1545         assert(VA.getLocVT() == MVT::i32 &&
1546                "unexpected calling convention register assignment");
1547         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1548                "unexpected use of 'returned'");
1549         isThisReturn = true;
1550       }
1551       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1552     } else if (isByVal) {
1553       assert(VA.isMemLoc());
1554       unsigned offset = 0;
1555
1556       // True if this byval aggregate will be split between registers
1557       // and memory.
1558       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1559       unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1560
1561       if (CurByValIdx < ByValArgsCount) {
1562
1563         unsigned RegBegin, RegEnd;
1564         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1565
1566         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1567         unsigned int i, j;
1568         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1569           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1570           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1571           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1572                                      MachinePointerInfo(),
1573                                      false, false, false,
1574                                      DAG.InferPtrAlignment(AddArg));
1575           MemOpChains.push_back(Load.getValue(1));
1576           RegsToPass.push_back(std::make_pair(j, Load));
1577         }
1578
1579         // If parameter size outsides register area, "offset" value
1580         // helps us to calculate stack slot for remained part properly.
1581         offset = RegEnd - RegBegin;
1582
1583         CCInfo.nextInRegsParam();
1584       }
1585
1586       if (Flags.getByValSize() > 4*offset) {
1587         unsigned LocMemOffset = VA.getLocMemOffset();
1588         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1589         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1590                                   StkPtrOff);
1591         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1592         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1593         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1594                                            MVT::i32);
1595         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1596
1597         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1598         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1599         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1600                                           Ops, array_lengthof(Ops)));
1601       }
1602     } else if (!isSibCall) {
1603       assert(VA.isMemLoc());
1604
1605       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1606                                              dl, DAG, VA, Flags));
1607     }
1608   }
1609
1610   if (!MemOpChains.empty())
1611     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1612                         &MemOpChains[0], MemOpChains.size());
1613
1614   // Build a sequence of copy-to-reg nodes chained together with token chain
1615   // and flag operands which copy the outgoing args into the appropriate regs.
1616   SDValue InFlag;
1617   // Tail call byval lowering might overwrite argument registers so in case of
1618   // tail call optimization the copies to registers are lowered later.
1619   if (!isTailCall)
1620     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1621       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1622                                RegsToPass[i].second, InFlag);
1623       InFlag = Chain.getValue(1);
1624     }
1625
1626   // For tail calls lower the arguments to the 'real' stack slot.
1627   if (isTailCall) {
1628     // Force all the incoming stack arguments to be loaded from the stack
1629     // before any new outgoing arguments are stored to the stack, because the
1630     // outgoing stack slots may alias the incoming argument stack slots, and
1631     // the alias isn't otherwise explicit. This is slightly more conservative
1632     // than necessary, because it means that each store effectively depends
1633     // on every argument instead of just those arguments it would clobber.
1634
1635     // Do not flag preceding copytoreg stuff together with the following stuff.
1636     InFlag = SDValue();
1637     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1638       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1639                                RegsToPass[i].second, InFlag);
1640       InFlag = Chain.getValue(1);
1641     }
1642     InFlag = SDValue();
1643   }
1644
1645   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1646   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1647   // node so that legalize doesn't hack it.
1648   bool isDirect = false;
1649   bool isARMFunc = false;
1650   bool isLocalARMFunc = false;
1651   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1652
1653   if (EnableARMLongCalls) {
1654     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1655             && "long-calls with non-static relocation model!");
1656     // Handle a global address or an external symbol. If it's not one of
1657     // those, the target's already in a register, so we don't need to do
1658     // anything extra.
1659     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1660       const GlobalValue *GV = G->getGlobal();
1661       // Create a constant pool entry for the callee address
1662       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1663       ARMConstantPoolValue *CPV =
1664         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1665
1666       // Get the address of the callee into a register
1667       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1668       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1669       Callee = DAG.getLoad(getPointerTy(), dl,
1670                            DAG.getEntryNode(), CPAddr,
1671                            MachinePointerInfo::getConstantPool(),
1672                            false, false, false, 0);
1673     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1674       const char *Sym = S->getSymbol();
1675
1676       // Create a constant pool entry for the callee address
1677       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1678       ARMConstantPoolValue *CPV =
1679         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1680                                       ARMPCLabelIndex, 0);
1681       // Get the address of the callee into a register
1682       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1683       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1684       Callee = DAG.getLoad(getPointerTy(), dl,
1685                            DAG.getEntryNode(), CPAddr,
1686                            MachinePointerInfo::getConstantPool(),
1687                            false, false, false, 0);
1688     }
1689   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1690     const GlobalValue *GV = G->getGlobal();
1691     isDirect = true;
1692     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1693     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1694                    getTargetMachine().getRelocationModel() != Reloc::Static;
1695     isARMFunc = !Subtarget->isThumb() || isStub;
1696     // ARM call to a local ARM function is predicable.
1697     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1698     // tBX takes a register source operand.
1699     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1700       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1701       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1702                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy()));
1703     } else {
1704       // On ELF targets for PIC code, direct calls should go through the PLT
1705       unsigned OpFlags = 0;
1706       if (Subtarget->isTargetELF() &&
1707           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1708         OpFlags = ARMII::MO_PLT;
1709       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1710     }
1711   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1712     isDirect = true;
1713     bool isStub = Subtarget->isTargetMachO() &&
1714                   getTargetMachine().getRelocationModel() != Reloc::Static;
1715     isARMFunc = !Subtarget->isThumb() || isStub;
1716     // tBX takes a register source operand.
1717     const char *Sym = S->getSymbol();
1718     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1719       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1720       ARMConstantPoolValue *CPV =
1721         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1722                                       ARMPCLabelIndex, 4);
1723       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1724       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1725       Callee = DAG.getLoad(getPointerTy(), dl,
1726                            DAG.getEntryNode(), CPAddr,
1727                            MachinePointerInfo::getConstantPool(),
1728                            false, false, false, 0);
1729       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1730       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1731                            getPointerTy(), Callee, PICLabel);
1732     } else {
1733       unsigned OpFlags = 0;
1734       // On ELF targets for PIC code, direct calls should go through the PLT
1735       if (Subtarget->isTargetELF() &&
1736                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1737         OpFlags = ARMII::MO_PLT;
1738       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1739     }
1740   }
1741
1742   // FIXME: handle tail calls differently.
1743   unsigned CallOpc;
1744   bool HasMinSizeAttr = Subtarget->isMinSize();
1745   if (Subtarget->isThumb()) {
1746     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1747       CallOpc = ARMISD::CALL_NOLINK;
1748     else
1749       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1750   } else {
1751     if (!isDirect && !Subtarget->hasV5TOps())
1752       CallOpc = ARMISD::CALL_NOLINK;
1753     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1754                // Emit regular call when code size is the priority
1755                !HasMinSizeAttr)
1756       // "mov lr, pc; b _foo" to avoid confusing the RSP
1757       CallOpc = ARMISD::CALL_NOLINK;
1758     else
1759       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1760   }
1761
1762   std::vector<SDValue> Ops;
1763   Ops.push_back(Chain);
1764   Ops.push_back(Callee);
1765
1766   // Add argument registers to the end of the list so that they are known live
1767   // into the call.
1768   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1769     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1770                                   RegsToPass[i].second.getValueType()));
1771
1772   // Add a register mask operand representing the call-preserved registers.
1773   if (!isTailCall) {
1774     const uint32_t *Mask;
1775     const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1776     const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1777     if (isThisReturn) {
1778       // For 'this' returns, use the R0-preserving mask if applicable
1779       Mask = ARI->getThisReturnPreservedMask(CallConv);
1780       if (!Mask) {
1781         // Set isThisReturn to false if the calling convention is not one that
1782         // allows 'returned' to be modeled in this way, so LowerCallResult does
1783         // not try to pass 'this' straight through
1784         isThisReturn = false;
1785         Mask = ARI->getCallPreservedMask(CallConv);
1786       }
1787     } else
1788       Mask = ARI->getCallPreservedMask(CallConv);
1789
1790     assert(Mask && "Missing call preserved mask for calling convention");
1791     Ops.push_back(DAG.getRegisterMask(Mask));
1792   }
1793
1794   if (InFlag.getNode())
1795     Ops.push_back(InFlag);
1796
1797   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1798   if (isTailCall)
1799     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1800
1801   // Returns a chain and a flag for retval copy to use.
1802   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1803   InFlag = Chain.getValue(1);
1804
1805   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1806                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1807   if (!Ins.empty())
1808     InFlag = Chain.getValue(1);
1809
1810   // Handle result values, copying them out of physregs into vregs that we
1811   // return.
1812   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1813                          InVals, isThisReturn,
1814                          isThisReturn ? OutVals[0] : SDValue());
1815 }
1816
1817 /// HandleByVal - Every parameter *after* a byval parameter is passed
1818 /// on the stack.  Remember the next parameter register to allocate,
1819 /// and then confiscate the rest of the parameter registers to insure
1820 /// this.
1821 void
1822 ARMTargetLowering::HandleByVal(
1823     CCState *State, unsigned &size, unsigned Align) const {
1824   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1825   assert((State->getCallOrPrologue() == Prologue ||
1826           State->getCallOrPrologue() == Call) &&
1827          "unhandled ParmContext");
1828
1829   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1830     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1831       unsigned AlignInRegs = Align / 4;
1832       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1833       for (unsigned i = 0; i < Waste; ++i)
1834         reg = State->AllocateReg(GPRArgRegs, 4);
1835     }
1836     if (reg != 0) {
1837       unsigned excess = 4 * (ARM::R4 - reg);
1838
1839       // Special case when NSAA != SP and parameter size greater than size of
1840       // all remained GPR regs. In that case we can't split parameter, we must
1841       // send it to stack. We also must set NCRN to R4, so waste all
1842       // remained registers.
1843       const unsigned NSAAOffset = State->getNextStackOffset();
1844       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1845         while (State->AllocateReg(GPRArgRegs, 4))
1846           ;
1847         return;
1848       }
1849
1850       // First register for byval parameter is the first register that wasn't
1851       // allocated before this method call, so it would be "reg".
1852       // If parameter is small enough to be saved in range [reg, r4), then
1853       // the end (first after last) register would be reg + param-size-in-regs,
1854       // else parameter would be splitted between registers and stack,
1855       // end register would be r4 in this case.
1856       unsigned ByValRegBegin = reg;
1857       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1858       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1859       // Note, first register is allocated in the beginning of function already,
1860       // allocate remained amount of registers we need.
1861       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1862         State->AllocateReg(GPRArgRegs, 4);
1863       // A byval parameter that is split between registers and memory needs its
1864       // size truncated here.
1865       // In the case where the entire structure fits in registers, we set the
1866       // size in memory to zero.
1867       if (size < excess)
1868         size = 0;
1869       else
1870         size -= excess;
1871     }
1872   }
1873 }
1874
1875 /// MatchingStackOffset - Return true if the given stack call argument is
1876 /// already available in the same position (relatively) of the caller's
1877 /// incoming argument stack.
1878 static
1879 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1880                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1881                          const TargetInstrInfo *TII) {
1882   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1883   int FI = INT_MAX;
1884   if (Arg.getOpcode() == ISD::CopyFromReg) {
1885     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1886     if (!TargetRegisterInfo::isVirtualRegister(VR))
1887       return false;
1888     MachineInstr *Def = MRI->getVRegDef(VR);
1889     if (!Def)
1890       return false;
1891     if (!Flags.isByVal()) {
1892       if (!TII->isLoadFromStackSlot(Def, FI))
1893         return false;
1894     } else {
1895       return false;
1896     }
1897   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1898     if (Flags.isByVal())
1899       // ByVal argument is passed in as a pointer but it's now being
1900       // dereferenced. e.g.
1901       // define @foo(%struct.X* %A) {
1902       //   tail call @bar(%struct.X* byval %A)
1903       // }
1904       return false;
1905     SDValue Ptr = Ld->getBasePtr();
1906     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1907     if (!FINode)
1908       return false;
1909     FI = FINode->getIndex();
1910   } else
1911     return false;
1912
1913   assert(FI != INT_MAX);
1914   if (!MFI->isFixedObjectIndex(FI))
1915     return false;
1916   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1917 }
1918
1919 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1920 /// for tail call optimization. Targets which want to do tail call
1921 /// optimization should implement this function.
1922 bool
1923 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1924                                                      CallingConv::ID CalleeCC,
1925                                                      bool isVarArg,
1926                                                      bool isCalleeStructRet,
1927                                                      bool isCallerStructRet,
1928                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1929                                     const SmallVectorImpl<SDValue> &OutVals,
1930                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1931                                                      SelectionDAG& DAG) const {
1932   const Function *CallerF = DAG.getMachineFunction().getFunction();
1933   CallingConv::ID CallerCC = CallerF->getCallingConv();
1934   bool CCMatch = CallerCC == CalleeCC;
1935
1936   // Look for obvious safe cases to perform tail call optimization that do not
1937   // require ABI changes. This is what gcc calls sibcall.
1938
1939   // Do not sibcall optimize vararg calls unless the call site is not passing
1940   // any arguments.
1941   if (isVarArg && !Outs.empty())
1942     return false;
1943
1944   // Exception-handling functions need a special set of instructions to indicate
1945   // a return to the hardware. Tail-calling another function would probably
1946   // break this.
1947   if (CallerF->hasFnAttribute("interrupt"))
1948     return false;
1949
1950   // Also avoid sibcall optimization if either caller or callee uses struct
1951   // return semantics.
1952   if (isCalleeStructRet || isCallerStructRet)
1953     return false;
1954
1955   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1956   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1957   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1958   // support in the assembler and linker to be used. This would need to be
1959   // fixed to fully support tail calls in Thumb1.
1960   //
1961   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1962   // LR.  This means if we need to reload LR, it takes an extra instructions,
1963   // which outweighs the value of the tail call; but here we don't know yet
1964   // whether LR is going to be used.  Probably the right approach is to
1965   // generate the tail call here and turn it back into CALL/RET in
1966   // emitEpilogue if LR is used.
1967
1968   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1969   // but we need to make sure there are enough registers; the only valid
1970   // registers are the 4 used for parameters.  We don't currently do this
1971   // case.
1972   if (Subtarget->isThumb1Only())
1973     return false;
1974
1975   // If the calling conventions do not match, then we'd better make sure the
1976   // results are returned in the same way as what the caller expects.
1977   if (!CCMatch) {
1978     SmallVector<CCValAssign, 16> RVLocs1;
1979     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1980                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1981     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1982
1983     SmallVector<CCValAssign, 16> RVLocs2;
1984     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1985                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1986     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1987
1988     if (RVLocs1.size() != RVLocs2.size())
1989       return false;
1990     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1991       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1992         return false;
1993       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1994         return false;
1995       if (RVLocs1[i].isRegLoc()) {
1996         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1997           return false;
1998       } else {
1999         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2000           return false;
2001       }
2002     }
2003   }
2004
2005   // If Caller's vararg or byval argument has been split between registers and
2006   // stack, do not perform tail call, since part of the argument is in caller's
2007   // local frame.
2008   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2009                                       getInfo<ARMFunctionInfo>();
2010   if (AFI_Caller->getArgRegsSaveSize())
2011     return false;
2012
2013   // If the callee takes no arguments then go on to check the results of the
2014   // call.
2015   if (!Outs.empty()) {
2016     // Check if stack adjustment is needed. For now, do not do this if any
2017     // argument is passed on the stack.
2018     SmallVector<CCValAssign, 16> ArgLocs;
2019     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2020                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
2021     CCInfo.AnalyzeCallOperands(Outs,
2022                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2023     if (CCInfo.getNextStackOffset()) {
2024       MachineFunction &MF = DAG.getMachineFunction();
2025
2026       // Check if the arguments are already laid out in the right way as
2027       // the caller's fixed stack objects.
2028       MachineFrameInfo *MFI = MF.getFrameInfo();
2029       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2030       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2031       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2032            i != e;
2033            ++i, ++realArgIdx) {
2034         CCValAssign &VA = ArgLocs[i];
2035         EVT RegVT = VA.getLocVT();
2036         SDValue Arg = OutVals[realArgIdx];
2037         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2038         if (VA.getLocInfo() == CCValAssign::Indirect)
2039           return false;
2040         if (VA.needsCustom()) {
2041           // f64 and vector types are split into multiple registers or
2042           // register/stack-slot combinations.  The types will not match
2043           // the registers; give up on memory f64 refs until we figure
2044           // out what to do about this.
2045           if (!VA.isRegLoc())
2046             return false;
2047           if (!ArgLocs[++i].isRegLoc())
2048             return false;
2049           if (RegVT == MVT::v2f64) {
2050             if (!ArgLocs[++i].isRegLoc())
2051               return false;
2052             if (!ArgLocs[++i].isRegLoc())
2053               return false;
2054           }
2055         } else if (!VA.isRegLoc()) {
2056           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2057                                    MFI, MRI, TII))
2058             return false;
2059         }
2060       }
2061     }
2062   }
2063
2064   return true;
2065 }
2066
2067 bool
2068 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2069                                   MachineFunction &MF, bool isVarArg,
2070                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2071                                   LLVMContext &Context) const {
2072   SmallVector<CCValAssign, 16> RVLocs;
2073   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2074   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2075                                                     isVarArg));
2076 }
2077
2078 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2079                                     SDLoc DL, SelectionDAG &DAG) {
2080   const MachineFunction &MF = DAG.getMachineFunction();
2081   const Function *F = MF.getFunction();
2082
2083   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2084
2085   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2086   // version of the "preferred return address". These offsets affect the return
2087   // instruction if this is a return from PL1 without hypervisor extensions.
2088   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2089   //    SWI:     0      "subs pc, lr, #0"
2090   //    ABORT:   +4     "subs pc, lr, #4"
2091   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2092   // UNDEF varies depending on where the exception came from ARM or Thumb
2093   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2094
2095   int64_t LROffset;
2096   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2097       IntKind == "ABORT")
2098     LROffset = 4;
2099   else if (IntKind == "SWI" || IntKind == "UNDEF")
2100     LROffset = 0;
2101   else
2102     report_fatal_error("Unsupported interrupt attribute. If present, value "
2103                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2104
2105   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2106
2107   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other,
2108                      RetOps.data(), RetOps.size());
2109 }
2110
2111 SDValue
2112 ARMTargetLowering::LowerReturn(SDValue Chain,
2113                                CallingConv::ID CallConv, bool isVarArg,
2114                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2115                                const SmallVectorImpl<SDValue> &OutVals,
2116                                SDLoc dl, SelectionDAG &DAG) const {
2117
2118   // CCValAssign - represent the assignment of the return value to a location.
2119   SmallVector<CCValAssign, 16> RVLocs;
2120
2121   // CCState - Info about the registers and stack slots.
2122   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2123                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2124
2125   // Analyze outgoing return values.
2126   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2127                                                isVarArg));
2128
2129   SDValue Flag;
2130   SmallVector<SDValue, 4> RetOps;
2131   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2132
2133   // Copy the result values into the output registers.
2134   for (unsigned i = 0, realRVLocIdx = 0;
2135        i != RVLocs.size();
2136        ++i, ++realRVLocIdx) {
2137     CCValAssign &VA = RVLocs[i];
2138     assert(VA.isRegLoc() && "Can only return in registers!");
2139
2140     SDValue Arg = OutVals[realRVLocIdx];
2141
2142     switch (VA.getLocInfo()) {
2143     default: llvm_unreachable("Unknown loc info!");
2144     case CCValAssign::Full: break;
2145     case CCValAssign::BCvt:
2146       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2147       break;
2148     }
2149
2150     if (VA.needsCustom()) {
2151       if (VA.getLocVT() == MVT::v2f64) {
2152         // Extract the first half and return it in two registers.
2153         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2154                                    DAG.getConstant(0, MVT::i32));
2155         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2156                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2157
2158         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
2159         Flag = Chain.getValue(1);
2160         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2161         VA = RVLocs[++i]; // skip ahead to next loc
2162         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2163                                  HalfGPRs.getValue(1), Flag);
2164         Flag = Chain.getValue(1);
2165         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2166         VA = RVLocs[++i]; // skip ahead to next loc
2167
2168         // Extract the 2nd half and fall through to handle it as an f64 value.
2169         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2170                           DAG.getConstant(1, MVT::i32));
2171       }
2172       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2173       // available.
2174       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2175                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
2176       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
2177       Flag = Chain.getValue(1);
2178       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2179       VA = RVLocs[++i]; // skip ahead to next loc
2180       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
2181                                Flag);
2182     } else
2183       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2184
2185     // Guarantee that all emitted copies are
2186     // stuck together, avoiding something bad.
2187     Flag = Chain.getValue(1);
2188     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2189   }
2190
2191   // Update chain and glue.
2192   RetOps[0] = Chain;
2193   if (Flag.getNode())
2194     RetOps.push_back(Flag);
2195
2196   // CPUs which aren't M-class use a special sequence to return from
2197   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2198   // though we use "subs pc, lr, #N").
2199   //
2200   // M-class CPUs actually use a normal return sequence with a special
2201   // (hardware-provided) value in LR, so the normal code path works.
2202   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2203       !Subtarget->isMClass()) {
2204     if (Subtarget->isThumb1Only())
2205       report_fatal_error("interrupt attribute is not supported in Thumb1");
2206     return LowerInterruptReturn(RetOps, dl, DAG);
2207   }
2208
2209   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
2210                      RetOps.data(), RetOps.size());
2211 }
2212
2213 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2214   if (N->getNumValues() != 1)
2215     return false;
2216   if (!N->hasNUsesOfValue(1, 0))
2217     return false;
2218
2219   SDValue TCChain = Chain;
2220   SDNode *Copy = *N->use_begin();
2221   if (Copy->getOpcode() == ISD::CopyToReg) {
2222     // If the copy has a glue operand, we conservatively assume it isn't safe to
2223     // perform a tail call.
2224     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2225       return false;
2226     TCChain = Copy->getOperand(0);
2227   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2228     SDNode *VMov = Copy;
2229     // f64 returned in a pair of GPRs.
2230     SmallPtrSet<SDNode*, 2> Copies;
2231     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2232          UI != UE; ++UI) {
2233       if (UI->getOpcode() != ISD::CopyToReg)
2234         return false;
2235       Copies.insert(*UI);
2236     }
2237     if (Copies.size() > 2)
2238       return false;
2239
2240     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2241          UI != UE; ++UI) {
2242       SDValue UseChain = UI->getOperand(0);
2243       if (Copies.count(UseChain.getNode()))
2244         // Second CopyToReg
2245         Copy = *UI;
2246       else
2247         // First CopyToReg
2248         TCChain = UseChain;
2249     }
2250   } else if (Copy->getOpcode() == ISD::BITCAST) {
2251     // f32 returned in a single GPR.
2252     if (!Copy->hasOneUse())
2253       return false;
2254     Copy = *Copy->use_begin();
2255     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2256       return false;
2257     TCChain = Copy->getOperand(0);
2258   } else {
2259     return false;
2260   }
2261
2262   bool HasRet = false;
2263   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2264        UI != UE; ++UI) {
2265     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2266         UI->getOpcode() != ARMISD::INTRET_FLAG)
2267       return false;
2268     HasRet = true;
2269   }
2270
2271   if (!HasRet)
2272     return false;
2273
2274   Chain = TCChain;
2275   return true;
2276 }
2277
2278 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2279   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2280     return false;
2281
2282   if (!CI->isTailCall())
2283     return false;
2284
2285   return !Subtarget->isThumb1Only();
2286 }
2287
2288 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2289 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2290 // one of the above mentioned nodes. It has to be wrapped because otherwise
2291 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2292 // be used to form addressing mode. These wrapped nodes will be selected
2293 // into MOVi.
2294 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2295   EVT PtrVT = Op.getValueType();
2296   // FIXME there is no actual debug info here
2297   SDLoc dl(Op);
2298   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2299   SDValue Res;
2300   if (CP->isMachineConstantPoolEntry())
2301     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2302                                     CP->getAlignment());
2303   else
2304     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2305                                     CP->getAlignment());
2306   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2307 }
2308
2309 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2310   return MachineJumpTableInfo::EK_Inline;
2311 }
2312
2313 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2314                                              SelectionDAG &DAG) const {
2315   MachineFunction &MF = DAG.getMachineFunction();
2316   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2317   unsigned ARMPCLabelIndex = 0;
2318   SDLoc DL(Op);
2319   EVT PtrVT = getPointerTy();
2320   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2321   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2322   SDValue CPAddr;
2323   if (RelocM == Reloc::Static) {
2324     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2325   } else {
2326     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2327     ARMPCLabelIndex = AFI->createPICLabelUId();
2328     ARMConstantPoolValue *CPV =
2329       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2330                                       ARMCP::CPBlockAddress, PCAdj);
2331     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2332   }
2333   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2334   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2335                                MachinePointerInfo::getConstantPool(),
2336                                false, false, false, 0);
2337   if (RelocM == Reloc::Static)
2338     return Result;
2339   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2340   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2341 }
2342
2343 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2344 SDValue
2345 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2346                                                  SelectionDAG &DAG) const {
2347   SDLoc dl(GA);
2348   EVT PtrVT = getPointerTy();
2349   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2350   MachineFunction &MF = DAG.getMachineFunction();
2351   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2352   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2353   ARMConstantPoolValue *CPV =
2354     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2355                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2356   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2357   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2358   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2359                          MachinePointerInfo::getConstantPool(),
2360                          false, false, false, 0);
2361   SDValue Chain = Argument.getValue(1);
2362
2363   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2364   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2365
2366   // call __tls_get_addr.
2367   ArgListTy Args;
2368   ArgListEntry Entry;
2369   Entry.Node = Argument;
2370   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2371   Args.push_back(Entry);
2372   // FIXME: is there useful debug info available here?
2373   TargetLowering::CallLoweringInfo CLI(Chain,
2374                 (Type *) Type::getInt32Ty(*DAG.getContext()),
2375                 false, false, false, false,
2376                 0, CallingConv::C, /*isTailCall=*/false,
2377                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2378                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2379   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2380   return CallResult.first;
2381 }
2382
2383 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2384 // "local exec" model.
2385 SDValue
2386 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2387                                         SelectionDAG &DAG,
2388                                         TLSModel::Model model) const {
2389   const GlobalValue *GV = GA->getGlobal();
2390   SDLoc dl(GA);
2391   SDValue Offset;
2392   SDValue Chain = DAG.getEntryNode();
2393   EVT PtrVT = getPointerTy();
2394   // Get the Thread Pointer
2395   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2396
2397   if (model == TLSModel::InitialExec) {
2398     MachineFunction &MF = DAG.getMachineFunction();
2399     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2400     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2401     // Initial exec model.
2402     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2403     ARMConstantPoolValue *CPV =
2404       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2405                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2406                                       true);
2407     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2408     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2409     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2410                          MachinePointerInfo::getConstantPool(),
2411                          false, false, false, 0);
2412     Chain = Offset.getValue(1);
2413
2414     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2415     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2416
2417     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2418                          MachinePointerInfo::getConstantPool(),
2419                          false, false, false, 0);
2420   } else {
2421     // local exec model
2422     assert(model == TLSModel::LocalExec);
2423     ARMConstantPoolValue *CPV =
2424       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2425     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2426     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2427     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2428                          MachinePointerInfo::getConstantPool(),
2429                          false, false, false, 0);
2430   }
2431
2432   // The address of the thread local variable is the add of the thread
2433   // pointer with the offset of the variable.
2434   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2435 }
2436
2437 SDValue
2438 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2439   // TODO: implement the "local dynamic" model
2440   assert(Subtarget->isTargetELF() &&
2441          "TLS not implemented for non-ELF targets");
2442   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2443
2444   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2445
2446   switch (model) {
2447     case TLSModel::GeneralDynamic:
2448     case TLSModel::LocalDynamic:
2449       return LowerToTLSGeneralDynamicModel(GA, DAG);
2450     case TLSModel::InitialExec:
2451     case TLSModel::LocalExec:
2452       return LowerToTLSExecModels(GA, DAG, model);
2453   }
2454   llvm_unreachable("bogus TLS model");
2455 }
2456
2457 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2458                                                  SelectionDAG &DAG) const {
2459   EVT PtrVT = getPointerTy();
2460   SDLoc dl(Op);
2461   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2462   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2463     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2464     ARMConstantPoolValue *CPV =
2465       ARMConstantPoolConstant::Create(GV,
2466                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2467     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2468     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2469     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2470                                  CPAddr,
2471                                  MachinePointerInfo::getConstantPool(),
2472                                  false, false, false, 0);
2473     SDValue Chain = Result.getValue(1);
2474     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2475     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2476     if (!UseGOTOFF)
2477       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2478                            MachinePointerInfo::getGOT(),
2479                            false, false, false, 0);
2480     return Result;
2481   }
2482
2483   // If we have T2 ops, we can materialize the address directly via movt/movw
2484   // pair. This is always cheaper.
2485   if (Subtarget->useMovt()) {
2486     ++NumMovwMovt;
2487     // FIXME: Once remat is capable of dealing with instructions with register
2488     // operands, expand this into two nodes.
2489     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2490                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2491   } else {
2492     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2493     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2494     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2495                        MachinePointerInfo::getConstantPool(),
2496                        false, false, false, 0);
2497   }
2498 }
2499
2500 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2501                                                     SelectionDAG &DAG) const {
2502   EVT PtrVT = getPointerTy();
2503   SDLoc dl(Op);
2504   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2505   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2506
2507   if (Subtarget->useMovt())
2508     ++NumMovwMovt;
2509
2510   // FIXME: Once remat is capable of dealing with instructions with register
2511   // operands, expand this into multiple nodes
2512   unsigned Wrapper =
2513       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2514
2515   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2516   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2517
2518   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2519     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2520                          MachinePointerInfo::getGOT(), false, false, false, 0);
2521   return Result;
2522 }
2523
2524 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2525                                                     SelectionDAG &DAG) const {
2526   assert(Subtarget->isTargetELF() &&
2527          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2528   MachineFunction &MF = DAG.getMachineFunction();
2529   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2530   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2531   EVT PtrVT = getPointerTy();
2532   SDLoc dl(Op);
2533   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2534   ARMConstantPoolValue *CPV =
2535     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2536                                   ARMPCLabelIndex, PCAdj);
2537   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2538   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2539   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2540                                MachinePointerInfo::getConstantPool(),
2541                                false, false, false, 0);
2542   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2543   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2544 }
2545
2546 SDValue
2547 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2548   SDLoc dl(Op);
2549   SDValue Val = DAG.getConstant(0, MVT::i32);
2550   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2551                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2552                      Op.getOperand(1), Val);
2553 }
2554
2555 SDValue
2556 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2557   SDLoc dl(Op);
2558   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2559                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2560 }
2561
2562 SDValue
2563 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2564                                           const ARMSubtarget *Subtarget) const {
2565   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2566   SDLoc dl(Op);
2567   switch (IntNo) {
2568   default: return SDValue();    // Don't custom lower most intrinsics.
2569   case Intrinsic::arm_thread_pointer: {
2570     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2571     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2572   }
2573   case Intrinsic::eh_sjlj_lsda: {
2574     MachineFunction &MF = DAG.getMachineFunction();
2575     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2576     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2577     EVT PtrVT = getPointerTy();
2578     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2579     SDValue CPAddr;
2580     unsigned PCAdj = (RelocM != Reloc::PIC_)
2581       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2582     ARMConstantPoolValue *CPV =
2583       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2584                                       ARMCP::CPLSDA, PCAdj);
2585     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2586     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2587     SDValue Result =
2588       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2589                   MachinePointerInfo::getConstantPool(),
2590                   false, false, false, 0);
2591
2592     if (RelocM == Reloc::PIC_) {
2593       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2594       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2595     }
2596     return Result;
2597   }
2598   case Intrinsic::arm_neon_vmulls:
2599   case Intrinsic::arm_neon_vmullu: {
2600     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2601       ? ARMISD::VMULLs : ARMISD::VMULLu;
2602     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2603                        Op.getOperand(1), Op.getOperand(2));
2604   }
2605   }
2606 }
2607
2608 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2609                                  const ARMSubtarget *Subtarget) {
2610   // FIXME: handle "fence singlethread" more efficiently.
2611   SDLoc dl(Op);
2612   if (!Subtarget->hasDataBarrier()) {
2613     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2614     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2615     // here.
2616     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2617            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2618     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2619                        DAG.getConstant(0, MVT::i32));
2620   }
2621
2622   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2623   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2624   unsigned Domain = ARM_MB::ISH;
2625   if (Subtarget->isMClass()) {
2626     // Only a full system barrier exists in the M-class architectures.
2627     Domain = ARM_MB::SY;
2628   } else if (Subtarget->isSwift() && Ord == Release) {
2629     // Swift happens to implement ISHST barriers in a way that's compatible with
2630     // Release semantics but weaker than ISH so we'd be fools not to use
2631     // it. Beware: other processors probably don't!
2632     Domain = ARM_MB::ISHST;
2633   }
2634
2635   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2636                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2637                      DAG.getConstant(Domain, MVT::i32));
2638 }
2639
2640 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2641                              const ARMSubtarget *Subtarget) {
2642   // ARM pre v5TE and Thumb1 does not have preload instructions.
2643   if (!(Subtarget->isThumb2() ||
2644         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2645     // Just preserve the chain.
2646     return Op.getOperand(0);
2647
2648   SDLoc dl(Op);
2649   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2650   if (!isRead &&
2651       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2652     // ARMv7 with MP extension has PLDW.
2653     return Op.getOperand(0);
2654
2655   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2656   if (Subtarget->isThumb()) {
2657     // Invert the bits.
2658     isRead = ~isRead & 1;
2659     isData = ~isData & 1;
2660   }
2661
2662   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2663                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2664                      DAG.getConstant(isData, MVT::i32));
2665 }
2666
2667 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2668   MachineFunction &MF = DAG.getMachineFunction();
2669   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2670
2671   // vastart just stores the address of the VarArgsFrameIndex slot into the
2672   // memory location argument.
2673   SDLoc dl(Op);
2674   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2675   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2676   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2677   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2678                       MachinePointerInfo(SV), false, false, 0);
2679 }
2680
2681 SDValue
2682 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2683                                         SDValue &Root, SelectionDAG &DAG,
2684                                         SDLoc dl) const {
2685   MachineFunction &MF = DAG.getMachineFunction();
2686   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2687
2688   const TargetRegisterClass *RC;
2689   if (AFI->isThumb1OnlyFunction())
2690     RC = &ARM::tGPRRegClass;
2691   else
2692     RC = &ARM::GPRRegClass;
2693
2694   // Transform the arguments stored in physical registers into virtual ones.
2695   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2696   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2697
2698   SDValue ArgValue2;
2699   if (NextVA.isMemLoc()) {
2700     MachineFrameInfo *MFI = MF.getFrameInfo();
2701     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2702
2703     // Create load node to retrieve arguments from the stack.
2704     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2705     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2706                             MachinePointerInfo::getFixedStack(FI),
2707                             false, false, false, 0);
2708   } else {
2709     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2710     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2711   }
2712
2713   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2714 }
2715
2716 void
2717 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2718                                   unsigned InRegsParamRecordIdx,
2719                                   unsigned ArgSize,
2720                                   unsigned &ArgRegsSize,
2721                                   unsigned &ArgRegsSaveSize)
2722   const {
2723   unsigned NumGPRs;
2724   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2725     unsigned RBegin, REnd;
2726     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2727     NumGPRs = REnd - RBegin;
2728   } else {
2729     unsigned int firstUnalloced;
2730     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2731                                                 sizeof(GPRArgRegs) /
2732                                                 sizeof(GPRArgRegs[0]));
2733     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2734   }
2735
2736   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2737   ArgRegsSize = NumGPRs * 4;
2738
2739   // If parameter is split between stack and GPRs...
2740   if (NumGPRs && Align > 4 &&
2741       (ArgRegsSize < ArgSize ||
2742         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2743     // Add padding for part of param recovered from GPRs.  For example,
2744     // if Align == 8, its last byte must be at address K*8 - 1.
2745     // We need to do it, since remained (stack) part of parameter has
2746     // stack alignment, and we need to "attach" "GPRs head" without gaps
2747     // to it:
2748     // Stack:
2749     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2750     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2751     //
2752     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2753     unsigned Padding =
2754         OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2755     ArgRegsSaveSize = ArgRegsSize + Padding;
2756   } else
2757     // We don't need to extend regs save size for byval parameters if they
2758     // are passed via GPRs only.
2759     ArgRegsSaveSize = ArgRegsSize;
2760 }
2761
2762 // The remaining GPRs hold either the beginning of variable-argument
2763 // data, or the beginning of an aggregate passed by value (usually
2764 // byval).  Either way, we allocate stack slots adjacent to the data
2765 // provided by our caller, and store the unallocated registers there.
2766 // If this is a variadic function, the va_list pointer will begin with
2767 // these values; otherwise, this reassembles a (byval) structure that
2768 // was split between registers and memory.
2769 // Return: The frame index registers were stored into.
2770 int
2771 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2772                                   SDLoc dl, SDValue &Chain,
2773                                   const Value *OrigArg,
2774                                   unsigned InRegsParamRecordIdx,
2775                                   unsigned OffsetFromOrigArg,
2776                                   unsigned ArgOffset,
2777                                   unsigned ArgSize,
2778                                   bool ForceMutable,
2779                                   unsigned ByValStoreOffset,
2780                                   unsigned TotalArgRegsSaveSize) const {
2781
2782   // Currently, two use-cases possible:
2783   // Case #1. Non-var-args function, and we meet first byval parameter.
2784   //          Setup first unallocated register as first byval register;
2785   //          eat all remained registers
2786   //          (these two actions are performed by HandleByVal method).
2787   //          Then, here, we initialize stack frame with
2788   //          "store-reg" instructions.
2789   // Case #2. Var-args function, that doesn't contain byval parameters.
2790   //          The same: eat all remained unallocated registers,
2791   //          initialize stack frame.
2792
2793   MachineFunction &MF = DAG.getMachineFunction();
2794   MachineFrameInfo *MFI = MF.getFrameInfo();
2795   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2796   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2797   unsigned RBegin, REnd;
2798   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2799     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2800     firstRegToSaveIndex = RBegin - ARM::R0;
2801     lastRegToSaveIndex = REnd - ARM::R0;
2802   } else {
2803     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2804       (GPRArgRegs, array_lengthof(GPRArgRegs));
2805     lastRegToSaveIndex = 4;
2806   }
2807
2808   unsigned ArgRegsSize, ArgRegsSaveSize;
2809   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2810                  ArgRegsSize, ArgRegsSaveSize);
2811
2812   // Store any by-val regs to their spots on the stack so that they may be
2813   // loaded by deferencing the result of formal parameter pointer or va_next.
2814   // Note: once stack area for byval/varargs registers
2815   // was initialized, it can't be initialized again.
2816   if (ArgRegsSaveSize) {
2817     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2818
2819     if (Padding) {
2820       assert(AFI->getStoredByValParamsPadding() == 0 &&
2821              "The only parameter may be padded.");
2822       AFI->setStoredByValParamsPadding(Padding);
2823     }
2824
2825     int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2826                                             Padding +
2827                                               ByValStoreOffset -
2828                                               (int64_t)TotalArgRegsSaveSize,
2829                                             false);
2830     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2831     if (Padding) {
2832        MFI->CreateFixedObject(Padding,
2833                               ArgOffset + ByValStoreOffset -
2834                                 (int64_t)ArgRegsSaveSize,
2835                               false);
2836     }
2837
2838     SmallVector<SDValue, 4> MemOps;
2839     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2840          ++firstRegToSaveIndex, ++i) {
2841       const TargetRegisterClass *RC;
2842       if (AFI->isThumb1OnlyFunction())
2843         RC = &ARM::tGPRRegClass;
2844       else
2845         RC = &ARM::GPRRegClass;
2846
2847       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2848       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2849       SDValue Store =
2850         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2851                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2852                      false, false, 0);
2853       MemOps.push_back(Store);
2854       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2855                         DAG.getConstant(4, getPointerTy()));
2856     }
2857
2858     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2859
2860     if (!MemOps.empty())
2861       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2862                           &MemOps[0], MemOps.size());
2863     return FrameIndex;
2864   } else {
2865     if (ArgSize == 0) {
2866       // We cannot allocate a zero-byte object for the first variadic argument,
2867       // so just make up a size.
2868       ArgSize = 4;
2869     }
2870     // This will point to the next argument passed via stack.
2871     return MFI->CreateFixedObject(
2872       ArgSize, ArgOffset, !ForceMutable);
2873   }
2874 }
2875
2876 // Setup stack frame, the va_list pointer will start from.
2877 void
2878 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2879                                         SDLoc dl, SDValue &Chain,
2880                                         unsigned ArgOffset,
2881                                         unsigned TotalArgRegsSaveSize,
2882                                         bool ForceMutable) const {
2883   MachineFunction &MF = DAG.getMachineFunction();
2884   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2885
2886   // Try to store any remaining integer argument regs
2887   // to their spots on the stack so that they may be loaded by deferencing
2888   // the result of va_next.
2889   // If there is no regs to be stored, just point address after last
2890   // argument passed via stack.
2891   int FrameIndex =
2892     StoreByValRegs(CCInfo, DAG, dl, Chain, 0, CCInfo.getInRegsParamsCount(),
2893                    0, ArgOffset, 0, ForceMutable, 0, TotalArgRegsSaveSize);
2894
2895   AFI->setVarArgsFrameIndex(FrameIndex);
2896 }
2897
2898 SDValue
2899 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2900                                         CallingConv::ID CallConv, bool isVarArg,
2901                                         const SmallVectorImpl<ISD::InputArg>
2902                                           &Ins,
2903                                         SDLoc dl, SelectionDAG &DAG,
2904                                         SmallVectorImpl<SDValue> &InVals)
2905                                           const {
2906   MachineFunction &MF = DAG.getMachineFunction();
2907   MachineFrameInfo *MFI = MF.getFrameInfo();
2908
2909   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2910
2911   // Assign locations to all of the incoming arguments.
2912   SmallVector<CCValAssign, 16> ArgLocs;
2913   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2914                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2915   CCInfo.AnalyzeFormalArguments(Ins,
2916                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2917                                                   isVarArg));
2918
2919   SmallVector<SDValue, 16> ArgValues;
2920   int lastInsIndex = -1;
2921   SDValue ArgValue;
2922   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2923   unsigned CurArgIdx = 0;
2924
2925   // Initially ArgRegsSaveSize is zero.
2926   // Then we increase this value each time we meet byval parameter.
2927   // We also increase this value in case of varargs function.
2928   AFI->setArgRegsSaveSize(0);
2929
2930   unsigned ByValStoreOffset = 0;
2931   unsigned TotalArgRegsSaveSize = 0;
2932   unsigned ArgRegsSaveSizeMaxAlign = 4;
2933
2934   // Calculate the amount of stack space that we need to allocate to store
2935   // byval and variadic arguments that are passed in registers.
2936   // We need to know this before we allocate the first byval or variadic
2937   // argument, as they will be allocated a stack slot below the CFA (Canonical
2938   // Frame Address, the stack pointer at entry to the function).
2939   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2940     CCValAssign &VA = ArgLocs[i];
2941     if (VA.isMemLoc()) {
2942       int index = VA.getValNo();
2943       if (index != lastInsIndex) {
2944         ISD::ArgFlagsTy Flags = Ins[index].Flags;
2945         if (Flags.isByVal()) {
2946           unsigned ExtraArgRegsSize;
2947           unsigned ExtraArgRegsSaveSize;
2948           computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
2949                          Flags.getByValSize(),
2950                          ExtraArgRegsSize, ExtraArgRegsSaveSize);
2951
2952           TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2953           if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
2954               ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
2955           CCInfo.nextInRegsParam();
2956         }
2957         lastInsIndex = index;
2958       }
2959     }
2960   }
2961   CCInfo.rewindByValRegsInfo();
2962   lastInsIndex = -1;
2963   if (isVarArg) {
2964     unsigned ExtraArgRegsSize;
2965     unsigned ExtraArgRegsSaveSize;
2966     computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
2967                    ExtraArgRegsSize, ExtraArgRegsSaveSize);
2968     TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2969   }
2970   // If the arg regs save area contains N-byte aligned values, the
2971   // bottom of it must be at least N-byte aligned.
2972   TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
2973   TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
2974
2975   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2976     CCValAssign &VA = ArgLocs[i];
2977     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2978     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2979     // Arguments stored in registers.
2980     if (VA.isRegLoc()) {
2981       EVT RegVT = VA.getLocVT();
2982
2983       if (VA.needsCustom()) {
2984         // f64 and vector types are split up into multiple registers or
2985         // combinations of registers and stack slots.
2986         if (VA.getLocVT() == MVT::v2f64) {
2987           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2988                                                    Chain, DAG, dl);
2989           VA = ArgLocs[++i]; // skip ahead to next loc
2990           SDValue ArgValue2;
2991           if (VA.isMemLoc()) {
2992             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2993             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2994             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2995                                     MachinePointerInfo::getFixedStack(FI),
2996                                     false, false, false, 0);
2997           } else {
2998             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2999                                              Chain, DAG, dl);
3000           }
3001           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3002           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3003                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3004           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3005                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3006         } else
3007           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3008
3009       } else {
3010         const TargetRegisterClass *RC;
3011
3012         if (RegVT == MVT::f32)
3013           RC = &ARM::SPRRegClass;
3014         else if (RegVT == MVT::f64)
3015           RC = &ARM::DPRRegClass;
3016         else if (RegVT == MVT::v2f64)
3017           RC = &ARM::QPRRegClass;
3018         else if (RegVT == MVT::i32)
3019           RC = AFI->isThumb1OnlyFunction() ?
3020             (const TargetRegisterClass*)&ARM::tGPRRegClass :
3021             (const TargetRegisterClass*)&ARM::GPRRegClass;
3022         else
3023           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3024
3025         // Transform the arguments in physical registers into virtual ones.
3026         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3027         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3028       }
3029
3030       // If this is an 8 or 16-bit value, it is really passed promoted
3031       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3032       // truncate to the right size.
3033       switch (VA.getLocInfo()) {
3034       default: llvm_unreachable("Unknown loc info!");
3035       case CCValAssign::Full: break;
3036       case CCValAssign::BCvt:
3037         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3038         break;
3039       case CCValAssign::SExt:
3040         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3041                                DAG.getValueType(VA.getValVT()));
3042         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3043         break;
3044       case CCValAssign::ZExt:
3045         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3046                                DAG.getValueType(VA.getValVT()));
3047         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3048         break;
3049       }
3050
3051       InVals.push_back(ArgValue);
3052
3053     } else { // VA.isRegLoc()
3054
3055       // sanity check
3056       assert(VA.isMemLoc());
3057       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3058
3059       int index = ArgLocs[i].getValNo();
3060
3061       // Some Ins[] entries become multiple ArgLoc[] entries.
3062       // Process them only once.
3063       if (index != lastInsIndex)
3064         {
3065           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3066           // FIXME: For now, all byval parameter objects are marked mutable.
3067           // This can be changed with more analysis.
3068           // In case of tail call optimization mark all arguments mutable.
3069           // Since they could be overwritten by lowering of arguments in case of
3070           // a tail call.
3071           if (Flags.isByVal()) {
3072             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3073
3074             ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3075             int FrameIndex = StoreByValRegs(
3076                 CCInfo, DAG, dl, Chain, CurOrigArg,
3077                 CurByValIndex,
3078                 Ins[VA.getValNo()].PartOffset,
3079                 VA.getLocMemOffset(),
3080                 Flags.getByValSize(),
3081                 true /*force mutable frames*/,
3082                 ByValStoreOffset,
3083                 TotalArgRegsSaveSize);
3084             ByValStoreOffset += Flags.getByValSize();
3085             ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3086             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3087             CCInfo.nextInRegsParam();
3088           } else {
3089             unsigned FIOffset = VA.getLocMemOffset();
3090             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3091                                             FIOffset, true);
3092
3093             // Create load nodes to retrieve arguments from the stack.
3094             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3095             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3096                                          MachinePointerInfo::getFixedStack(FI),
3097                                          false, false, false, 0));
3098           }
3099           lastInsIndex = index;
3100         }
3101     }
3102   }
3103
3104   // varargs
3105   if (isVarArg)
3106     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3107                          CCInfo.getNextStackOffset(),
3108                          TotalArgRegsSaveSize);
3109
3110   return Chain;
3111 }
3112
3113 /// isFloatingPointZero - Return true if this is +0.0.
3114 static bool isFloatingPointZero(SDValue Op) {
3115   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3116     return CFP->getValueAPF().isPosZero();
3117   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3118     // Maybe this has already been legalized into the constant pool?
3119     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3120       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3121       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3122         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3123           return CFP->getValueAPF().isPosZero();
3124     }
3125   }
3126   return false;
3127 }
3128
3129 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3130 /// the given operands.
3131 SDValue
3132 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3133                              SDValue &ARMcc, SelectionDAG &DAG,
3134                              SDLoc dl) const {
3135   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3136     unsigned C = RHSC->getZExtValue();
3137     if (!isLegalICmpImmediate(C)) {
3138       // Constant does not fit, try adjusting it by one?
3139       switch (CC) {
3140       default: break;
3141       case ISD::SETLT:
3142       case ISD::SETGE:
3143         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3144           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3145           RHS = DAG.getConstant(C-1, MVT::i32);
3146         }
3147         break;
3148       case ISD::SETULT:
3149       case ISD::SETUGE:
3150         if (C != 0 && isLegalICmpImmediate(C-1)) {
3151           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3152           RHS = DAG.getConstant(C-1, MVT::i32);
3153         }
3154         break;
3155       case ISD::SETLE:
3156       case ISD::SETGT:
3157         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3158           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3159           RHS = DAG.getConstant(C+1, MVT::i32);
3160         }
3161         break;
3162       case ISD::SETULE:
3163       case ISD::SETUGT:
3164         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3165           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3166           RHS = DAG.getConstant(C+1, MVT::i32);
3167         }
3168         break;
3169       }
3170     }
3171   }
3172
3173   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3174   ARMISD::NodeType CompareType;
3175   switch (CondCode) {
3176   default:
3177     CompareType = ARMISD::CMP;
3178     break;
3179   case ARMCC::EQ:
3180   case ARMCC::NE:
3181     // Uses only Z Flag
3182     CompareType = ARMISD::CMPZ;
3183     break;
3184   }
3185   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3186   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3187 }
3188
3189 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3190 SDValue
3191 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3192                              SDLoc dl) const {
3193   SDValue Cmp;
3194   if (!isFloatingPointZero(RHS))
3195     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3196   else
3197     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3198   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3199 }
3200
3201 /// duplicateCmp - Glue values can have only one use, so this function
3202 /// duplicates a comparison node.
3203 SDValue
3204 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3205   unsigned Opc = Cmp.getOpcode();
3206   SDLoc DL(Cmp);
3207   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3208     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3209
3210   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3211   Cmp = Cmp.getOperand(0);
3212   Opc = Cmp.getOpcode();
3213   if (Opc == ARMISD::CMPFP)
3214     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3215   else {
3216     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3217     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3218   }
3219   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3220 }
3221
3222 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3223   SDValue Cond = Op.getOperand(0);
3224   SDValue SelectTrue = Op.getOperand(1);
3225   SDValue SelectFalse = Op.getOperand(2);
3226   SDLoc dl(Op);
3227
3228   // Convert:
3229   //
3230   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3231   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3232   //
3233   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3234     const ConstantSDNode *CMOVTrue =
3235       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3236     const ConstantSDNode *CMOVFalse =
3237       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3238
3239     if (CMOVTrue && CMOVFalse) {
3240       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3241       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3242
3243       SDValue True;
3244       SDValue False;
3245       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3246         True = SelectTrue;
3247         False = SelectFalse;
3248       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3249         True = SelectFalse;
3250         False = SelectTrue;
3251       }
3252
3253       if (True.getNode() && False.getNode()) {
3254         EVT VT = Op.getValueType();
3255         SDValue ARMcc = Cond.getOperand(2);
3256         SDValue CCR = Cond.getOperand(3);
3257         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3258         assert(True.getValueType() == VT);
3259         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3260       }
3261     }
3262   }
3263
3264   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3265   // undefined bits before doing a full-word comparison with zero.
3266   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3267                      DAG.getConstant(1, Cond.getValueType()));
3268
3269   return DAG.getSelectCC(dl, Cond,
3270                          DAG.getConstant(0, Cond.getValueType()),
3271                          SelectTrue, SelectFalse, ISD::SETNE);
3272 }
3273
3274 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3275   if (CC == ISD::SETNE)
3276     return ISD::SETEQ;
3277   return ISD::getSetCCInverse(CC, true);
3278 }
3279
3280 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3281                                  bool &swpCmpOps, bool &swpVselOps) {
3282   // Start by selecting the GE condition code for opcodes that return true for
3283   // 'equality'
3284   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3285       CC == ISD::SETULE)
3286     CondCode = ARMCC::GE;
3287
3288   // and GT for opcodes that return false for 'equality'.
3289   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3290            CC == ISD::SETULT)
3291     CondCode = ARMCC::GT;
3292
3293   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3294   // to swap the compare operands.
3295   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3296       CC == ISD::SETULT)
3297     swpCmpOps = true;
3298
3299   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3300   // If we have an unordered opcode, we need to swap the operands to the VSEL
3301   // instruction (effectively negating the condition).
3302   //
3303   // This also has the effect of swapping which one of 'less' or 'greater'
3304   // returns true, so we also swap the compare operands. It also switches
3305   // whether we return true for 'equality', so we compensate by picking the
3306   // opposite condition code to our original choice.
3307   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3308       CC == ISD::SETUGT) {
3309     swpCmpOps = !swpCmpOps;
3310     swpVselOps = !swpVselOps;
3311     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3312   }
3313
3314   // 'ordered' is 'anything but unordered', so use the VS condition code and
3315   // swap the VSEL operands.
3316   if (CC == ISD::SETO) {
3317     CondCode = ARMCC::VS;
3318     swpVselOps = true;
3319   }
3320
3321   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3322   // code and swap the VSEL operands.
3323   if (CC == ISD::SETUNE) {
3324     CondCode = ARMCC::EQ;
3325     swpVselOps = true;
3326   }
3327 }
3328
3329 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3330   EVT VT = Op.getValueType();
3331   SDValue LHS = Op.getOperand(0);
3332   SDValue RHS = Op.getOperand(1);
3333   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3334   SDValue TrueVal = Op.getOperand(2);
3335   SDValue FalseVal = Op.getOperand(3);
3336   SDLoc dl(Op);
3337
3338   if (LHS.getValueType() == MVT::i32) {
3339     // Try to generate VSEL on ARMv8.
3340     // The VSEL instruction can't use all the usual ARM condition
3341     // codes: it only has two bits to select the condition code, so it's
3342     // constrained to use only GE, GT, VS and EQ.
3343     //
3344     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3345     // swap the operands of the previous compare instruction (effectively
3346     // inverting the compare condition, swapping 'less' and 'greater') and
3347     // sometimes need to swap the operands to the VSEL (which inverts the
3348     // condition in the sense of firing whenever the previous condition didn't)
3349     if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3350                                       TrueVal.getValueType() == MVT::f64)) {
3351       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3352       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3353           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3354         CC = getInverseCCForVSEL(CC);
3355         std::swap(TrueVal, FalseVal);
3356       }
3357     }
3358
3359     SDValue ARMcc;
3360     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3361     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3362     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3363                        Cmp);
3364   }
3365
3366   ARMCC::CondCodes CondCode, CondCode2;
3367   FPCCToARMCC(CC, CondCode, CondCode2);
3368
3369   // Try to generate VSEL on ARMv8.
3370   if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3371                                     TrueVal.getValueType() == MVT::f64)) {
3372     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3373     // same operands, as follows:
3374     //   c = fcmp [ogt, olt, ugt, ult] a, b
3375     //   select c, a, b
3376     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3377     // handled differently than the original code sequence.
3378     if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3379         RHS == FalseVal) {
3380       if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3381         return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3382       if (CC == ISD::SETOLT || CC == ISD::SETULT)
3383         return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3384     }
3385
3386     bool swpCmpOps = false;
3387     bool swpVselOps = false;
3388     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3389
3390     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3391         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3392       if (swpCmpOps)
3393         std::swap(LHS, RHS);
3394       if (swpVselOps)
3395         std::swap(TrueVal, FalseVal);
3396     }
3397   }
3398
3399   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3400   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3401   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3402   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3403                                ARMcc, CCR, Cmp);
3404   if (CondCode2 != ARMCC::AL) {
3405     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3406     // FIXME: Needs another CMP because flag can have but one use.
3407     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3408     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3409                          Result, TrueVal, ARMcc2, CCR, Cmp2);
3410   }
3411   return Result;
3412 }
3413
3414 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3415 /// to morph to an integer compare sequence.
3416 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3417                            const ARMSubtarget *Subtarget) {
3418   SDNode *N = Op.getNode();
3419   if (!N->hasOneUse())
3420     // Otherwise it requires moving the value from fp to integer registers.
3421     return false;
3422   if (!N->getNumValues())
3423     return false;
3424   EVT VT = Op.getValueType();
3425   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3426     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3427     // vmrs are very slow, e.g. cortex-a8.
3428     return false;
3429
3430   if (isFloatingPointZero(Op)) {
3431     SeenZero = true;
3432     return true;
3433   }
3434   return ISD::isNormalLoad(N);
3435 }
3436
3437 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3438   if (isFloatingPointZero(Op))
3439     return DAG.getConstant(0, MVT::i32);
3440
3441   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3442     return DAG.getLoad(MVT::i32, SDLoc(Op),
3443                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3444                        Ld->isVolatile(), Ld->isNonTemporal(),
3445                        Ld->isInvariant(), Ld->getAlignment());
3446
3447   llvm_unreachable("Unknown VFP cmp argument!");
3448 }
3449
3450 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3451                            SDValue &RetVal1, SDValue &RetVal2) {
3452   if (isFloatingPointZero(Op)) {
3453     RetVal1 = DAG.getConstant(0, MVT::i32);
3454     RetVal2 = DAG.getConstant(0, MVT::i32);
3455     return;
3456   }
3457
3458   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3459     SDValue Ptr = Ld->getBasePtr();
3460     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3461                           Ld->getChain(), Ptr,
3462                           Ld->getPointerInfo(),
3463                           Ld->isVolatile(), Ld->isNonTemporal(),
3464                           Ld->isInvariant(), Ld->getAlignment());
3465
3466     EVT PtrType = Ptr.getValueType();
3467     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3468     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3469                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3470     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3471                           Ld->getChain(), NewPtr,
3472                           Ld->getPointerInfo().getWithOffset(4),
3473                           Ld->isVolatile(), Ld->isNonTemporal(),
3474                           Ld->isInvariant(), NewAlign);
3475     return;
3476   }
3477
3478   llvm_unreachable("Unknown VFP cmp argument!");
3479 }
3480
3481 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3482 /// f32 and even f64 comparisons to integer ones.
3483 SDValue
3484 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3485   SDValue Chain = Op.getOperand(0);
3486   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3487   SDValue LHS = Op.getOperand(2);
3488   SDValue RHS = Op.getOperand(3);
3489   SDValue Dest = Op.getOperand(4);
3490   SDLoc dl(Op);
3491
3492   bool LHSSeenZero = false;
3493   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3494   bool RHSSeenZero = false;
3495   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3496   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3497     // If unsafe fp math optimization is enabled and there are no other uses of
3498     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3499     // to an integer comparison.
3500     if (CC == ISD::SETOEQ)
3501       CC = ISD::SETEQ;
3502     else if (CC == ISD::SETUNE)
3503       CC = ISD::SETNE;
3504
3505     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3506     SDValue ARMcc;
3507     if (LHS.getValueType() == MVT::f32) {
3508       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3509                         bitcastf32Toi32(LHS, DAG), Mask);
3510       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3511                         bitcastf32Toi32(RHS, DAG), Mask);
3512       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3513       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3514       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3515                          Chain, Dest, ARMcc, CCR, Cmp);
3516     }
3517
3518     SDValue LHS1, LHS2;
3519     SDValue RHS1, RHS2;
3520     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3521     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3522     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3523     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3524     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3525     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3526     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3527     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3528     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3529   }
3530
3531   return SDValue();
3532 }
3533
3534 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3535   SDValue Chain = Op.getOperand(0);
3536   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3537   SDValue LHS = Op.getOperand(2);
3538   SDValue RHS = Op.getOperand(3);
3539   SDValue Dest = Op.getOperand(4);
3540   SDLoc dl(Op);
3541
3542   if (LHS.getValueType() == MVT::i32) {
3543     SDValue ARMcc;
3544     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3545     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3546     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3547                        Chain, Dest, ARMcc, CCR, Cmp);
3548   }
3549
3550   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3551
3552   if (getTargetMachine().Options.UnsafeFPMath &&
3553       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3554        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3555     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3556     if (Result.getNode())
3557       return Result;
3558   }
3559
3560   ARMCC::CondCodes CondCode, CondCode2;
3561   FPCCToARMCC(CC, CondCode, CondCode2);
3562
3563   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3564   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3565   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3566   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3567   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3568   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3569   if (CondCode2 != ARMCC::AL) {
3570     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3571     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3572     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3573   }
3574   return Res;
3575 }
3576
3577 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3578   SDValue Chain = Op.getOperand(0);
3579   SDValue Table = Op.getOperand(1);
3580   SDValue Index = Op.getOperand(2);
3581   SDLoc dl(Op);
3582
3583   EVT PTy = getPointerTy();
3584   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3585   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3586   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3587   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3588   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3589   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3590   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3591   if (Subtarget->isThumb2()) {
3592     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3593     // which does another jump to the destination. This also makes it easier
3594     // to translate it to TBB / TBH later.
3595     // FIXME: This might not work if the function is extremely large.
3596     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3597                        Addr, Op.getOperand(2), JTI, UId);
3598   }
3599   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3600     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3601                        MachinePointerInfo::getJumpTable(),
3602                        false, false, false, 0);
3603     Chain = Addr.getValue(1);
3604     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3605     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3606   } else {
3607     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3608                        MachinePointerInfo::getJumpTable(),
3609                        false, false, false, 0);
3610     Chain = Addr.getValue(1);
3611     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3612   }
3613 }
3614
3615 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3616   EVT VT = Op.getValueType();
3617   SDLoc dl(Op);
3618
3619   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3620     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3621       return Op;
3622     return DAG.UnrollVectorOp(Op.getNode());
3623   }
3624
3625   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3626          "Invalid type for custom lowering!");
3627   if (VT != MVT::v4i16)
3628     return DAG.UnrollVectorOp(Op.getNode());
3629
3630   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3631   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3632 }
3633
3634 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3635   EVT VT = Op.getValueType();
3636   if (VT.isVector())
3637     return LowerVectorFP_TO_INT(Op, DAG);
3638
3639   SDLoc dl(Op);
3640   unsigned Opc;
3641
3642   switch (Op.getOpcode()) {
3643   default: llvm_unreachable("Invalid opcode!");
3644   case ISD::FP_TO_SINT:
3645     Opc = ARMISD::FTOSI;
3646     break;
3647   case ISD::FP_TO_UINT:
3648     Opc = ARMISD::FTOUI;
3649     break;
3650   }
3651   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3652   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3653 }
3654
3655 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3656   EVT VT = Op.getValueType();
3657   SDLoc dl(Op);
3658
3659   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3660     if (VT.getVectorElementType() == MVT::f32)
3661       return Op;
3662     return DAG.UnrollVectorOp(Op.getNode());
3663   }
3664
3665   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3666          "Invalid type for custom lowering!");
3667   if (VT != MVT::v4f32)
3668     return DAG.UnrollVectorOp(Op.getNode());
3669
3670   unsigned CastOpc;
3671   unsigned Opc;
3672   switch (Op.getOpcode()) {
3673   default: llvm_unreachable("Invalid opcode!");
3674   case ISD::SINT_TO_FP:
3675     CastOpc = ISD::SIGN_EXTEND;
3676     Opc = ISD::SINT_TO_FP;
3677     break;
3678   case ISD::UINT_TO_FP:
3679     CastOpc = ISD::ZERO_EXTEND;
3680     Opc = ISD::UINT_TO_FP;
3681     break;
3682   }
3683
3684   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3685   return DAG.getNode(Opc, dl, VT, Op);
3686 }
3687
3688 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3689   EVT VT = Op.getValueType();
3690   if (VT.isVector())
3691     return LowerVectorINT_TO_FP(Op, DAG);
3692
3693   SDLoc dl(Op);
3694   unsigned Opc;
3695
3696   switch (Op.getOpcode()) {
3697   default: llvm_unreachable("Invalid opcode!");
3698   case ISD::SINT_TO_FP:
3699     Opc = ARMISD::SITOF;
3700     break;
3701   case ISD::UINT_TO_FP:
3702     Opc = ARMISD::UITOF;
3703     break;
3704   }
3705
3706   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3707   return DAG.getNode(Opc, dl, VT, Op);
3708 }
3709
3710 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3711   // Implement fcopysign with a fabs and a conditional fneg.
3712   SDValue Tmp0 = Op.getOperand(0);
3713   SDValue Tmp1 = Op.getOperand(1);
3714   SDLoc dl(Op);
3715   EVT VT = Op.getValueType();
3716   EVT SrcVT = Tmp1.getValueType();
3717   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3718     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3719   bool UseNEON = !InGPR && Subtarget->hasNEON();
3720
3721   if (UseNEON) {
3722     // Use VBSL to copy the sign bit.
3723     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3724     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3725                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3726     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3727     if (VT == MVT::f64)
3728       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3729                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3730                          DAG.getConstant(32, MVT::i32));
3731     else /*if (VT == MVT::f32)*/
3732       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3733     if (SrcVT == MVT::f32) {
3734       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3735       if (VT == MVT::f64)
3736         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3737                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3738                            DAG.getConstant(32, MVT::i32));
3739     } else if (VT == MVT::f32)
3740       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3741                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3742                          DAG.getConstant(32, MVT::i32));
3743     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3744     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3745
3746     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3747                                             MVT::i32);
3748     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3749     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3750                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3751
3752     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3753                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3754                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3755     if (VT == MVT::f32) {
3756       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3757       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3758                         DAG.getConstant(0, MVT::i32));
3759     } else {
3760       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3761     }
3762
3763     return Res;
3764   }
3765
3766   // Bitcast operand 1 to i32.
3767   if (SrcVT == MVT::f64)
3768     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3769                        &Tmp1, 1).getValue(1);
3770   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3771
3772   // Or in the signbit with integer operations.
3773   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3774   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3775   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3776   if (VT == MVT::f32) {
3777     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3778                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3779     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3780                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3781   }
3782
3783   // f64: Or the high part with signbit and then combine two parts.
3784   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3785                      &Tmp0, 1);
3786   SDValue Lo = Tmp0.getValue(0);
3787   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3788   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3789   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3790 }
3791
3792 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3793   MachineFunction &MF = DAG.getMachineFunction();
3794   MachineFrameInfo *MFI = MF.getFrameInfo();
3795   MFI->setReturnAddressIsTaken(true);
3796
3797   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3798     return SDValue();
3799
3800   EVT VT = Op.getValueType();
3801   SDLoc dl(Op);
3802   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3803   if (Depth) {
3804     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3805     SDValue Offset = DAG.getConstant(4, MVT::i32);
3806     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3807                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3808                        MachinePointerInfo(), false, false, false, 0);
3809   }
3810
3811   // Return LR, which contains the return address. Mark it an implicit live-in.
3812   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3813   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3814 }
3815
3816 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3817   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3818   MFI->setFrameAddressIsTaken(true);
3819
3820   EVT VT = Op.getValueType();
3821   SDLoc dl(Op);  // FIXME probably not meaningful
3822   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3823   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetMachO())
3824     ? ARM::R7 : ARM::R11;
3825   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3826   while (Depth--)
3827     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3828                             MachinePointerInfo(),
3829                             false, false, false, 0);
3830   return FrameAddr;
3831 }
3832
3833 /// ExpandBITCAST - If the target supports VFP, this function is called to
3834 /// expand a bit convert where either the source or destination type is i64 to
3835 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3836 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3837 /// vectors), since the legalizer won't know what to do with that.
3838 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3839   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3840   SDLoc dl(N);
3841   SDValue Op = N->getOperand(0);
3842
3843   // This function is only supposed to be called for i64 types, either as the
3844   // source or destination of the bit convert.
3845   EVT SrcVT = Op.getValueType();
3846   EVT DstVT = N->getValueType(0);
3847   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3848          "ExpandBITCAST called for non-i64 type");
3849
3850   // Turn i64->f64 into VMOVDRR.
3851   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3852     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3853                              DAG.getConstant(0, MVT::i32));
3854     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3855                              DAG.getConstant(1, MVT::i32));
3856     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3857                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3858   }
3859
3860   // Turn f64->i64 into VMOVRRD.
3861   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3862     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3863                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3864     // Merge the pieces into a single i64 value.
3865     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3866   }
3867
3868   return SDValue();
3869 }
3870
3871 /// getZeroVector - Returns a vector of specified type with all zero elements.
3872 /// Zero vectors are used to represent vector negation and in those cases
3873 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3874 /// not support i64 elements, so sometimes the zero vectors will need to be
3875 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3876 /// zero vector.
3877 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3878   assert(VT.isVector() && "Expected a vector type");
3879   // The canonical modified immediate encoding of a zero vector is....0!
3880   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3881   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3882   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3883   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3884 }
3885
3886 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3887 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3888 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3889                                                 SelectionDAG &DAG) const {
3890   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3891   EVT VT = Op.getValueType();
3892   unsigned VTBits = VT.getSizeInBits();
3893   SDLoc dl(Op);
3894   SDValue ShOpLo = Op.getOperand(0);
3895   SDValue ShOpHi = Op.getOperand(1);
3896   SDValue ShAmt  = Op.getOperand(2);
3897   SDValue ARMcc;
3898   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3899
3900   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3901
3902   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3903                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3904   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3905   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3906                                    DAG.getConstant(VTBits, MVT::i32));
3907   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3908   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3909   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3910
3911   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3912   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3913                           ARMcc, DAG, dl);
3914   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3915   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3916                            CCR, Cmp);
3917
3918   SDValue Ops[2] = { Lo, Hi };
3919   return DAG.getMergeValues(Ops, 2, dl);
3920 }
3921
3922 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3923 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3924 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3925                                                SelectionDAG &DAG) const {
3926   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3927   EVT VT = Op.getValueType();
3928   unsigned VTBits = VT.getSizeInBits();
3929   SDLoc dl(Op);
3930   SDValue ShOpLo = Op.getOperand(0);
3931   SDValue ShOpHi = Op.getOperand(1);
3932   SDValue ShAmt  = Op.getOperand(2);
3933   SDValue ARMcc;
3934
3935   assert(Op.getOpcode() == ISD::SHL_PARTS);
3936   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3937                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3938   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3939   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3940                                    DAG.getConstant(VTBits, MVT::i32));
3941   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3942   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3943
3944   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3945   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3946   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3947                           ARMcc, DAG, dl);
3948   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3949   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3950                            CCR, Cmp);
3951
3952   SDValue Ops[2] = { Lo, Hi };
3953   return DAG.getMergeValues(Ops, 2, dl);
3954 }
3955
3956 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3957                                             SelectionDAG &DAG) const {
3958   // The rounding mode is in bits 23:22 of the FPSCR.
3959   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3960   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3961   // so that the shift + and get folded into a bitfield extract.
3962   SDLoc dl(Op);
3963   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3964                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3965                                               MVT::i32));
3966   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3967                                   DAG.getConstant(1U << 22, MVT::i32));
3968   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3969                               DAG.getConstant(22, MVT::i32));
3970   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3971                      DAG.getConstant(3, MVT::i32));
3972 }
3973
3974 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3975                          const ARMSubtarget *ST) {
3976   EVT VT = N->getValueType(0);
3977   SDLoc dl(N);
3978
3979   if (!ST->hasV6T2Ops())
3980     return SDValue();
3981
3982   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3983   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3984 }
3985
3986 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3987 /// for each 16-bit element from operand, repeated.  The basic idea is to
3988 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3989 ///
3990 /// Trace for v4i16:
3991 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
3992 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3993 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3994 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3995 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
3996 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
3997 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3998 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
3999 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4000   EVT VT = N->getValueType(0);
4001   SDLoc DL(N);
4002
4003   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4004   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4005   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4006   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4007   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4008   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4009 }
4010
4011 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4012 /// bit-count for each 16-bit element from the operand.  We need slightly
4013 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4014 /// 64/128-bit registers.
4015 ///
4016 /// Trace for v4i16:
4017 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4018 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4019 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4020 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4021 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4022   EVT VT = N->getValueType(0);
4023   SDLoc DL(N);
4024
4025   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4026   if (VT.is64BitVector()) {
4027     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4028     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4029                        DAG.getIntPtrConstant(0));
4030   } else {
4031     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4032                                     BitCounts, DAG.getIntPtrConstant(0));
4033     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4034   }
4035 }
4036
4037 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4038 /// bit-count for each 32-bit element from the operand.  The idea here is
4039 /// to split the vector into 16-bit elements, leverage the 16-bit count
4040 /// routine, and then combine the results.
4041 ///
4042 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4043 /// input    = [v0    v1    ] (vi: 32-bit elements)
4044 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4045 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4046 /// vrev: N0 = [k1 k0 k3 k2 ]
4047 ///            [k0 k1 k2 k3 ]
4048 ///       N1 =+[k1 k0 k3 k2 ]
4049 ///            [k0 k2 k1 k3 ]
4050 ///       N2 =+[k1 k3 k0 k2 ]
4051 ///            [k0    k2    k1    k3    ]
4052 /// Extended =+[k1    k3    k0    k2    ]
4053 ///            [k0    k2    ]
4054 /// Extracted=+[k1    k3    ]
4055 ///
4056 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4057   EVT VT = N->getValueType(0);
4058   SDLoc DL(N);
4059
4060   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4061
4062   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4063   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4064   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4065   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4066   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4067
4068   if (VT.is64BitVector()) {
4069     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4070     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4071                        DAG.getIntPtrConstant(0));
4072   } else {
4073     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4074                                     DAG.getIntPtrConstant(0));
4075     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4076   }
4077 }
4078
4079 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4080                           const ARMSubtarget *ST) {
4081   EVT VT = N->getValueType(0);
4082
4083   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4084   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4085           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4086          "Unexpected type for custom ctpop lowering");
4087
4088   if (VT.getVectorElementType() == MVT::i32)
4089     return lowerCTPOP32BitElements(N, DAG);
4090   else
4091     return lowerCTPOP16BitElements(N, DAG);
4092 }
4093
4094 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4095                           const ARMSubtarget *ST) {
4096   EVT VT = N->getValueType(0);
4097   SDLoc dl(N);
4098
4099   if (!VT.isVector())
4100     return SDValue();
4101
4102   // Lower vector shifts on NEON to use VSHL.
4103   assert(ST->hasNEON() && "unexpected vector shift");
4104
4105   // Left shifts translate directly to the vshiftu intrinsic.
4106   if (N->getOpcode() == ISD::SHL)
4107     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4108                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4109                        N->getOperand(0), N->getOperand(1));
4110
4111   assert((N->getOpcode() == ISD::SRA ||
4112           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4113
4114   // NEON uses the same intrinsics for both left and right shifts.  For
4115   // right shifts, the shift amounts are negative, so negate the vector of
4116   // shift amounts.
4117   EVT ShiftVT = N->getOperand(1).getValueType();
4118   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4119                                      getZeroVector(ShiftVT, DAG, dl),
4120                                      N->getOperand(1));
4121   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4122                              Intrinsic::arm_neon_vshifts :
4123                              Intrinsic::arm_neon_vshiftu);
4124   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4125                      DAG.getConstant(vshiftInt, MVT::i32),
4126                      N->getOperand(0), NegatedCount);
4127 }
4128
4129 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4130                                 const ARMSubtarget *ST) {
4131   EVT VT = N->getValueType(0);
4132   SDLoc dl(N);
4133
4134   // We can get here for a node like i32 = ISD::SHL i32, i64
4135   if (VT != MVT::i64)
4136     return SDValue();
4137
4138   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4139          "Unknown shift to lower!");
4140
4141   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4142   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4143       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4144     return SDValue();
4145
4146   // If we are in thumb mode, we don't have RRX.
4147   if (ST->isThumb1Only()) return SDValue();
4148
4149   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4150   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4151                            DAG.getConstant(0, MVT::i32));
4152   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4153                            DAG.getConstant(1, MVT::i32));
4154
4155   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4156   // captures the result into a carry flag.
4157   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4158   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
4159
4160   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4161   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4162
4163   // Merge the pieces into a single i64 value.
4164  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4165 }
4166
4167 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4168   SDValue TmpOp0, TmpOp1;
4169   bool Invert = false;
4170   bool Swap = false;
4171   unsigned Opc = 0;
4172
4173   SDValue Op0 = Op.getOperand(0);
4174   SDValue Op1 = Op.getOperand(1);
4175   SDValue CC = Op.getOperand(2);
4176   EVT VT = Op.getValueType();
4177   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4178   SDLoc dl(Op);
4179
4180   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4181     switch (SetCCOpcode) {
4182     default: llvm_unreachable("Illegal FP comparison");
4183     case ISD::SETUNE:
4184     case ISD::SETNE:  Invert = true; // Fallthrough
4185     case ISD::SETOEQ:
4186     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4187     case ISD::SETOLT:
4188     case ISD::SETLT: Swap = true; // Fallthrough
4189     case ISD::SETOGT:
4190     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4191     case ISD::SETOLE:
4192     case ISD::SETLE:  Swap = true; // Fallthrough
4193     case ISD::SETOGE:
4194     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4195     case ISD::SETUGE: Swap = true; // Fallthrough
4196     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4197     case ISD::SETUGT: Swap = true; // Fallthrough
4198     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4199     case ISD::SETUEQ: Invert = true; // Fallthrough
4200     case ISD::SETONE:
4201       // Expand this to (OLT | OGT).
4202       TmpOp0 = Op0;
4203       TmpOp1 = Op1;
4204       Opc = ISD::OR;
4205       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4206       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4207       break;
4208     case ISD::SETUO: Invert = true; // Fallthrough
4209     case ISD::SETO:
4210       // Expand this to (OLT | OGE).
4211       TmpOp0 = Op0;
4212       TmpOp1 = Op1;
4213       Opc = ISD::OR;
4214       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4215       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4216       break;
4217     }
4218   } else {
4219     // Integer comparisons.
4220     switch (SetCCOpcode) {
4221     default: llvm_unreachable("Illegal integer comparison");
4222     case ISD::SETNE:  Invert = true;
4223     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4224     case ISD::SETLT:  Swap = true;
4225     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4226     case ISD::SETLE:  Swap = true;
4227     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4228     case ISD::SETULT: Swap = true;
4229     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4230     case ISD::SETULE: Swap = true;
4231     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4232     }
4233
4234     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4235     if (Opc == ARMISD::VCEQ) {
4236
4237       SDValue AndOp;
4238       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4239         AndOp = Op0;
4240       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4241         AndOp = Op1;
4242
4243       // Ignore bitconvert.
4244       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4245         AndOp = AndOp.getOperand(0);
4246
4247       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4248         Opc = ARMISD::VTST;
4249         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4250         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4251         Invert = !Invert;
4252       }
4253     }
4254   }
4255
4256   if (Swap)
4257     std::swap(Op0, Op1);
4258
4259   // If one of the operands is a constant vector zero, attempt to fold the
4260   // comparison to a specialized compare-against-zero form.
4261   SDValue SingleOp;
4262   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4263     SingleOp = Op0;
4264   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4265     if (Opc == ARMISD::VCGE)
4266       Opc = ARMISD::VCLEZ;
4267     else if (Opc == ARMISD::VCGT)
4268       Opc = ARMISD::VCLTZ;
4269     SingleOp = Op1;
4270   }
4271
4272   SDValue Result;
4273   if (SingleOp.getNode()) {
4274     switch (Opc) {
4275     case ARMISD::VCEQ:
4276       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4277     case ARMISD::VCGE:
4278       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4279     case ARMISD::VCLEZ:
4280       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4281     case ARMISD::VCGT:
4282       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4283     case ARMISD::VCLTZ:
4284       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4285     default:
4286       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4287     }
4288   } else {
4289      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4290   }
4291
4292   if (Invert)
4293     Result = DAG.getNOT(dl, Result, VT);
4294
4295   return Result;
4296 }
4297
4298 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4299 /// valid vector constant for a NEON instruction with a "modified immediate"
4300 /// operand (e.g., VMOV).  If so, return the encoded value.
4301 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4302                                  unsigned SplatBitSize, SelectionDAG &DAG,
4303                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4304   unsigned OpCmode, Imm;
4305
4306   // SplatBitSize is set to the smallest size that splats the vector, so a
4307   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4308   // immediate instructions others than VMOV do not support the 8-bit encoding
4309   // of a zero vector, and the default encoding of zero is supposed to be the
4310   // 32-bit version.
4311   if (SplatBits == 0)
4312     SplatBitSize = 32;
4313
4314   switch (SplatBitSize) {
4315   case 8:
4316     if (type != VMOVModImm)
4317       return SDValue();
4318     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4319     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4320     OpCmode = 0xe;
4321     Imm = SplatBits;
4322     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4323     break;
4324
4325   case 16:
4326     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4327     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4328     if ((SplatBits & ~0xff) == 0) {
4329       // Value = 0x00nn: Op=x, Cmode=100x.
4330       OpCmode = 0x8;
4331       Imm = SplatBits;
4332       break;
4333     }
4334     if ((SplatBits & ~0xff00) == 0) {
4335       // Value = 0xnn00: Op=x, Cmode=101x.
4336       OpCmode = 0xa;
4337       Imm = SplatBits >> 8;
4338       break;
4339     }
4340     return SDValue();
4341
4342   case 32:
4343     // NEON's 32-bit VMOV supports splat values where:
4344     // * only one byte is nonzero, or
4345     // * the least significant byte is 0xff and the second byte is nonzero, or
4346     // * the least significant 2 bytes are 0xff and the third is nonzero.
4347     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4348     if ((SplatBits & ~0xff) == 0) {
4349       // Value = 0x000000nn: Op=x, Cmode=000x.
4350       OpCmode = 0;
4351       Imm = SplatBits;
4352       break;
4353     }
4354     if ((SplatBits & ~0xff00) == 0) {
4355       // Value = 0x0000nn00: Op=x, Cmode=001x.
4356       OpCmode = 0x2;
4357       Imm = SplatBits >> 8;
4358       break;
4359     }
4360     if ((SplatBits & ~0xff0000) == 0) {
4361       // Value = 0x00nn0000: Op=x, Cmode=010x.
4362       OpCmode = 0x4;
4363       Imm = SplatBits >> 16;
4364       break;
4365     }
4366     if ((SplatBits & ~0xff000000) == 0) {
4367       // Value = 0xnn000000: Op=x, Cmode=011x.
4368       OpCmode = 0x6;
4369       Imm = SplatBits >> 24;
4370       break;
4371     }
4372
4373     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4374     if (type == OtherModImm) return SDValue();
4375
4376     if ((SplatBits & ~0xffff) == 0 &&
4377         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4378       // Value = 0x0000nnff: Op=x, Cmode=1100.
4379       OpCmode = 0xc;
4380       Imm = SplatBits >> 8;
4381       SplatBits |= 0xff;
4382       break;
4383     }
4384
4385     if ((SplatBits & ~0xffffff) == 0 &&
4386         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4387       // Value = 0x00nnffff: Op=x, Cmode=1101.
4388       OpCmode = 0xd;
4389       Imm = SplatBits >> 16;
4390       SplatBits |= 0xffff;
4391       break;
4392     }
4393
4394     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4395     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4396     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4397     // and fall through here to test for a valid 64-bit splat.  But, then the
4398     // caller would also need to check and handle the change in size.
4399     return SDValue();
4400
4401   case 64: {
4402     if (type != VMOVModImm)
4403       return SDValue();
4404     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4405     uint64_t BitMask = 0xff;
4406     uint64_t Val = 0;
4407     unsigned ImmMask = 1;
4408     Imm = 0;
4409     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4410       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4411         Val |= BitMask;
4412         Imm |= ImmMask;
4413       } else if ((SplatBits & BitMask) != 0) {
4414         return SDValue();
4415       }
4416       BitMask <<= 8;
4417       ImmMask <<= 1;
4418     }
4419     // Op=1, Cmode=1110.
4420     OpCmode = 0x1e;
4421     SplatBits = Val;
4422     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4423     break;
4424   }
4425
4426   default:
4427     llvm_unreachable("unexpected size for isNEONModifiedImm");
4428   }
4429
4430   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4431   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4432 }
4433
4434 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4435                                            const ARMSubtarget *ST) const {
4436   if (!ST->hasVFP3())
4437     return SDValue();
4438
4439   bool IsDouble = Op.getValueType() == MVT::f64;
4440   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4441
4442   // Try splatting with a VMOV.f32...
4443   APFloat FPVal = CFP->getValueAPF();
4444   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4445
4446   if (ImmVal != -1) {
4447     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4448       // We have code in place to select a valid ConstantFP already, no need to
4449       // do any mangling.
4450       return Op;
4451     }
4452
4453     // It's a float and we are trying to use NEON operations where
4454     // possible. Lower it to a splat followed by an extract.
4455     SDLoc DL(Op);
4456     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4457     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4458                                       NewVal);
4459     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4460                        DAG.getConstant(0, MVT::i32));
4461   }
4462
4463   // The rest of our options are NEON only, make sure that's allowed before
4464   // proceeding..
4465   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4466     return SDValue();
4467
4468   EVT VMovVT;
4469   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4470
4471   // It wouldn't really be worth bothering for doubles except for one very
4472   // important value, which does happen to match: 0.0. So make sure we don't do
4473   // anything stupid.
4474   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4475     return SDValue();
4476
4477   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4478   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4479                                      false, VMOVModImm);
4480   if (NewVal != SDValue()) {
4481     SDLoc DL(Op);
4482     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4483                                       NewVal);
4484     if (IsDouble)
4485       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4486
4487     // It's a float: cast and extract a vector element.
4488     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4489                                        VecConstant);
4490     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4491                        DAG.getConstant(0, MVT::i32));
4492   }
4493
4494   // Finally, try a VMVN.i32
4495   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4496                              false, VMVNModImm);
4497   if (NewVal != SDValue()) {
4498     SDLoc DL(Op);
4499     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4500
4501     if (IsDouble)
4502       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4503
4504     // It's a float: cast and extract a vector element.
4505     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4506                                        VecConstant);
4507     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4508                        DAG.getConstant(0, MVT::i32));
4509   }
4510
4511   return SDValue();
4512 }
4513
4514 // check if an VEXT instruction can handle the shuffle mask when the
4515 // vector sources of the shuffle are the same.
4516 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4517   unsigned NumElts = VT.getVectorNumElements();
4518
4519   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4520   if (M[0] < 0)
4521     return false;
4522
4523   Imm = M[0];
4524
4525   // If this is a VEXT shuffle, the immediate value is the index of the first
4526   // element.  The other shuffle indices must be the successive elements after
4527   // the first one.
4528   unsigned ExpectedElt = Imm;
4529   for (unsigned i = 1; i < NumElts; ++i) {
4530     // Increment the expected index.  If it wraps around, just follow it
4531     // back to index zero and keep going.
4532     ++ExpectedElt;
4533     if (ExpectedElt == NumElts)
4534       ExpectedElt = 0;
4535
4536     if (M[i] < 0) continue; // ignore UNDEF indices
4537     if (ExpectedElt != static_cast<unsigned>(M[i]))
4538       return false;
4539   }
4540
4541   return true;
4542 }
4543
4544
4545 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4546                        bool &ReverseVEXT, unsigned &Imm) {
4547   unsigned NumElts = VT.getVectorNumElements();
4548   ReverseVEXT = false;
4549
4550   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4551   if (M[0] < 0)
4552     return false;
4553
4554   Imm = M[0];
4555
4556   // If this is a VEXT shuffle, the immediate value is the index of the first
4557   // element.  The other shuffle indices must be the successive elements after
4558   // the first one.
4559   unsigned ExpectedElt = Imm;
4560   for (unsigned i = 1; i < NumElts; ++i) {
4561     // Increment the expected index.  If it wraps around, it may still be
4562     // a VEXT but the source vectors must be swapped.
4563     ExpectedElt += 1;
4564     if (ExpectedElt == NumElts * 2) {
4565       ExpectedElt = 0;
4566       ReverseVEXT = true;
4567     }
4568
4569     if (M[i] < 0) continue; // ignore UNDEF indices
4570     if (ExpectedElt != static_cast<unsigned>(M[i]))
4571       return false;
4572   }
4573
4574   // Adjust the index value if the source operands will be swapped.
4575   if (ReverseVEXT)
4576     Imm -= NumElts;
4577
4578   return true;
4579 }
4580
4581 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4582 /// instruction with the specified blocksize.  (The order of the elements
4583 /// within each block of the vector is reversed.)
4584 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4585   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4586          "Only possible block sizes for VREV are: 16, 32, 64");
4587
4588   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4589   if (EltSz == 64)
4590     return false;
4591
4592   unsigned NumElts = VT.getVectorNumElements();
4593   unsigned BlockElts = M[0] + 1;
4594   // If the first shuffle index is UNDEF, be optimistic.
4595   if (M[0] < 0)
4596     BlockElts = BlockSize / EltSz;
4597
4598   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4599     return false;
4600
4601   for (unsigned i = 0; i < NumElts; ++i) {
4602     if (M[i] < 0) continue; // ignore UNDEF indices
4603     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4604       return false;
4605   }
4606
4607   return true;
4608 }
4609
4610 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4611   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4612   // range, then 0 is placed into the resulting vector. So pretty much any mask
4613   // of 8 elements can work here.
4614   return VT == MVT::v8i8 && M.size() == 8;
4615 }
4616
4617 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4618   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4619   if (EltSz == 64)
4620     return false;
4621
4622   unsigned NumElts = VT.getVectorNumElements();
4623   WhichResult = (M[0] == 0 ? 0 : 1);
4624   for (unsigned i = 0; i < NumElts; i += 2) {
4625     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4626         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4627       return false;
4628   }
4629   return true;
4630 }
4631
4632 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4633 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4634 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4635 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4636   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4637   if (EltSz == 64)
4638     return false;
4639
4640   unsigned NumElts = VT.getVectorNumElements();
4641   WhichResult = (M[0] == 0 ? 0 : 1);
4642   for (unsigned i = 0; i < NumElts; i += 2) {
4643     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4644         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4645       return false;
4646   }
4647   return true;
4648 }
4649
4650 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4651   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4652   if (EltSz == 64)
4653     return false;
4654
4655   unsigned NumElts = VT.getVectorNumElements();
4656   WhichResult = (M[0] == 0 ? 0 : 1);
4657   for (unsigned i = 0; i != NumElts; ++i) {
4658     if (M[i] < 0) continue; // ignore UNDEF indices
4659     if ((unsigned) M[i] != 2 * i + WhichResult)
4660       return false;
4661   }
4662
4663   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4664   if (VT.is64BitVector() && EltSz == 32)
4665     return false;
4666
4667   return true;
4668 }
4669
4670 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4671 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4672 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4673 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4674   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4675   if (EltSz == 64)
4676     return false;
4677
4678   unsigned Half = VT.getVectorNumElements() / 2;
4679   WhichResult = (M[0] == 0 ? 0 : 1);
4680   for (unsigned j = 0; j != 2; ++j) {
4681     unsigned Idx = WhichResult;
4682     for (unsigned i = 0; i != Half; ++i) {
4683       int MIdx = M[i + j * Half];
4684       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4685         return false;
4686       Idx += 2;
4687     }
4688   }
4689
4690   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4691   if (VT.is64BitVector() && EltSz == 32)
4692     return false;
4693
4694   return true;
4695 }
4696
4697 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4698   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4699   if (EltSz == 64)
4700     return false;
4701
4702   unsigned NumElts = VT.getVectorNumElements();
4703   WhichResult = (M[0] == 0 ? 0 : 1);
4704   unsigned Idx = WhichResult * NumElts / 2;
4705   for (unsigned i = 0; i != NumElts; i += 2) {
4706     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4707         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4708       return false;
4709     Idx += 1;
4710   }
4711
4712   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4713   if (VT.is64BitVector() && EltSz == 32)
4714     return false;
4715
4716   return true;
4717 }
4718
4719 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4720 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4721 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4722 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4723   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4724   if (EltSz == 64)
4725     return false;
4726
4727   unsigned NumElts = VT.getVectorNumElements();
4728   WhichResult = (M[0] == 0 ? 0 : 1);
4729   unsigned Idx = WhichResult * NumElts / 2;
4730   for (unsigned i = 0; i != NumElts; i += 2) {
4731     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4732         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4733       return false;
4734     Idx += 1;
4735   }
4736
4737   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4738   if (VT.is64BitVector() && EltSz == 32)
4739     return false;
4740
4741   return true;
4742 }
4743
4744 /// \return true if this is a reverse operation on an vector.
4745 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4746   unsigned NumElts = VT.getVectorNumElements();
4747   // Make sure the mask has the right size.
4748   if (NumElts != M.size())
4749       return false;
4750
4751   // Look for <15, ..., 3, -1, 1, 0>.
4752   for (unsigned i = 0; i != NumElts; ++i)
4753     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4754       return false;
4755
4756   return true;
4757 }
4758
4759 // If N is an integer constant that can be moved into a register in one
4760 // instruction, return an SDValue of such a constant (will become a MOV
4761 // instruction).  Otherwise return null.
4762 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4763                                      const ARMSubtarget *ST, SDLoc dl) {
4764   uint64_t Val;
4765   if (!isa<ConstantSDNode>(N))
4766     return SDValue();
4767   Val = cast<ConstantSDNode>(N)->getZExtValue();
4768
4769   if (ST->isThumb1Only()) {
4770     if (Val <= 255 || ~Val <= 255)
4771       return DAG.getConstant(Val, MVT::i32);
4772   } else {
4773     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4774       return DAG.getConstant(Val, MVT::i32);
4775   }
4776   return SDValue();
4777 }
4778
4779 // If this is a case we can't handle, return null and let the default
4780 // expansion code take care of it.
4781 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4782                                              const ARMSubtarget *ST) const {
4783   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4784   SDLoc dl(Op);
4785   EVT VT = Op.getValueType();
4786
4787   APInt SplatBits, SplatUndef;
4788   unsigned SplatBitSize;
4789   bool HasAnyUndefs;
4790   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4791     if (SplatBitSize <= 64) {
4792       // Check if an immediate VMOV works.
4793       EVT VmovVT;
4794       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4795                                       SplatUndef.getZExtValue(), SplatBitSize,
4796                                       DAG, VmovVT, VT.is128BitVector(),
4797                                       VMOVModImm);
4798       if (Val.getNode()) {
4799         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4800         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4801       }
4802
4803       // Try an immediate VMVN.
4804       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4805       Val = isNEONModifiedImm(NegatedImm,
4806                                       SplatUndef.getZExtValue(), SplatBitSize,
4807                                       DAG, VmovVT, VT.is128BitVector(),
4808                                       VMVNModImm);
4809       if (Val.getNode()) {
4810         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4811         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4812       }
4813
4814       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4815       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4816         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4817         if (ImmVal != -1) {
4818           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4819           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4820         }
4821       }
4822     }
4823   }
4824
4825   // Scan through the operands to see if only one value is used.
4826   //
4827   // As an optimisation, even if more than one value is used it may be more
4828   // profitable to splat with one value then change some lanes.
4829   //
4830   // Heuristically we decide to do this if the vector has a "dominant" value,
4831   // defined as splatted to more than half of the lanes.
4832   unsigned NumElts = VT.getVectorNumElements();
4833   bool isOnlyLowElement = true;
4834   bool usesOnlyOneValue = true;
4835   bool hasDominantValue = false;
4836   bool isConstant = true;
4837
4838   // Map of the number of times a particular SDValue appears in the
4839   // element list.
4840   DenseMap<SDValue, unsigned> ValueCounts;
4841   SDValue Value;
4842   for (unsigned i = 0; i < NumElts; ++i) {
4843     SDValue V = Op.getOperand(i);
4844     if (V.getOpcode() == ISD::UNDEF)
4845       continue;
4846     if (i > 0)
4847       isOnlyLowElement = false;
4848     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4849       isConstant = false;
4850
4851     ValueCounts.insert(std::make_pair(V, 0));
4852     unsigned &Count = ValueCounts[V];
4853
4854     // Is this value dominant? (takes up more than half of the lanes)
4855     if (++Count > (NumElts / 2)) {
4856       hasDominantValue = true;
4857       Value = V;
4858     }
4859   }
4860   if (ValueCounts.size() != 1)
4861     usesOnlyOneValue = false;
4862   if (!Value.getNode() && ValueCounts.size() > 0)
4863     Value = ValueCounts.begin()->first;
4864
4865   if (ValueCounts.size() == 0)
4866     return DAG.getUNDEF(VT);
4867
4868   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
4869   // Keep going if we are hitting this case.
4870   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
4871     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4872
4873   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4874
4875   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4876   // i32 and try again.
4877   if (hasDominantValue && EltSize <= 32) {
4878     if (!isConstant) {
4879       SDValue N;
4880
4881       // If we are VDUPing a value that comes directly from a vector, that will
4882       // cause an unnecessary move to and from a GPR, where instead we could
4883       // just use VDUPLANE. We can only do this if the lane being extracted
4884       // is at a constant index, as the VDUP from lane instructions only have
4885       // constant-index forms.
4886       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4887           isa<ConstantSDNode>(Value->getOperand(1))) {
4888         // We need to create a new undef vector to use for the VDUPLANE if the
4889         // size of the vector from which we get the value is different than the
4890         // size of the vector that we need to create. We will insert the element
4891         // such that the register coalescer will remove unnecessary copies.
4892         if (VT != Value->getOperand(0).getValueType()) {
4893           ConstantSDNode *constIndex;
4894           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4895           assert(constIndex && "The index is not a constant!");
4896           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4897                              VT.getVectorNumElements();
4898           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4899                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4900                         Value, DAG.getConstant(index, MVT::i32)),
4901                            DAG.getConstant(index, MVT::i32));
4902         } else
4903           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4904                         Value->getOperand(0), Value->getOperand(1));
4905       } else
4906         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4907
4908       if (!usesOnlyOneValue) {
4909         // The dominant value was splatted as 'N', but we now have to insert
4910         // all differing elements.
4911         for (unsigned I = 0; I < NumElts; ++I) {
4912           if (Op.getOperand(I) == Value)
4913             continue;
4914           SmallVector<SDValue, 3> Ops;
4915           Ops.push_back(N);
4916           Ops.push_back(Op.getOperand(I));
4917           Ops.push_back(DAG.getConstant(I, MVT::i32));
4918           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4919         }
4920       }
4921       return N;
4922     }
4923     if (VT.getVectorElementType().isFloatingPoint()) {
4924       SmallVector<SDValue, 8> Ops;
4925       for (unsigned i = 0; i < NumElts; ++i)
4926         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4927                                   Op.getOperand(i)));
4928       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4929       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4930       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4931       if (Val.getNode())
4932         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4933     }
4934     if (usesOnlyOneValue) {
4935       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4936       if (isConstant && Val.getNode())
4937         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4938     }
4939   }
4940
4941   // If all elements are constants and the case above didn't get hit, fall back
4942   // to the default expansion, which will generate a load from the constant
4943   // pool.
4944   if (isConstant)
4945     return SDValue();
4946
4947   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4948   if (NumElts >= 4) {
4949     SDValue shuffle = ReconstructShuffle(Op, DAG);
4950     if (shuffle != SDValue())
4951       return shuffle;
4952   }
4953
4954   // Vectors with 32- or 64-bit elements can be built by directly assigning
4955   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4956   // will be legalized.
4957   if (EltSize >= 32) {
4958     // Do the expansion with floating-point types, since that is what the VFP
4959     // registers are defined to use, and since i64 is not legal.
4960     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4961     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4962     SmallVector<SDValue, 8> Ops;
4963     for (unsigned i = 0; i < NumElts; ++i)
4964       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4965     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4966     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4967   }
4968
4969   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
4970   // know the default expansion would otherwise fall back on something even
4971   // worse. For a vector with one or two non-undef values, that's
4972   // scalar_to_vector for the elements followed by a shuffle (provided the
4973   // shuffle is valid for the target) and materialization element by element
4974   // on the stack followed by a load for everything else.
4975   if (!isConstant && !usesOnlyOneValue) {
4976     SDValue Vec = DAG.getUNDEF(VT);
4977     for (unsigned i = 0 ; i < NumElts; ++i) {
4978       SDValue V = Op.getOperand(i);
4979       if (V.getOpcode() == ISD::UNDEF)
4980         continue;
4981       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
4982       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
4983     }
4984     return Vec;
4985   }
4986
4987   return SDValue();
4988 }
4989
4990 // Gather data to see if the operation can be modelled as a
4991 // shuffle in combination with VEXTs.
4992 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4993                                               SelectionDAG &DAG) const {
4994   SDLoc dl(Op);
4995   EVT VT = Op.getValueType();
4996   unsigned NumElts = VT.getVectorNumElements();
4997
4998   SmallVector<SDValue, 2> SourceVecs;
4999   SmallVector<unsigned, 2> MinElts;
5000   SmallVector<unsigned, 2> MaxElts;
5001
5002   for (unsigned i = 0; i < NumElts; ++i) {
5003     SDValue V = Op.getOperand(i);
5004     if (V.getOpcode() == ISD::UNDEF)
5005       continue;
5006     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5007       // A shuffle can only come from building a vector from various
5008       // elements of other vectors.
5009       return SDValue();
5010     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5011                VT.getVectorElementType()) {
5012       // This code doesn't know how to handle shuffles where the vector
5013       // element types do not match (this happens because type legalization
5014       // promotes the return type of EXTRACT_VECTOR_ELT).
5015       // FIXME: It might be appropriate to extend this code to handle
5016       // mismatched types.
5017       return SDValue();
5018     }
5019
5020     // Record this extraction against the appropriate vector if possible...
5021     SDValue SourceVec = V.getOperand(0);
5022     // If the element number isn't a constant, we can't effectively
5023     // analyze what's going on.
5024     if (!isa<ConstantSDNode>(V.getOperand(1)))
5025       return SDValue();
5026     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5027     bool FoundSource = false;
5028     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5029       if (SourceVecs[j] == SourceVec) {
5030         if (MinElts[j] > EltNo)
5031           MinElts[j] = EltNo;
5032         if (MaxElts[j] < EltNo)
5033           MaxElts[j] = EltNo;
5034         FoundSource = true;
5035         break;
5036       }
5037     }
5038
5039     // Or record a new source if not...
5040     if (!FoundSource) {
5041       SourceVecs.push_back(SourceVec);
5042       MinElts.push_back(EltNo);
5043       MaxElts.push_back(EltNo);
5044     }
5045   }
5046
5047   // Currently only do something sane when at most two source vectors
5048   // involved.
5049   if (SourceVecs.size() > 2)
5050     return SDValue();
5051
5052   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5053   int VEXTOffsets[2] = {0, 0};
5054
5055   // This loop extracts the usage patterns of the source vectors
5056   // and prepares appropriate SDValues for a shuffle if possible.
5057   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5058     if (SourceVecs[i].getValueType() == VT) {
5059       // No VEXT necessary
5060       ShuffleSrcs[i] = SourceVecs[i];
5061       VEXTOffsets[i] = 0;
5062       continue;
5063     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5064       // It probably isn't worth padding out a smaller vector just to
5065       // break it down again in a shuffle.
5066       return SDValue();
5067     }
5068
5069     // Since only 64-bit and 128-bit vectors are legal on ARM and
5070     // we've eliminated the other cases...
5071     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5072            "unexpected vector sizes in ReconstructShuffle");
5073
5074     if (MaxElts[i] - MinElts[i] >= NumElts) {
5075       // Span too large for a VEXT to cope
5076       return SDValue();
5077     }
5078
5079     if (MinElts[i] >= NumElts) {
5080       // The extraction can just take the second half
5081       VEXTOffsets[i] = NumElts;
5082       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5083                                    SourceVecs[i],
5084                                    DAG.getIntPtrConstant(NumElts));
5085     } else if (MaxElts[i] < NumElts) {
5086       // The extraction can just take the first half
5087       VEXTOffsets[i] = 0;
5088       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5089                                    SourceVecs[i],
5090                                    DAG.getIntPtrConstant(0));
5091     } else {
5092       // An actual VEXT is needed
5093       VEXTOffsets[i] = MinElts[i];
5094       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5095                                      SourceVecs[i],
5096                                      DAG.getIntPtrConstant(0));
5097       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5098                                      SourceVecs[i],
5099                                      DAG.getIntPtrConstant(NumElts));
5100       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5101                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5102     }
5103   }
5104
5105   SmallVector<int, 8> Mask;
5106
5107   for (unsigned i = 0; i < NumElts; ++i) {
5108     SDValue Entry = Op.getOperand(i);
5109     if (Entry.getOpcode() == ISD::UNDEF) {
5110       Mask.push_back(-1);
5111       continue;
5112     }
5113
5114     SDValue ExtractVec = Entry.getOperand(0);
5115     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5116                                           .getOperand(1))->getSExtValue();
5117     if (ExtractVec == SourceVecs[0]) {
5118       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5119     } else {
5120       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5121     }
5122   }
5123
5124   // Final check before we try to produce nonsense...
5125   if (isShuffleMaskLegal(Mask, VT))
5126     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5127                                 &Mask[0]);
5128
5129   return SDValue();
5130 }
5131
5132 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5133 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5134 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5135 /// are assumed to be legal.
5136 bool
5137 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5138                                       EVT VT) const {
5139   if (VT.getVectorNumElements() == 4 &&
5140       (VT.is128BitVector() || VT.is64BitVector())) {
5141     unsigned PFIndexes[4];
5142     for (unsigned i = 0; i != 4; ++i) {
5143       if (M[i] < 0)
5144         PFIndexes[i] = 8;
5145       else
5146         PFIndexes[i] = M[i];
5147     }
5148
5149     // Compute the index in the perfect shuffle table.
5150     unsigned PFTableIndex =
5151       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5152     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5153     unsigned Cost = (PFEntry >> 30);
5154
5155     if (Cost <= 4)
5156       return true;
5157   }
5158
5159   bool ReverseVEXT;
5160   unsigned Imm, WhichResult;
5161
5162   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5163   return (EltSize >= 32 ||
5164           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5165           isVREVMask(M, VT, 64) ||
5166           isVREVMask(M, VT, 32) ||
5167           isVREVMask(M, VT, 16) ||
5168           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5169           isVTBLMask(M, VT) ||
5170           isVTRNMask(M, VT, WhichResult) ||
5171           isVUZPMask(M, VT, WhichResult) ||
5172           isVZIPMask(M, VT, WhichResult) ||
5173           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5174           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5175           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5176           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5177 }
5178
5179 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5180 /// the specified operations to build the shuffle.
5181 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5182                                       SDValue RHS, SelectionDAG &DAG,
5183                                       SDLoc dl) {
5184   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5185   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5186   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5187
5188   enum {
5189     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5190     OP_VREV,
5191     OP_VDUP0,
5192     OP_VDUP1,
5193     OP_VDUP2,
5194     OP_VDUP3,
5195     OP_VEXT1,
5196     OP_VEXT2,
5197     OP_VEXT3,
5198     OP_VUZPL, // VUZP, left result
5199     OP_VUZPR, // VUZP, right result
5200     OP_VZIPL, // VZIP, left result
5201     OP_VZIPR, // VZIP, right result
5202     OP_VTRNL, // VTRN, left result
5203     OP_VTRNR  // VTRN, right result
5204   };
5205
5206   if (OpNum == OP_COPY) {
5207     if (LHSID == (1*9+2)*9+3) return LHS;
5208     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5209     return RHS;
5210   }
5211
5212   SDValue OpLHS, OpRHS;
5213   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5214   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5215   EVT VT = OpLHS.getValueType();
5216
5217   switch (OpNum) {
5218   default: llvm_unreachable("Unknown shuffle opcode!");
5219   case OP_VREV:
5220     // VREV divides the vector in half and swaps within the half.
5221     if (VT.getVectorElementType() == MVT::i32 ||
5222         VT.getVectorElementType() == MVT::f32)
5223       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5224     // vrev <4 x i16> -> VREV32
5225     if (VT.getVectorElementType() == MVT::i16)
5226       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5227     // vrev <4 x i8> -> VREV16
5228     assert(VT.getVectorElementType() == MVT::i8);
5229     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5230   case OP_VDUP0:
5231   case OP_VDUP1:
5232   case OP_VDUP2:
5233   case OP_VDUP3:
5234     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5235                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5236   case OP_VEXT1:
5237   case OP_VEXT2:
5238   case OP_VEXT3:
5239     return DAG.getNode(ARMISD::VEXT, dl, VT,
5240                        OpLHS, OpRHS,
5241                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5242   case OP_VUZPL:
5243   case OP_VUZPR:
5244     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5245                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5246   case OP_VZIPL:
5247   case OP_VZIPR:
5248     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5249                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5250   case OP_VTRNL:
5251   case OP_VTRNR:
5252     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5253                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5254   }
5255 }
5256
5257 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5258                                        ArrayRef<int> ShuffleMask,
5259                                        SelectionDAG &DAG) {
5260   // Check to see if we can use the VTBL instruction.
5261   SDValue V1 = Op.getOperand(0);
5262   SDValue V2 = Op.getOperand(1);
5263   SDLoc DL(Op);
5264
5265   SmallVector<SDValue, 8> VTBLMask;
5266   for (ArrayRef<int>::iterator
5267          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5268     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5269
5270   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5271     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5272                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5273                                    &VTBLMask[0], 8));
5274
5275   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5276                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5277                                  &VTBLMask[0], 8));
5278 }
5279
5280 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5281                                                       SelectionDAG &DAG) {
5282   SDLoc DL(Op);
5283   SDValue OpLHS = Op.getOperand(0);
5284   EVT VT = OpLHS.getValueType();
5285
5286   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5287          "Expect an v8i16/v16i8 type");
5288   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5289   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5290   // extract the first 8 bytes into the top double word and the last 8 bytes
5291   // into the bottom double word. The v8i16 case is similar.
5292   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5293   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5294                      DAG.getConstant(ExtractNum, MVT::i32));
5295 }
5296
5297 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5298   SDValue V1 = Op.getOperand(0);
5299   SDValue V2 = Op.getOperand(1);
5300   SDLoc dl(Op);
5301   EVT VT = Op.getValueType();
5302   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5303
5304   // Convert shuffles that are directly supported on NEON to target-specific
5305   // DAG nodes, instead of keeping them as shuffles and matching them again
5306   // during code selection.  This is more efficient and avoids the possibility
5307   // of inconsistencies between legalization and selection.
5308   // FIXME: floating-point vectors should be canonicalized to integer vectors
5309   // of the same time so that they get CSEd properly.
5310   ArrayRef<int> ShuffleMask = SVN->getMask();
5311
5312   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5313   if (EltSize <= 32) {
5314     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5315       int Lane = SVN->getSplatIndex();
5316       // If this is undef splat, generate it via "just" vdup, if possible.
5317       if (Lane == -1) Lane = 0;
5318
5319       // Test if V1 is a SCALAR_TO_VECTOR.
5320       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5321         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5322       }
5323       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5324       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5325       // reaches it).
5326       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5327           !isa<ConstantSDNode>(V1.getOperand(0))) {
5328         bool IsScalarToVector = true;
5329         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5330           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5331             IsScalarToVector = false;
5332             break;
5333           }
5334         if (IsScalarToVector)
5335           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5336       }
5337       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5338                          DAG.getConstant(Lane, MVT::i32));
5339     }
5340
5341     bool ReverseVEXT;
5342     unsigned Imm;
5343     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5344       if (ReverseVEXT)
5345         std::swap(V1, V2);
5346       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5347                          DAG.getConstant(Imm, MVT::i32));
5348     }
5349
5350     if (isVREVMask(ShuffleMask, VT, 64))
5351       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5352     if (isVREVMask(ShuffleMask, VT, 32))
5353       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5354     if (isVREVMask(ShuffleMask, VT, 16))
5355       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5356
5357     if (V2->getOpcode() == ISD::UNDEF &&
5358         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5359       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5360                          DAG.getConstant(Imm, MVT::i32));
5361     }
5362
5363     // Check for Neon shuffles that modify both input vectors in place.
5364     // If both results are used, i.e., if there are two shuffles with the same
5365     // source operands and with masks corresponding to both results of one of
5366     // these operations, DAG memoization will ensure that a single node is
5367     // used for both shuffles.
5368     unsigned WhichResult;
5369     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5370       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5371                          V1, V2).getValue(WhichResult);
5372     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5373       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5374                          V1, V2).getValue(WhichResult);
5375     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5376       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5377                          V1, V2).getValue(WhichResult);
5378
5379     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5380       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5381                          V1, V1).getValue(WhichResult);
5382     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5383       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5384                          V1, V1).getValue(WhichResult);
5385     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5386       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5387                          V1, V1).getValue(WhichResult);
5388   }
5389
5390   // If the shuffle is not directly supported and it has 4 elements, use
5391   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5392   unsigned NumElts = VT.getVectorNumElements();
5393   if (NumElts == 4) {
5394     unsigned PFIndexes[4];
5395     for (unsigned i = 0; i != 4; ++i) {
5396       if (ShuffleMask[i] < 0)
5397         PFIndexes[i] = 8;
5398       else
5399         PFIndexes[i] = ShuffleMask[i];
5400     }
5401
5402     // Compute the index in the perfect shuffle table.
5403     unsigned PFTableIndex =
5404       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5405     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5406     unsigned Cost = (PFEntry >> 30);
5407
5408     if (Cost <= 4)
5409       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5410   }
5411
5412   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5413   if (EltSize >= 32) {
5414     // Do the expansion with floating-point types, since that is what the VFP
5415     // registers are defined to use, and since i64 is not legal.
5416     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5417     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5418     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5419     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5420     SmallVector<SDValue, 8> Ops;
5421     for (unsigned i = 0; i < NumElts; ++i) {
5422       if (ShuffleMask[i] < 0)
5423         Ops.push_back(DAG.getUNDEF(EltVT));
5424       else
5425         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5426                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5427                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5428                                                   MVT::i32)));
5429     }
5430     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5431     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5432   }
5433
5434   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5435     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5436
5437   if (VT == MVT::v8i8) {
5438     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5439     if (NewOp.getNode())
5440       return NewOp;
5441   }
5442
5443   return SDValue();
5444 }
5445
5446 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5447   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5448   SDValue Lane = Op.getOperand(2);
5449   if (!isa<ConstantSDNode>(Lane))
5450     return SDValue();
5451
5452   return Op;
5453 }
5454
5455 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5456   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5457   SDValue Lane = Op.getOperand(1);
5458   if (!isa<ConstantSDNode>(Lane))
5459     return SDValue();
5460
5461   SDValue Vec = Op.getOperand(0);
5462   if (Op.getValueType() == MVT::i32 &&
5463       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5464     SDLoc dl(Op);
5465     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5466   }
5467
5468   return Op;
5469 }
5470
5471 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5472   // The only time a CONCAT_VECTORS operation can have legal types is when
5473   // two 64-bit vectors are concatenated to a 128-bit vector.
5474   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5475          "unexpected CONCAT_VECTORS");
5476   SDLoc dl(Op);
5477   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5478   SDValue Op0 = Op.getOperand(0);
5479   SDValue Op1 = Op.getOperand(1);
5480   if (Op0.getOpcode() != ISD::UNDEF)
5481     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5482                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5483                       DAG.getIntPtrConstant(0));
5484   if (Op1.getOpcode() != ISD::UNDEF)
5485     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5486                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5487                       DAG.getIntPtrConstant(1));
5488   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5489 }
5490
5491 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5492 /// element has been zero/sign-extended, depending on the isSigned parameter,
5493 /// from an integer type half its size.
5494 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5495                                    bool isSigned) {
5496   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5497   EVT VT = N->getValueType(0);
5498   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5499     SDNode *BVN = N->getOperand(0).getNode();
5500     if (BVN->getValueType(0) != MVT::v4i32 ||
5501         BVN->getOpcode() != ISD::BUILD_VECTOR)
5502       return false;
5503     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5504     unsigned HiElt = 1 - LoElt;
5505     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5506     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5507     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5508     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5509     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5510       return false;
5511     if (isSigned) {
5512       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5513           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5514         return true;
5515     } else {
5516       if (Hi0->isNullValue() && Hi1->isNullValue())
5517         return true;
5518     }
5519     return false;
5520   }
5521
5522   if (N->getOpcode() != ISD::BUILD_VECTOR)
5523     return false;
5524
5525   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5526     SDNode *Elt = N->getOperand(i).getNode();
5527     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5528       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5529       unsigned HalfSize = EltSize / 2;
5530       if (isSigned) {
5531         if (!isIntN(HalfSize, C->getSExtValue()))
5532           return false;
5533       } else {
5534         if (!isUIntN(HalfSize, C->getZExtValue()))
5535           return false;
5536       }
5537       continue;
5538     }
5539     return false;
5540   }
5541
5542   return true;
5543 }
5544
5545 /// isSignExtended - Check if a node is a vector value that is sign-extended
5546 /// or a constant BUILD_VECTOR with sign-extended elements.
5547 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5548   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5549     return true;
5550   if (isExtendedBUILD_VECTOR(N, DAG, true))
5551     return true;
5552   return false;
5553 }
5554
5555 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5556 /// or a constant BUILD_VECTOR with zero-extended elements.
5557 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5558   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5559     return true;
5560   if (isExtendedBUILD_VECTOR(N, DAG, false))
5561     return true;
5562   return false;
5563 }
5564
5565 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5566   if (OrigVT.getSizeInBits() >= 64)
5567     return OrigVT;
5568
5569   assert(OrigVT.isSimple() && "Expecting a simple value type");
5570
5571   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5572   switch (OrigSimpleTy) {
5573   default: llvm_unreachable("Unexpected Vector Type");
5574   case MVT::v2i8:
5575   case MVT::v2i16:
5576      return MVT::v2i32;
5577   case MVT::v4i8:
5578     return  MVT::v4i16;
5579   }
5580 }
5581
5582 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5583 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5584 /// We insert the required extension here to get the vector to fill a D register.
5585 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5586                                             const EVT &OrigTy,
5587                                             const EVT &ExtTy,
5588                                             unsigned ExtOpcode) {
5589   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5590   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5591   // 64-bits we need to insert a new extension so that it will be 64-bits.
5592   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5593   if (OrigTy.getSizeInBits() >= 64)
5594     return N;
5595
5596   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5597   EVT NewVT = getExtensionTo64Bits(OrigTy);
5598
5599   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5600 }
5601
5602 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5603 /// does not do any sign/zero extension. If the original vector is less
5604 /// than 64 bits, an appropriate extension will be added after the load to
5605 /// reach a total size of 64 bits. We have to add the extension separately
5606 /// because ARM does not have a sign/zero extending load for vectors.
5607 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5608   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5609
5610   // The load already has the right type.
5611   if (ExtendedTy == LD->getMemoryVT())
5612     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5613                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5614                 LD->isNonTemporal(), LD->isInvariant(),
5615                 LD->getAlignment());
5616
5617   // We need to create a zextload/sextload. We cannot just create a load
5618   // followed by a zext/zext node because LowerMUL is also run during normal
5619   // operation legalization where we can't create illegal types.
5620   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5621                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5622                         LD->getMemoryVT(), LD->isVolatile(),
5623                         LD->isNonTemporal(), LD->getAlignment());
5624 }
5625
5626 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5627 /// extending load, or BUILD_VECTOR with extended elements, return the
5628 /// unextended value. The unextended vector should be 64 bits so that it can
5629 /// be used as an operand to a VMULL instruction. If the original vector size
5630 /// before extension is less than 64 bits we add a an extension to resize
5631 /// the vector to 64 bits.
5632 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5633   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5634     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5635                                         N->getOperand(0)->getValueType(0),
5636                                         N->getValueType(0),
5637                                         N->getOpcode());
5638
5639   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5640     return SkipLoadExtensionForVMULL(LD, DAG);
5641
5642   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5643   // have been legalized as a BITCAST from v4i32.
5644   if (N->getOpcode() == ISD::BITCAST) {
5645     SDNode *BVN = N->getOperand(0).getNode();
5646     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5647            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5648     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5649     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5650                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5651   }
5652   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5653   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5654   EVT VT = N->getValueType(0);
5655   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5656   unsigned NumElts = VT.getVectorNumElements();
5657   MVT TruncVT = MVT::getIntegerVT(EltSize);
5658   SmallVector<SDValue, 8> Ops;
5659   for (unsigned i = 0; i != NumElts; ++i) {
5660     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5661     const APInt &CInt = C->getAPIntValue();
5662     // Element types smaller than 32 bits are not legal, so use i32 elements.
5663     // The values are implicitly truncated so sext vs. zext doesn't matter.
5664     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5665   }
5666   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5667                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5668 }
5669
5670 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5671   unsigned Opcode = N->getOpcode();
5672   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5673     SDNode *N0 = N->getOperand(0).getNode();
5674     SDNode *N1 = N->getOperand(1).getNode();
5675     return N0->hasOneUse() && N1->hasOneUse() &&
5676       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5677   }
5678   return false;
5679 }
5680
5681 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5682   unsigned Opcode = N->getOpcode();
5683   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5684     SDNode *N0 = N->getOperand(0).getNode();
5685     SDNode *N1 = N->getOperand(1).getNode();
5686     return N0->hasOneUse() && N1->hasOneUse() &&
5687       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5688   }
5689   return false;
5690 }
5691
5692 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5693   // Multiplications are only custom-lowered for 128-bit vectors so that
5694   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5695   EVT VT = Op.getValueType();
5696   assert(VT.is128BitVector() && VT.isInteger() &&
5697          "unexpected type for custom-lowering ISD::MUL");
5698   SDNode *N0 = Op.getOperand(0).getNode();
5699   SDNode *N1 = Op.getOperand(1).getNode();
5700   unsigned NewOpc = 0;
5701   bool isMLA = false;
5702   bool isN0SExt = isSignExtended(N0, DAG);
5703   bool isN1SExt = isSignExtended(N1, DAG);
5704   if (isN0SExt && isN1SExt)
5705     NewOpc = ARMISD::VMULLs;
5706   else {
5707     bool isN0ZExt = isZeroExtended(N0, DAG);
5708     bool isN1ZExt = isZeroExtended(N1, DAG);
5709     if (isN0ZExt && isN1ZExt)
5710       NewOpc = ARMISD::VMULLu;
5711     else if (isN1SExt || isN1ZExt) {
5712       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5713       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5714       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5715         NewOpc = ARMISD::VMULLs;
5716         isMLA = true;
5717       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5718         NewOpc = ARMISD::VMULLu;
5719         isMLA = true;
5720       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5721         std::swap(N0, N1);
5722         NewOpc = ARMISD::VMULLu;
5723         isMLA = true;
5724       }
5725     }
5726
5727     if (!NewOpc) {
5728       if (VT == MVT::v2i64)
5729         // Fall through to expand this.  It is not legal.
5730         return SDValue();
5731       else
5732         // Other vector multiplications are legal.
5733         return Op;
5734     }
5735   }
5736
5737   // Legalize to a VMULL instruction.
5738   SDLoc DL(Op);
5739   SDValue Op0;
5740   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5741   if (!isMLA) {
5742     Op0 = SkipExtensionForVMULL(N0, DAG);
5743     assert(Op0.getValueType().is64BitVector() &&
5744            Op1.getValueType().is64BitVector() &&
5745            "unexpected types for extended operands to VMULL");
5746     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5747   }
5748
5749   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5750   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5751   //   vmull q0, d4, d6
5752   //   vmlal q0, d5, d6
5753   // is faster than
5754   //   vaddl q0, d4, d5
5755   //   vmovl q1, d6
5756   //   vmul  q0, q0, q1
5757   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5758   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5759   EVT Op1VT = Op1.getValueType();
5760   return DAG.getNode(N0->getOpcode(), DL, VT,
5761                      DAG.getNode(NewOpc, DL, VT,
5762                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5763                      DAG.getNode(NewOpc, DL, VT,
5764                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5765 }
5766
5767 static SDValue
5768 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5769   // Convert to float
5770   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5771   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5772   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5773   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5774   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5775   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5776   // Get reciprocal estimate.
5777   // float4 recip = vrecpeq_f32(yf);
5778   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5779                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5780   // Because char has a smaller range than uchar, we can actually get away
5781   // without any newton steps.  This requires that we use a weird bias
5782   // of 0xb000, however (again, this has been exhaustively tested).
5783   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5784   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5785   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5786   Y = DAG.getConstant(0xb000, MVT::i32);
5787   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5788   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5789   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5790   // Convert back to short.
5791   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5792   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5793   return X;
5794 }
5795
5796 static SDValue
5797 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5798   SDValue N2;
5799   // Convert to float.
5800   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5801   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5802   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5803   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5804   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5805   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5806
5807   // Use reciprocal estimate and one refinement step.
5808   // float4 recip = vrecpeq_f32(yf);
5809   // recip *= vrecpsq_f32(yf, recip);
5810   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5811                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5812   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5813                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5814                    N1, N2);
5815   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5816   // Because short has a smaller range than ushort, we can actually get away
5817   // with only a single newton step.  This requires that we use a weird bias
5818   // of 89, however (again, this has been exhaustively tested).
5819   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5820   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5821   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5822   N1 = DAG.getConstant(0x89, MVT::i32);
5823   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5824   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5825   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5826   // Convert back to integer and return.
5827   // return vmovn_s32(vcvt_s32_f32(result));
5828   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5829   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5830   return N0;
5831 }
5832
5833 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5834   EVT VT = Op.getValueType();
5835   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5836          "unexpected type for custom-lowering ISD::SDIV");
5837
5838   SDLoc dl(Op);
5839   SDValue N0 = Op.getOperand(0);
5840   SDValue N1 = Op.getOperand(1);
5841   SDValue N2, N3;
5842
5843   if (VT == MVT::v8i8) {
5844     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5845     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5846
5847     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5848                      DAG.getIntPtrConstant(4));
5849     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5850                      DAG.getIntPtrConstant(4));
5851     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5852                      DAG.getIntPtrConstant(0));
5853     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5854                      DAG.getIntPtrConstant(0));
5855
5856     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5857     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5858
5859     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5860     N0 = LowerCONCAT_VECTORS(N0, DAG);
5861
5862     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5863     return N0;
5864   }
5865   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5866 }
5867
5868 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5869   EVT VT = Op.getValueType();
5870   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5871          "unexpected type for custom-lowering ISD::UDIV");
5872
5873   SDLoc dl(Op);
5874   SDValue N0 = Op.getOperand(0);
5875   SDValue N1 = Op.getOperand(1);
5876   SDValue N2, N3;
5877
5878   if (VT == MVT::v8i8) {
5879     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5880     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5881
5882     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5883                      DAG.getIntPtrConstant(4));
5884     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5885                      DAG.getIntPtrConstant(4));
5886     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5887                      DAG.getIntPtrConstant(0));
5888     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5889                      DAG.getIntPtrConstant(0));
5890
5891     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5892     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5893
5894     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5895     N0 = LowerCONCAT_VECTORS(N0, DAG);
5896
5897     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5898                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5899                      N0);
5900     return N0;
5901   }
5902
5903   // v4i16 sdiv ... Convert to float.
5904   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5905   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5906   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5907   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5908   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5909   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5910
5911   // Use reciprocal estimate and two refinement steps.
5912   // float4 recip = vrecpeq_f32(yf);
5913   // recip *= vrecpsq_f32(yf, recip);
5914   // recip *= vrecpsq_f32(yf, recip);
5915   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5916                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5917   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5918                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5919                    BN1, N2);
5920   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5921   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5922                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5923                    BN1, N2);
5924   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5925   // Simply multiplying by the reciprocal estimate can leave us a few ulps
5926   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5927   // and that it will never cause us to return an answer too large).
5928   // float4 result = as_float4(as_int4(xf*recip) + 2);
5929   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5930   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5931   N1 = DAG.getConstant(2, MVT::i32);
5932   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5933   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5934   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5935   // Convert back to integer and return.
5936   // return vmovn_u32(vcvt_s32_f32(result));
5937   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5938   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5939   return N0;
5940 }
5941
5942 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5943   EVT VT = Op.getNode()->getValueType(0);
5944   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5945
5946   unsigned Opc;
5947   bool ExtraOp = false;
5948   switch (Op.getOpcode()) {
5949   default: llvm_unreachable("Invalid code");
5950   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5951   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5952   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5953   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5954   }
5955
5956   if (!ExtraOp)
5957     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5958                        Op.getOperand(1));
5959   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5960                      Op.getOperand(1), Op.getOperand(2));
5961 }
5962
5963 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
5964   assert(Subtarget->isTargetDarwin());
5965
5966   // For iOS, we want to call an alternative entry point: __sincos_stret,
5967   // return values are passed via sret.
5968   SDLoc dl(Op);
5969   SDValue Arg = Op.getOperand(0);
5970   EVT ArgVT = Arg.getValueType();
5971   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
5972
5973   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
5974   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5975
5976   // Pair of floats / doubles used to pass the result.
5977   StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
5978
5979   // Create stack object for sret.
5980   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
5981   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
5982   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
5983   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
5984
5985   ArgListTy Args;
5986   ArgListEntry Entry;
5987
5988   Entry.Node = SRet;
5989   Entry.Ty = RetTy->getPointerTo();
5990   Entry.isSExt = false;
5991   Entry.isZExt = false;
5992   Entry.isSRet = true;
5993   Args.push_back(Entry);
5994
5995   Entry.Node = Arg;
5996   Entry.Ty = ArgTy;
5997   Entry.isSExt = false;
5998   Entry.isZExt = false;
5999   Args.push_back(Entry);
6000
6001   const char *LibcallName  = (ArgVT == MVT::f64)
6002   ? "__sincos_stret" : "__sincosf_stret";
6003   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6004
6005   TargetLowering::
6006   CallLoweringInfo CLI(DAG.getEntryNode(), Type::getVoidTy(*DAG.getContext()),
6007                        false, false, false, false, 0,
6008                        CallingConv::C, /*isTaillCall=*/false,
6009                        /*doesNotRet=*/false, /*isReturnValueUsed*/false,
6010                        Callee, Args, DAG, dl);
6011   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6012
6013   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6014                                 MachinePointerInfo(), false, false, false, 0);
6015
6016   // Address of cos field.
6017   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6018                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6019   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6020                                 MachinePointerInfo(), false, false, false, 0);
6021
6022   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6023   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6024                      LoadSin.getValue(0), LoadCos.getValue(0));
6025 }
6026
6027 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6028   // Monotonic load/store is legal for all targets
6029   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6030     return Op;
6031
6032   // Acquire/Release load/store is not legal for targets without a
6033   // dmb or equivalent available.
6034   return SDValue();
6035 }
6036
6037 static void
6038 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
6039                     SelectionDAG &DAG) {
6040   SDLoc dl(Node);
6041   assert (Node->getValueType(0) == MVT::i64 &&
6042           "Only know how to expand i64 atomics");
6043   AtomicSDNode *AN = cast<AtomicSDNode>(Node);
6044
6045   SmallVector<SDValue, 6> Ops;
6046   Ops.push_back(Node->getOperand(0)); // Chain
6047   Ops.push_back(Node->getOperand(1)); // Ptr
6048   for(unsigned i=2; i<Node->getNumOperands(); i++) {
6049     // Low part
6050     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6051                               Node->getOperand(i), DAG.getIntPtrConstant(0)));
6052     // High part
6053     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6054                               Node->getOperand(i), DAG.getIntPtrConstant(1)));
6055   }
6056   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6057   SDValue Result = DAG.getAtomic(
6058       Node->getOpcode(), dl, MVT::i64, Tys, Ops.data(), Ops.size(),
6059       cast<MemSDNode>(Node)->getMemOperand(), AN->getSuccessOrdering(),
6060       AN->getFailureOrdering(), AN->getSynchScope());
6061   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
6062   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6063   Results.push_back(Result.getValue(2));
6064 }
6065
6066 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6067                                     SmallVectorImpl<SDValue> &Results,
6068                                     SelectionDAG &DAG,
6069                                     const ARMSubtarget *Subtarget) {
6070   SDLoc DL(N);
6071   SDValue Cycles32, OutChain;
6072
6073   if (Subtarget->hasPerfMon()) {
6074     // Under Power Management extensions, the cycle-count is:
6075     //    mrc p15, #0, <Rt>, c9, c13, #0
6076     SDValue Ops[] = { N->getOperand(0), // Chain
6077                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6078                       DAG.getConstant(15, MVT::i32),
6079                       DAG.getConstant(0, MVT::i32),
6080                       DAG.getConstant(9, MVT::i32),
6081                       DAG.getConstant(13, MVT::i32),
6082                       DAG.getConstant(0, MVT::i32)
6083     };
6084
6085     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6086                            DAG.getVTList(MVT::i32, MVT::Other), &Ops[0],
6087                            array_lengthof(Ops));
6088     OutChain = Cycles32.getValue(1);
6089   } else {
6090     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6091     // there are older ARM CPUs that have implementation-specific ways of
6092     // obtaining this information (FIXME!).
6093     Cycles32 = DAG.getConstant(0, MVT::i32);
6094     OutChain = DAG.getEntryNode();
6095   }
6096
6097
6098   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6099                                  Cycles32, DAG.getConstant(0, MVT::i32));
6100   Results.push_back(Cycles64);
6101   Results.push_back(OutChain);
6102 }
6103
6104 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6105   switch (Op.getOpcode()) {
6106   default: llvm_unreachable("Don't know how to custom lower this!");
6107   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6108   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6109   case ISD::GlobalAddress:
6110     return Subtarget->isTargetMachO() ? LowerGlobalAddressDarwin(Op, DAG) :
6111       LowerGlobalAddressELF(Op, DAG);
6112   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6113   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6114   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6115   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6116   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6117   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6118   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6119   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6120   case ISD::SINT_TO_FP:
6121   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6122   case ISD::FP_TO_SINT:
6123   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6124   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6125   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6126   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6127   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6128   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6129   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6130   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6131                                                                Subtarget);
6132   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6133   case ISD::SHL:
6134   case ISD::SRL:
6135   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6136   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6137   case ISD::SRL_PARTS:
6138   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6139   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6140   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6141   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6142   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6143   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6144   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6145   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6146   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6147   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6148   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6149   case ISD::MUL:           return LowerMUL(Op, DAG);
6150   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6151   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6152   case ISD::ADDC:
6153   case ISD::ADDE:
6154   case ISD::SUBC:
6155   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6156   case ISD::ATOMIC_LOAD:
6157   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6158   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6159   case ISD::SDIVREM:
6160   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6161   }
6162 }
6163
6164 /// ReplaceNodeResults - Replace the results of node with an illegal result
6165 /// type with new values built out of custom code.
6166 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6167                                            SmallVectorImpl<SDValue>&Results,
6168                                            SelectionDAG &DAG) const {
6169   SDValue Res;
6170   switch (N->getOpcode()) {
6171   default:
6172     llvm_unreachable("Don't know how to custom expand this!");
6173   case ISD::BITCAST:
6174     Res = ExpandBITCAST(N, DAG);
6175     break;
6176   case ISD::SRL:
6177   case ISD::SRA:
6178     Res = Expand64BitShift(N, DAG, Subtarget);
6179     break;
6180   case ISD::READCYCLECOUNTER:
6181     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6182     return;
6183   case ISD::ATOMIC_STORE:
6184   case ISD::ATOMIC_LOAD:
6185   case ISD::ATOMIC_LOAD_ADD:
6186   case ISD::ATOMIC_LOAD_AND:
6187   case ISD::ATOMIC_LOAD_NAND:
6188   case ISD::ATOMIC_LOAD_OR:
6189   case ISD::ATOMIC_LOAD_SUB:
6190   case ISD::ATOMIC_LOAD_XOR:
6191   case ISD::ATOMIC_SWAP:
6192   case ISD::ATOMIC_CMP_SWAP:
6193   case ISD::ATOMIC_LOAD_MIN:
6194   case ISD::ATOMIC_LOAD_UMIN:
6195   case ISD::ATOMIC_LOAD_MAX:
6196   case ISD::ATOMIC_LOAD_UMAX:
6197     ReplaceATOMIC_OP_64(N, Results, DAG);
6198     return;
6199   }
6200   if (Res.getNode())
6201     Results.push_back(Res);
6202 }
6203
6204 //===----------------------------------------------------------------------===//
6205 //                           ARM Scheduler Hooks
6206 //===----------------------------------------------------------------------===//
6207
6208 MachineBasicBlock *
6209 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
6210                                      MachineBasicBlock *BB,
6211                                      unsigned Size) const {
6212   unsigned dest    = MI->getOperand(0).getReg();
6213   unsigned ptr     = MI->getOperand(1).getReg();
6214   unsigned oldval  = MI->getOperand(2).getReg();
6215   unsigned newval  = MI->getOperand(3).getReg();
6216   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6217   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(4).getImm());
6218   DebugLoc dl = MI->getDebugLoc();
6219   bool isThumb2 = Subtarget->isThumb2();
6220
6221   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6222   unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
6223     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6224     (const TargetRegisterClass*)&ARM::GPRRegClass);
6225
6226   if (isThumb2) {
6227     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6228     MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
6229     MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
6230   }
6231
6232   unsigned ldrOpc, strOpc;
6233   getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6234
6235   MachineFunction *MF = BB->getParent();
6236   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6237   MachineFunction::iterator It = BB;
6238   ++It; // insert the new blocks after the current block
6239
6240   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6241   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6242   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6243   MF->insert(It, loop1MBB);
6244   MF->insert(It, loop2MBB);
6245   MF->insert(It, exitMBB);
6246
6247   // Transfer the remainder of BB and its successor edges to exitMBB.
6248   exitMBB->splice(exitMBB->begin(), BB,
6249                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6250   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6251
6252   //  thisMBB:
6253   //   ...
6254   //   fallthrough --> loop1MBB
6255   BB->addSuccessor(loop1MBB);
6256
6257   // loop1MBB:
6258   //   ldrex dest, [ptr]
6259   //   cmp dest, oldval
6260   //   bne exitMBB
6261   BB = loop1MBB;
6262   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6263   if (ldrOpc == ARM::t2LDREX)
6264     MIB.addImm(0);
6265   AddDefaultPred(MIB);
6266   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6267                  .addReg(dest).addReg(oldval));
6268   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6269     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6270   BB->addSuccessor(loop2MBB);
6271   BB->addSuccessor(exitMBB);
6272
6273   // loop2MBB:
6274   //   strex scratch, newval, [ptr]
6275   //   cmp scratch, #0
6276   //   bne loop1MBB
6277   BB = loop2MBB;
6278   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
6279   if (strOpc == ARM::t2STREX)
6280     MIB.addImm(0);
6281   AddDefaultPred(MIB);
6282   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6283                  .addReg(scratch).addImm(0));
6284   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6285     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6286   BB->addSuccessor(loop1MBB);
6287   BB->addSuccessor(exitMBB);
6288
6289   //  exitMBB:
6290   //   ...
6291   BB = exitMBB;
6292
6293   MI->eraseFromParent();   // The instruction is gone now.
6294
6295   return BB;
6296 }
6297
6298 MachineBasicBlock *
6299 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6300                                     unsigned Size, unsigned BinOpcode) const {
6301   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6302   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6303
6304   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6305   MachineFunction *MF = BB->getParent();
6306   MachineFunction::iterator It = BB;
6307   ++It;
6308
6309   unsigned dest = MI->getOperand(0).getReg();
6310   unsigned ptr = MI->getOperand(1).getReg();
6311   unsigned incr = MI->getOperand(2).getReg();
6312   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6313   DebugLoc dl = MI->getDebugLoc();
6314   bool isThumb2 = Subtarget->isThumb2();
6315
6316   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6317   if (isThumb2) {
6318     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6319     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6320     MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6321   }
6322
6323   unsigned ldrOpc, strOpc;
6324   getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6325
6326   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6327   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6328   MF->insert(It, loopMBB);
6329   MF->insert(It, exitMBB);
6330
6331   // Transfer the remainder of BB and its successor edges to exitMBB.
6332   exitMBB->splice(exitMBB->begin(), BB,
6333                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6334   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6335
6336   const TargetRegisterClass *TRC = isThumb2 ?
6337     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6338     (const TargetRegisterClass*)&ARM::GPRRegClass;
6339   unsigned scratch = MRI.createVirtualRegister(TRC);
6340   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
6341
6342   //  thisMBB:
6343   //   ...
6344   //   fallthrough --> loopMBB
6345   BB->addSuccessor(loopMBB);
6346
6347   //  loopMBB:
6348   //   ldrex dest, ptr
6349   //   <binop> scratch2, dest, incr
6350   //   strex scratch, scratch2, ptr
6351   //   cmp scratch, #0
6352   //   bne- loopMBB
6353   //   fallthrough --> exitMBB
6354   BB = loopMBB;
6355   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6356   if (ldrOpc == ARM::t2LDREX)
6357     MIB.addImm(0);
6358   AddDefaultPred(MIB);
6359   if (BinOpcode) {
6360     // operand order needs to go the other way for NAND
6361     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
6362       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6363                      addReg(incr).addReg(dest)).addReg(0);
6364     else
6365       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6366                      addReg(dest).addReg(incr)).addReg(0);
6367   }
6368
6369   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6370   if (strOpc == ARM::t2STREX)
6371     MIB.addImm(0);
6372   AddDefaultPred(MIB);
6373   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6374                  .addReg(scratch).addImm(0));
6375   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6376     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6377
6378   BB->addSuccessor(loopMBB);
6379   BB->addSuccessor(exitMBB);
6380
6381   //  exitMBB:
6382   //   ...
6383   BB = exitMBB;
6384
6385   MI->eraseFromParent();   // The instruction is gone now.
6386
6387   return BB;
6388 }
6389
6390 MachineBasicBlock *
6391 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
6392                                           MachineBasicBlock *BB,
6393                                           unsigned Size,
6394                                           bool signExtend,
6395                                           ARMCC::CondCodes Cond) const {
6396   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6397
6398   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6399   MachineFunction *MF = BB->getParent();
6400   MachineFunction::iterator It = BB;
6401   ++It;
6402
6403   unsigned dest = MI->getOperand(0).getReg();
6404   unsigned ptr = MI->getOperand(1).getReg();
6405   unsigned incr = MI->getOperand(2).getReg();
6406   unsigned oldval = dest;
6407   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6408   DebugLoc dl = MI->getDebugLoc();
6409   bool isThumb2 = Subtarget->isThumb2();
6410
6411   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6412   if (isThumb2) {
6413     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6414     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6415     MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6416   }
6417
6418   unsigned ldrOpc, strOpc, extendOpc;
6419   getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6420   switch (Size) {
6421   default: llvm_unreachable("unsupported size for AtomicBinaryMinMax!");
6422   case 1:
6423     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
6424     break;
6425   case 2:
6426     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
6427     break;
6428   case 4:
6429     extendOpc = 0;
6430     break;
6431   }
6432
6433   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6434   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6435   MF->insert(It, loopMBB);
6436   MF->insert(It, exitMBB);
6437
6438   // Transfer the remainder of BB and its successor edges to exitMBB.
6439   exitMBB->splice(exitMBB->begin(), BB,
6440                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6441   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6442
6443   const TargetRegisterClass *TRC = isThumb2 ?
6444     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6445     (const TargetRegisterClass*)&ARM::GPRRegClass;
6446   unsigned scratch = MRI.createVirtualRegister(TRC);
6447   unsigned scratch2 = MRI.createVirtualRegister(TRC);
6448
6449   //  thisMBB:
6450   //   ...
6451   //   fallthrough --> loopMBB
6452   BB->addSuccessor(loopMBB);
6453
6454   //  loopMBB:
6455   //   ldrex dest, ptr
6456   //   (sign extend dest, if required)
6457   //   cmp dest, incr
6458   //   cmov.cond scratch2, incr, dest
6459   //   strex scratch, scratch2, ptr
6460   //   cmp scratch, #0
6461   //   bne- loopMBB
6462   //   fallthrough --> exitMBB
6463   BB = loopMBB;
6464   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6465   if (ldrOpc == ARM::t2LDREX)
6466     MIB.addImm(0);
6467   AddDefaultPred(MIB);
6468
6469   // Sign extend the value, if necessary.
6470   if (signExtend && extendOpc) {
6471     oldval = MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass
6472                                                 : &ARM::GPRnopcRegClass);
6473     if (!isThumb2)
6474       MRI.constrainRegClass(dest, &ARM::GPRnopcRegClass);
6475     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
6476                      .addReg(dest)
6477                      .addImm(0));
6478   }
6479
6480   // Build compare and cmov instructions.
6481   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6482                  .addReg(oldval).addReg(incr));
6483   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
6484          .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
6485
6486   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6487   if (strOpc == ARM::t2STREX)
6488     MIB.addImm(0);
6489   AddDefaultPred(MIB);
6490   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6491                  .addReg(scratch).addImm(0));
6492   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6493     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6494
6495   BB->addSuccessor(loopMBB);
6496   BB->addSuccessor(exitMBB);
6497
6498   //  exitMBB:
6499   //   ...
6500   BB = exitMBB;
6501
6502   MI->eraseFromParent();   // The instruction is gone now.
6503
6504   return BB;
6505 }
6506
6507 MachineBasicBlock *
6508 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
6509                                       unsigned Op1, unsigned Op2,
6510                                       bool NeedsCarry, bool IsCmpxchg,
6511                                       bool IsMinMax, ARMCC::CondCodes CC) const {
6512   // This also handles ATOMIC_SWAP and ATOMIC_STORE, indicated by Op1==0.
6513   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6514
6515   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6516   MachineFunction *MF = BB->getParent();
6517   MachineFunction::iterator It = BB;
6518   ++It;
6519
6520   unsigned destlo = MI->getOperand(0).getReg();
6521   unsigned desthi = MI->getOperand(1).getReg();
6522   unsigned ptr = MI->getOperand(2).getReg();
6523   unsigned vallo = MI->getOperand(3).getReg();
6524   unsigned valhi = MI->getOperand(4).getReg();
6525   AtomicOrdering Ord =
6526       static_cast<AtomicOrdering>(MI->getOperand(IsCmpxchg ? 7 : 5).getImm());
6527   DebugLoc dl = MI->getDebugLoc();
6528   bool isThumb2 = Subtarget->isThumb2();
6529
6530   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6531   if (isThumb2) {
6532     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6533     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6534     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6535     MRI.constrainRegClass(vallo, &ARM::rGPRRegClass);
6536     MRI.constrainRegClass(valhi, &ARM::rGPRRegClass);
6537   }
6538
6539   unsigned ldrOpc, strOpc;
6540   getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6541
6542   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6543   MachineBasicBlock *contBB = 0, *cont2BB = 0;
6544   if (IsCmpxchg || IsMinMax)
6545     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
6546   if (IsCmpxchg)
6547     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
6548   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6549
6550   MF->insert(It, loopMBB);
6551   if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6552   if (IsCmpxchg) MF->insert(It, cont2BB);
6553   MF->insert(It, exitMBB);
6554
6555   // Transfer the remainder of BB and its successor edges to exitMBB.
6556   exitMBB->splice(exitMBB->begin(), BB,
6557                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6558   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6559
6560   const TargetRegisterClass *TRC = isThumb2 ?
6561     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6562     (const TargetRegisterClass*)&ARM::GPRRegClass;
6563   unsigned storesuccess = MRI.createVirtualRegister(TRC);
6564
6565   //  thisMBB:
6566   //   ...
6567   //   fallthrough --> loopMBB
6568   BB->addSuccessor(loopMBB);
6569
6570   //  loopMBB:
6571   //   ldrexd r2, r3, ptr
6572   //   <binopa> r0, r2, incr
6573   //   <binopb> r1, r3, incr
6574   //   strexd storesuccess, r0, r1, ptr
6575   //   cmp storesuccess, #0
6576   //   bne- loopMBB
6577   //   fallthrough --> exitMBB
6578   BB = loopMBB;
6579
6580   // Load
6581   if (isThumb2) {
6582     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6583                        .addReg(destlo, RegState::Define)
6584                        .addReg(desthi, RegState::Define)
6585                        .addReg(ptr));
6586   } else {
6587     unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6588     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6589                        .addReg(GPRPair0, RegState::Define)
6590                        .addReg(ptr));
6591     // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
6592     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6593         .addReg(GPRPair0, 0, ARM::gsub_0);
6594     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6595         .addReg(GPRPair0, 0, ARM::gsub_1);
6596   }
6597
6598   unsigned StoreLo, StoreHi;
6599   if (IsCmpxchg) {
6600     // Add early exit
6601     for (unsigned i = 0; i < 2; i++) {
6602       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6603                                                          ARM::CMPrr))
6604                      .addReg(i == 0 ? destlo : desthi)
6605                      .addReg(i == 0 ? vallo : valhi));
6606       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6607         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6608       BB->addSuccessor(exitMBB);
6609       BB->addSuccessor(i == 0 ? contBB : cont2BB);
6610       BB = (i == 0 ? contBB : cont2BB);
6611     }
6612
6613     // Copy to physregs for strexd
6614     StoreLo = MI->getOperand(5).getReg();
6615     StoreHi = MI->getOperand(6).getReg();
6616   } else if (Op1) {
6617     // Perform binary operation
6618     unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6619     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6620                    .addReg(destlo).addReg(vallo))
6621         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6622     unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6623     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6624                    .addReg(desthi).addReg(valhi))
6625         .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6626
6627     StoreLo = tmpRegLo;
6628     StoreHi = tmpRegHi;
6629   } else {
6630     // Copy to physregs for strexd
6631     StoreLo = vallo;
6632     StoreHi = valhi;
6633   }
6634   if (IsMinMax) {
6635     // Compare and branch to exit block.
6636     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6637       .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6638     BB->addSuccessor(exitMBB);
6639     BB->addSuccessor(contBB);
6640     BB = contBB;
6641     StoreLo = vallo;
6642     StoreHi = valhi;
6643   }
6644
6645   // Store
6646   if (isThumb2) {
6647     MRI.constrainRegClass(StoreLo, &ARM::rGPRRegClass);
6648     MRI.constrainRegClass(StoreHi, &ARM::rGPRRegClass);
6649     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6650                    .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6651   } else {
6652     // Marshal a pair...
6653     unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6654     unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6655     unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6656     BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6657     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6658       .addReg(UndefPair)
6659       .addReg(StoreLo)
6660       .addImm(ARM::gsub_0);
6661     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6662       .addReg(r1)
6663       .addReg(StoreHi)
6664       .addImm(ARM::gsub_1);
6665
6666     // ...and store it
6667     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6668                    .addReg(StorePair).addReg(ptr));
6669   }
6670   // Cmp+jump
6671   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6672                  .addReg(storesuccess).addImm(0));
6673   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6674     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6675
6676   BB->addSuccessor(loopMBB);
6677   BB->addSuccessor(exitMBB);
6678
6679   //  exitMBB:
6680   //   ...
6681   BB = exitMBB;
6682
6683   MI->eraseFromParent();   // The instruction is gone now.
6684
6685   return BB;
6686 }
6687
6688 MachineBasicBlock *
6689 ARMTargetLowering::EmitAtomicLoad64(MachineInstr *MI, MachineBasicBlock *BB) const {
6690
6691   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6692
6693   unsigned destlo = MI->getOperand(0).getReg();
6694   unsigned desthi = MI->getOperand(1).getReg();
6695   unsigned ptr = MI->getOperand(2).getReg();
6696   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6697   DebugLoc dl = MI->getDebugLoc();
6698   bool isThumb2 = Subtarget->isThumb2();
6699
6700   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6701   if (isThumb2) {
6702     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6703     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6704     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6705   }
6706   unsigned ldrOpc, strOpc;
6707   getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6708
6709   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(ldrOpc));
6710
6711   if (isThumb2) {
6712     MIB.addReg(destlo, RegState::Define)
6713        .addReg(desthi, RegState::Define)
6714        .addReg(ptr);
6715
6716   } else {
6717     unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6718     MIB.addReg(GPRPair0, RegState::Define).addReg(ptr);
6719
6720     // Copy GPRPair0 into dest.  (This copy will normally be coalesced.)
6721     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), destlo)
6722       .addReg(GPRPair0, 0, ARM::gsub_0);
6723     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), desthi)
6724       .addReg(GPRPair0, 0, ARM::gsub_1);
6725   }
6726   AddDefaultPred(MIB);
6727
6728   MI->eraseFromParent();   // The instruction is gone now.
6729
6730   return BB;
6731 }
6732
6733 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6734 /// registers the function context.
6735 void ARMTargetLowering::
6736 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6737                        MachineBasicBlock *DispatchBB, int FI) const {
6738   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6739   DebugLoc dl = MI->getDebugLoc();
6740   MachineFunction *MF = MBB->getParent();
6741   MachineRegisterInfo *MRI = &MF->getRegInfo();
6742   MachineConstantPool *MCP = MF->getConstantPool();
6743   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6744   const Function *F = MF->getFunction();
6745
6746   bool isThumb = Subtarget->isThumb();
6747   bool isThumb2 = Subtarget->isThumb2();
6748
6749   unsigned PCLabelId = AFI->createPICLabelUId();
6750   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6751   ARMConstantPoolValue *CPV =
6752     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6753   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6754
6755   const TargetRegisterClass *TRC = isThumb ?
6756     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6757     (const TargetRegisterClass*)&ARM::GPRRegClass;
6758
6759   // Grab constant pool and fixed stack memory operands.
6760   MachineMemOperand *CPMMO =
6761     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6762                              MachineMemOperand::MOLoad, 4, 4);
6763
6764   MachineMemOperand *FIMMOSt =
6765     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6766                              MachineMemOperand::MOStore, 4, 4);
6767
6768   // Load the address of the dispatch MBB into the jump buffer.
6769   if (isThumb2) {
6770     // Incoming value: jbuf
6771     //   ldr.n  r5, LCPI1_1
6772     //   orr    r5, r5, #1
6773     //   add    r5, pc
6774     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6775     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6776     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6777                    .addConstantPoolIndex(CPI)
6778                    .addMemOperand(CPMMO));
6779     // Set the low bit because of thumb mode.
6780     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6781     AddDefaultCC(
6782       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6783                      .addReg(NewVReg1, RegState::Kill)
6784                      .addImm(0x01)));
6785     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6786     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6787       .addReg(NewVReg2, RegState::Kill)
6788       .addImm(PCLabelId);
6789     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6790                    .addReg(NewVReg3, RegState::Kill)
6791                    .addFrameIndex(FI)
6792                    .addImm(36)  // &jbuf[1] :: pc
6793                    .addMemOperand(FIMMOSt));
6794   } else if (isThumb) {
6795     // Incoming value: jbuf
6796     //   ldr.n  r1, LCPI1_4
6797     //   add    r1, pc
6798     //   mov    r2, #1
6799     //   orrs   r1, r2
6800     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6801     //   str    r1, [r2]
6802     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6803     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6804                    .addConstantPoolIndex(CPI)
6805                    .addMemOperand(CPMMO));
6806     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6807     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6808       .addReg(NewVReg1, RegState::Kill)
6809       .addImm(PCLabelId);
6810     // Set the low bit because of thumb mode.
6811     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6812     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6813                    .addReg(ARM::CPSR, RegState::Define)
6814                    .addImm(1));
6815     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6816     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6817                    .addReg(ARM::CPSR, RegState::Define)
6818                    .addReg(NewVReg2, RegState::Kill)
6819                    .addReg(NewVReg3, RegState::Kill));
6820     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6821     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6822                    .addFrameIndex(FI)
6823                    .addImm(36)); // &jbuf[1] :: pc
6824     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6825                    .addReg(NewVReg4, RegState::Kill)
6826                    .addReg(NewVReg5, RegState::Kill)
6827                    .addImm(0)
6828                    .addMemOperand(FIMMOSt));
6829   } else {
6830     // Incoming value: jbuf
6831     //   ldr  r1, LCPI1_1
6832     //   add  r1, pc, r1
6833     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6834     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6835     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6836                    .addConstantPoolIndex(CPI)
6837                    .addImm(0)
6838                    .addMemOperand(CPMMO));
6839     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6840     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6841                    .addReg(NewVReg1, RegState::Kill)
6842                    .addImm(PCLabelId));
6843     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6844                    .addReg(NewVReg2, RegState::Kill)
6845                    .addFrameIndex(FI)
6846                    .addImm(36)  // &jbuf[1] :: pc
6847                    .addMemOperand(FIMMOSt));
6848   }
6849 }
6850
6851 MachineBasicBlock *ARMTargetLowering::
6852 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6853   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6854   DebugLoc dl = MI->getDebugLoc();
6855   MachineFunction *MF = MBB->getParent();
6856   MachineRegisterInfo *MRI = &MF->getRegInfo();
6857   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6858   MachineFrameInfo *MFI = MF->getFrameInfo();
6859   int FI = MFI->getFunctionContextIndex();
6860
6861   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6862     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6863     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6864
6865   // Get a mapping of the call site numbers to all of the landing pads they're
6866   // associated with.
6867   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6868   unsigned MaxCSNum = 0;
6869   MachineModuleInfo &MMI = MF->getMMI();
6870   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6871        ++BB) {
6872     if (!BB->isLandingPad()) continue;
6873
6874     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6875     // pad.
6876     for (MachineBasicBlock::iterator
6877            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6878       if (!II->isEHLabel()) continue;
6879
6880       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6881       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6882
6883       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6884       for (SmallVectorImpl<unsigned>::iterator
6885              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6886            CSI != CSE; ++CSI) {
6887         CallSiteNumToLPad[*CSI].push_back(BB);
6888         MaxCSNum = std::max(MaxCSNum, *CSI);
6889       }
6890       break;
6891     }
6892   }
6893
6894   // Get an ordered list of the machine basic blocks for the jump table.
6895   std::vector<MachineBasicBlock*> LPadList;
6896   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6897   LPadList.reserve(CallSiteNumToLPad.size());
6898   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6899     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6900     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6901            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6902       LPadList.push_back(*II);
6903       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6904     }
6905   }
6906
6907   assert(!LPadList.empty() &&
6908          "No landing pad destinations for the dispatch jump table!");
6909
6910   // Create the jump table and associated information.
6911   MachineJumpTableInfo *JTI =
6912     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6913   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6914   unsigned UId = AFI->createJumpTableUId();
6915   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6916
6917   // Create the MBBs for the dispatch code.
6918
6919   // Shove the dispatch's address into the return slot in the function context.
6920   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6921   DispatchBB->setIsLandingPad();
6922
6923   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6924   unsigned trap_opcode;
6925   if (Subtarget->isThumb())
6926     trap_opcode = ARM::tTRAP;
6927   else
6928     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6929
6930   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6931   DispatchBB->addSuccessor(TrapBB);
6932
6933   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6934   DispatchBB->addSuccessor(DispContBB);
6935
6936   // Insert and MBBs.
6937   MF->insert(MF->end(), DispatchBB);
6938   MF->insert(MF->end(), DispContBB);
6939   MF->insert(MF->end(), TrapBB);
6940
6941   // Insert code into the entry block that creates and registers the function
6942   // context.
6943   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6944
6945   MachineMemOperand *FIMMOLd =
6946     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6947                              MachineMemOperand::MOLoad |
6948                              MachineMemOperand::MOVolatile, 4, 4);
6949
6950   MachineInstrBuilder MIB;
6951   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6952
6953   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6954   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6955
6956   // Add a register mask with no preserved registers.  This results in all
6957   // registers being marked as clobbered.
6958   MIB.addRegMask(RI.getNoPreservedMask());
6959
6960   unsigned NumLPads = LPadList.size();
6961   if (Subtarget->isThumb2()) {
6962     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6963     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6964                    .addFrameIndex(FI)
6965                    .addImm(4)
6966                    .addMemOperand(FIMMOLd));
6967
6968     if (NumLPads < 256) {
6969       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6970                      .addReg(NewVReg1)
6971                      .addImm(LPadList.size()));
6972     } else {
6973       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6974       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6975                      .addImm(NumLPads & 0xFFFF));
6976
6977       unsigned VReg2 = VReg1;
6978       if ((NumLPads & 0xFFFF0000) != 0) {
6979         VReg2 = MRI->createVirtualRegister(TRC);
6980         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6981                        .addReg(VReg1)
6982                        .addImm(NumLPads >> 16));
6983       }
6984
6985       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6986                      .addReg(NewVReg1)
6987                      .addReg(VReg2));
6988     }
6989
6990     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6991       .addMBB(TrapBB)
6992       .addImm(ARMCC::HI)
6993       .addReg(ARM::CPSR);
6994
6995     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6996     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6997                    .addJumpTableIndex(MJTI)
6998                    .addImm(UId));
6999
7000     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7001     AddDefaultCC(
7002       AddDefaultPred(
7003         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7004         .addReg(NewVReg3, RegState::Kill)
7005         .addReg(NewVReg1)
7006         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7007
7008     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7009       .addReg(NewVReg4, RegState::Kill)
7010       .addReg(NewVReg1)
7011       .addJumpTableIndex(MJTI)
7012       .addImm(UId);
7013   } else if (Subtarget->isThumb()) {
7014     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7015     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7016                    .addFrameIndex(FI)
7017                    .addImm(1)
7018                    .addMemOperand(FIMMOLd));
7019
7020     if (NumLPads < 256) {
7021       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7022                      .addReg(NewVReg1)
7023                      .addImm(NumLPads));
7024     } else {
7025       MachineConstantPool *ConstantPool = MF->getConstantPool();
7026       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7027       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7028
7029       // MachineConstantPool wants an explicit alignment.
7030       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7031       if (Align == 0)
7032         Align = getDataLayout()->getTypeAllocSize(C->getType());
7033       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7034
7035       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7036       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7037                      .addReg(VReg1, RegState::Define)
7038                      .addConstantPoolIndex(Idx));
7039       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7040                      .addReg(NewVReg1)
7041                      .addReg(VReg1));
7042     }
7043
7044     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7045       .addMBB(TrapBB)
7046       .addImm(ARMCC::HI)
7047       .addReg(ARM::CPSR);
7048
7049     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7050     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7051                    .addReg(ARM::CPSR, RegState::Define)
7052                    .addReg(NewVReg1)
7053                    .addImm(2));
7054
7055     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7056     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7057                    .addJumpTableIndex(MJTI)
7058                    .addImm(UId));
7059
7060     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7061     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7062                    .addReg(ARM::CPSR, RegState::Define)
7063                    .addReg(NewVReg2, RegState::Kill)
7064                    .addReg(NewVReg3));
7065
7066     MachineMemOperand *JTMMOLd =
7067       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7068                                MachineMemOperand::MOLoad, 4, 4);
7069
7070     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7071     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7072                    .addReg(NewVReg4, RegState::Kill)
7073                    .addImm(0)
7074                    .addMemOperand(JTMMOLd));
7075
7076     unsigned NewVReg6 = NewVReg5;
7077     if (RelocM == Reloc::PIC_) {
7078       NewVReg6 = MRI->createVirtualRegister(TRC);
7079       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7080                      .addReg(ARM::CPSR, RegState::Define)
7081                      .addReg(NewVReg5, RegState::Kill)
7082                      .addReg(NewVReg3));
7083     }
7084
7085     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7086       .addReg(NewVReg6, RegState::Kill)
7087       .addJumpTableIndex(MJTI)
7088       .addImm(UId);
7089   } else {
7090     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7091     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7092                    .addFrameIndex(FI)
7093                    .addImm(4)
7094                    .addMemOperand(FIMMOLd));
7095
7096     if (NumLPads < 256) {
7097       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7098                      .addReg(NewVReg1)
7099                      .addImm(NumLPads));
7100     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7101       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7102       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7103                      .addImm(NumLPads & 0xFFFF));
7104
7105       unsigned VReg2 = VReg1;
7106       if ((NumLPads & 0xFFFF0000) != 0) {
7107         VReg2 = MRI->createVirtualRegister(TRC);
7108         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7109                        .addReg(VReg1)
7110                        .addImm(NumLPads >> 16));
7111       }
7112
7113       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7114                      .addReg(NewVReg1)
7115                      .addReg(VReg2));
7116     } else {
7117       MachineConstantPool *ConstantPool = MF->getConstantPool();
7118       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7119       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7120
7121       // MachineConstantPool wants an explicit alignment.
7122       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7123       if (Align == 0)
7124         Align = getDataLayout()->getTypeAllocSize(C->getType());
7125       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7126
7127       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7128       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7129                      .addReg(VReg1, RegState::Define)
7130                      .addConstantPoolIndex(Idx)
7131                      .addImm(0));
7132       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7133                      .addReg(NewVReg1)
7134                      .addReg(VReg1, RegState::Kill));
7135     }
7136
7137     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7138       .addMBB(TrapBB)
7139       .addImm(ARMCC::HI)
7140       .addReg(ARM::CPSR);
7141
7142     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7143     AddDefaultCC(
7144       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7145                      .addReg(NewVReg1)
7146                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7147     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7148     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7149                    .addJumpTableIndex(MJTI)
7150                    .addImm(UId));
7151
7152     MachineMemOperand *JTMMOLd =
7153       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7154                                MachineMemOperand::MOLoad, 4, 4);
7155     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7156     AddDefaultPred(
7157       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7158       .addReg(NewVReg3, RegState::Kill)
7159       .addReg(NewVReg4)
7160       .addImm(0)
7161       .addMemOperand(JTMMOLd));
7162
7163     if (RelocM == Reloc::PIC_) {
7164       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7165         .addReg(NewVReg5, RegState::Kill)
7166         .addReg(NewVReg4)
7167         .addJumpTableIndex(MJTI)
7168         .addImm(UId);
7169     } else {
7170       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7171         .addReg(NewVReg5, RegState::Kill)
7172         .addJumpTableIndex(MJTI)
7173         .addImm(UId);
7174     }
7175   }
7176
7177   // Add the jump table entries as successors to the MBB.
7178   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7179   for (std::vector<MachineBasicBlock*>::iterator
7180          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7181     MachineBasicBlock *CurMBB = *I;
7182     if (SeenMBBs.insert(CurMBB))
7183       DispContBB->addSuccessor(CurMBB);
7184   }
7185
7186   // N.B. the order the invoke BBs are processed in doesn't matter here.
7187   const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
7188   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7189   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
7190          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
7191     MachineBasicBlock *BB = *I;
7192
7193     // Remove the landing pad successor from the invoke block and replace it
7194     // with the new dispatch block.
7195     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7196                                                   BB->succ_end());
7197     while (!Successors.empty()) {
7198       MachineBasicBlock *SMBB = Successors.pop_back_val();
7199       if (SMBB->isLandingPad()) {
7200         BB->removeSuccessor(SMBB);
7201         MBBLPads.push_back(SMBB);
7202       }
7203     }
7204
7205     BB->addSuccessor(DispatchBB);
7206
7207     // Find the invoke call and mark all of the callee-saved registers as
7208     // 'implicit defined' so that they're spilled. This prevents code from
7209     // moving instructions to before the EH block, where they will never be
7210     // executed.
7211     for (MachineBasicBlock::reverse_iterator
7212            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7213       if (!II->isCall()) continue;
7214
7215       DenseMap<unsigned, bool> DefRegs;
7216       for (MachineInstr::mop_iterator
7217              OI = II->operands_begin(), OE = II->operands_end();
7218            OI != OE; ++OI) {
7219         if (!OI->isReg()) continue;
7220         DefRegs[OI->getReg()] = true;
7221       }
7222
7223       MachineInstrBuilder MIB(*MF, &*II);
7224
7225       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7226         unsigned Reg = SavedRegs[i];
7227         if (Subtarget->isThumb2() &&
7228             !ARM::tGPRRegClass.contains(Reg) &&
7229             !ARM::hGPRRegClass.contains(Reg))
7230           continue;
7231         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7232           continue;
7233         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7234           continue;
7235         if (!DefRegs[Reg])
7236           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7237       }
7238
7239       break;
7240     }
7241   }
7242
7243   // Mark all former landing pads as non-landing pads. The dispatch is the only
7244   // landing pad now.
7245   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7246          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7247     (*I)->setIsLandingPad(false);
7248
7249   // The instruction is gone now.
7250   MI->eraseFromParent();
7251
7252   return MBB;
7253 }
7254
7255 static
7256 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7257   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7258        E = MBB->succ_end(); I != E; ++I)
7259     if (*I != Succ)
7260       return *I;
7261   llvm_unreachable("Expecting a BB with two successors!");
7262 }
7263
7264 /// Return the load opcode for a given load size. If load size >= 8,
7265 /// neon opcode will be returned.
7266 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7267   if (LdSize >= 8)
7268     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7269                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7270   if (IsThumb1)
7271     return LdSize == 4 ? ARM::tLDRi
7272                        : LdSize == 2 ? ARM::tLDRHi
7273                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7274   if (IsThumb2)
7275     return LdSize == 4 ? ARM::t2LDR_POST
7276                        : LdSize == 2 ? ARM::t2LDRH_POST
7277                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7278   return LdSize == 4 ? ARM::LDR_POST_IMM
7279                      : LdSize == 2 ? ARM::LDRH_POST
7280                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7281 }
7282
7283 /// Return the store opcode for a given store size. If store size >= 8,
7284 /// neon opcode will be returned.
7285 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7286   if (StSize >= 8)
7287     return StSize == 16 ? ARM::VST1q32wb_fixed
7288                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7289   if (IsThumb1)
7290     return StSize == 4 ? ARM::tSTRi
7291                        : StSize == 2 ? ARM::tSTRHi
7292                                      : StSize == 1 ? ARM::tSTRBi : 0;
7293   if (IsThumb2)
7294     return StSize == 4 ? ARM::t2STR_POST
7295                        : StSize == 2 ? ARM::t2STRH_POST
7296                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7297   return StSize == 4 ? ARM::STR_POST_IMM
7298                      : StSize == 2 ? ARM::STRH_POST
7299                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7300 }
7301
7302 /// Emit a post-increment load operation with given size. The instructions
7303 /// will be added to BB at Pos.
7304 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7305                        const TargetInstrInfo *TII, DebugLoc dl,
7306                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7307                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7308   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7309   assert(LdOpc != 0 && "Should have a load opcode");
7310   if (LdSize >= 8) {
7311     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7312                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7313                        .addImm(0));
7314   } else if (IsThumb1) {
7315     // load + update AddrIn
7316     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7317                        .addReg(AddrIn).addImm(0));
7318     MachineInstrBuilder MIB =
7319         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7320     MIB = AddDefaultT1CC(MIB);
7321     MIB.addReg(AddrIn).addImm(LdSize);
7322     AddDefaultPred(MIB);
7323   } else if (IsThumb2) {
7324     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7325                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7326                        .addImm(LdSize));
7327   } else { // arm
7328     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7329                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7330                        .addReg(0).addImm(LdSize));
7331   }
7332 }
7333
7334 /// Emit a post-increment store operation with given size. The instructions
7335 /// will be added to BB at Pos.
7336 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7337                        const TargetInstrInfo *TII, DebugLoc dl,
7338                        unsigned StSize, unsigned Data, unsigned AddrIn,
7339                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7340   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7341   assert(StOpc != 0 && "Should have a store opcode");
7342   if (StSize >= 8) {
7343     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7344                        .addReg(AddrIn).addImm(0).addReg(Data));
7345   } else if (IsThumb1) {
7346     // store + update AddrIn
7347     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7348                        .addReg(AddrIn).addImm(0));
7349     MachineInstrBuilder MIB =
7350         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7351     MIB = AddDefaultT1CC(MIB);
7352     MIB.addReg(AddrIn).addImm(StSize);
7353     AddDefaultPred(MIB);
7354   } else if (IsThumb2) {
7355     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7356                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7357   } else { // arm
7358     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7359                        .addReg(Data).addReg(AddrIn).addReg(0)
7360                        .addImm(StSize));
7361   }
7362 }
7363
7364 MachineBasicBlock *
7365 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7366                                    MachineBasicBlock *BB) const {
7367   // This pseudo instruction has 3 operands: dst, src, size
7368   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7369   // Otherwise, we will generate unrolled scalar copies.
7370   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7371   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7372   MachineFunction::iterator It = BB;
7373   ++It;
7374
7375   unsigned dest = MI->getOperand(0).getReg();
7376   unsigned src = MI->getOperand(1).getReg();
7377   unsigned SizeVal = MI->getOperand(2).getImm();
7378   unsigned Align = MI->getOperand(3).getImm();
7379   DebugLoc dl = MI->getDebugLoc();
7380
7381   MachineFunction *MF = BB->getParent();
7382   MachineRegisterInfo &MRI = MF->getRegInfo();
7383   unsigned UnitSize = 0;
7384   const TargetRegisterClass *TRC = 0;
7385   const TargetRegisterClass *VecTRC = 0;
7386
7387   bool IsThumb1 = Subtarget->isThumb1Only();
7388   bool IsThumb2 = Subtarget->isThumb2();
7389
7390   if (Align & 1) {
7391     UnitSize = 1;
7392   } else if (Align & 2) {
7393     UnitSize = 2;
7394   } else {
7395     // Check whether we can use NEON instructions.
7396     if (!MF->getFunction()->getAttributes().
7397           hasAttribute(AttributeSet::FunctionIndex,
7398                        Attribute::NoImplicitFloat) &&
7399         Subtarget->hasNEON()) {
7400       if ((Align % 16 == 0) && SizeVal >= 16)
7401         UnitSize = 16;
7402       else if ((Align % 8 == 0) && SizeVal >= 8)
7403         UnitSize = 8;
7404     }
7405     // Can't use NEON instructions.
7406     if (UnitSize == 0)
7407       UnitSize = 4;
7408   }
7409
7410   // Select the correct opcode and register class for unit size load/store
7411   bool IsNeon = UnitSize >= 8;
7412   TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
7413                                : (const TargetRegisterClass *)&ARM::GPRRegClass;
7414   if (IsNeon)
7415     VecTRC = UnitSize == 16
7416                  ? (const TargetRegisterClass *)&ARM::DPairRegClass
7417                  : UnitSize == 8
7418                        ? (const TargetRegisterClass *)&ARM::DPRRegClass
7419                        : 0;
7420
7421   unsigned BytesLeft = SizeVal % UnitSize;
7422   unsigned LoopSize = SizeVal - BytesLeft;
7423
7424   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7425     // Use LDR and STR to copy.
7426     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7427     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7428     unsigned srcIn = src;
7429     unsigned destIn = dest;
7430     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7431       unsigned srcOut = MRI.createVirtualRegister(TRC);
7432       unsigned destOut = MRI.createVirtualRegister(TRC);
7433       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7434       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7435                  IsThumb1, IsThumb2);
7436       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7437                  IsThumb1, IsThumb2);
7438       srcIn = srcOut;
7439       destIn = destOut;
7440     }
7441
7442     // Handle the leftover bytes with LDRB and STRB.
7443     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7444     // [destOut] = STRB_POST(scratch, destIn, 1)
7445     for (unsigned i = 0; i < BytesLeft; i++) {
7446       unsigned srcOut = MRI.createVirtualRegister(TRC);
7447       unsigned destOut = MRI.createVirtualRegister(TRC);
7448       unsigned scratch = MRI.createVirtualRegister(TRC);
7449       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7450                  IsThumb1, IsThumb2);
7451       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7452                  IsThumb1, IsThumb2);
7453       srcIn = srcOut;
7454       destIn = destOut;
7455     }
7456     MI->eraseFromParent();   // The instruction is gone now.
7457     return BB;
7458   }
7459
7460   // Expand the pseudo op to a loop.
7461   // thisMBB:
7462   //   ...
7463   //   movw varEnd, # --> with thumb2
7464   //   movt varEnd, #
7465   //   ldrcp varEnd, idx --> without thumb2
7466   //   fallthrough --> loopMBB
7467   // loopMBB:
7468   //   PHI varPhi, varEnd, varLoop
7469   //   PHI srcPhi, src, srcLoop
7470   //   PHI destPhi, dst, destLoop
7471   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7472   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7473   //   subs varLoop, varPhi, #UnitSize
7474   //   bne loopMBB
7475   //   fallthrough --> exitMBB
7476   // exitMBB:
7477   //   epilogue to handle left-over bytes
7478   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7479   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7480   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7481   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7482   MF->insert(It, loopMBB);
7483   MF->insert(It, exitMBB);
7484
7485   // Transfer the remainder of BB and its successor edges to exitMBB.
7486   exitMBB->splice(exitMBB->begin(), BB,
7487                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7488   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7489
7490   // Load an immediate to varEnd.
7491   unsigned varEnd = MRI.createVirtualRegister(TRC);
7492   if (IsThumb2) {
7493     unsigned Vtmp = varEnd;
7494     if ((LoopSize & 0xFFFF0000) != 0)
7495       Vtmp = MRI.createVirtualRegister(TRC);
7496     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7497                        .addImm(LoopSize & 0xFFFF));
7498
7499     if ((LoopSize & 0xFFFF0000) != 0)
7500       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7501                          .addReg(Vtmp).addImm(LoopSize >> 16));
7502   } else {
7503     MachineConstantPool *ConstantPool = MF->getConstantPool();
7504     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7505     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7506
7507     // MachineConstantPool wants an explicit alignment.
7508     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7509     if (Align == 0)
7510       Align = getDataLayout()->getTypeAllocSize(C->getType());
7511     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7512
7513     if (IsThumb1)
7514       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7515           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7516     else
7517       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7518           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7519   }
7520   BB->addSuccessor(loopMBB);
7521
7522   // Generate the loop body:
7523   //   varPhi = PHI(varLoop, varEnd)
7524   //   srcPhi = PHI(srcLoop, src)
7525   //   destPhi = PHI(destLoop, dst)
7526   MachineBasicBlock *entryBB = BB;
7527   BB = loopMBB;
7528   unsigned varLoop = MRI.createVirtualRegister(TRC);
7529   unsigned varPhi = MRI.createVirtualRegister(TRC);
7530   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7531   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7532   unsigned destLoop = MRI.createVirtualRegister(TRC);
7533   unsigned destPhi = MRI.createVirtualRegister(TRC);
7534
7535   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7536     .addReg(varLoop).addMBB(loopMBB)
7537     .addReg(varEnd).addMBB(entryBB);
7538   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7539     .addReg(srcLoop).addMBB(loopMBB)
7540     .addReg(src).addMBB(entryBB);
7541   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7542     .addReg(destLoop).addMBB(loopMBB)
7543     .addReg(dest).addMBB(entryBB);
7544
7545   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7546   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7547   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7548   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7549              IsThumb1, IsThumb2);
7550   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7551              IsThumb1, IsThumb2);
7552
7553   // Decrement loop variable by UnitSize.
7554   if (IsThumb1) {
7555     MachineInstrBuilder MIB =
7556         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7557     MIB = AddDefaultT1CC(MIB);
7558     MIB.addReg(varPhi).addImm(UnitSize);
7559     AddDefaultPred(MIB);
7560   } else {
7561     MachineInstrBuilder MIB =
7562         BuildMI(*BB, BB->end(), dl,
7563                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7564     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7565     MIB->getOperand(5).setReg(ARM::CPSR);
7566     MIB->getOperand(5).setIsDef(true);
7567   }
7568   BuildMI(*BB, BB->end(), dl,
7569           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7570       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7571
7572   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7573   BB->addSuccessor(loopMBB);
7574   BB->addSuccessor(exitMBB);
7575
7576   // Add epilogue to handle BytesLeft.
7577   BB = exitMBB;
7578   MachineInstr *StartOfExit = exitMBB->begin();
7579
7580   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7581   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7582   unsigned srcIn = srcLoop;
7583   unsigned destIn = destLoop;
7584   for (unsigned i = 0; i < BytesLeft; i++) {
7585     unsigned srcOut = MRI.createVirtualRegister(TRC);
7586     unsigned destOut = MRI.createVirtualRegister(TRC);
7587     unsigned scratch = MRI.createVirtualRegister(TRC);
7588     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7589                IsThumb1, IsThumb2);
7590     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7591                IsThumb1, IsThumb2);
7592     srcIn = srcOut;
7593     destIn = destOut;
7594   }
7595
7596   MI->eraseFromParent();   // The instruction is gone now.
7597   return BB;
7598 }
7599
7600 MachineBasicBlock *
7601 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7602                                                MachineBasicBlock *BB) const {
7603   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7604   DebugLoc dl = MI->getDebugLoc();
7605   bool isThumb2 = Subtarget->isThumb2();
7606   switch (MI->getOpcode()) {
7607   default: {
7608     MI->dump();
7609     llvm_unreachable("Unexpected instr type to insert");
7610   }
7611   // The Thumb2 pre-indexed stores have the same MI operands, they just
7612   // define them differently in the .td files from the isel patterns, so
7613   // they need pseudos.
7614   case ARM::t2STR_preidx:
7615     MI->setDesc(TII->get(ARM::t2STR_PRE));
7616     return BB;
7617   case ARM::t2STRB_preidx:
7618     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7619     return BB;
7620   case ARM::t2STRH_preidx:
7621     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7622     return BB;
7623
7624   case ARM::STRi_preidx:
7625   case ARM::STRBi_preidx: {
7626     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7627       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7628     // Decode the offset.
7629     unsigned Offset = MI->getOperand(4).getImm();
7630     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7631     Offset = ARM_AM::getAM2Offset(Offset);
7632     if (isSub)
7633       Offset = -Offset;
7634
7635     MachineMemOperand *MMO = *MI->memoperands_begin();
7636     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7637       .addOperand(MI->getOperand(0))  // Rn_wb
7638       .addOperand(MI->getOperand(1))  // Rt
7639       .addOperand(MI->getOperand(2))  // Rn
7640       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7641       .addOperand(MI->getOperand(5))  // pred
7642       .addOperand(MI->getOperand(6))
7643       .addMemOperand(MMO);
7644     MI->eraseFromParent();
7645     return BB;
7646   }
7647   case ARM::STRr_preidx:
7648   case ARM::STRBr_preidx:
7649   case ARM::STRH_preidx: {
7650     unsigned NewOpc;
7651     switch (MI->getOpcode()) {
7652     default: llvm_unreachable("unexpected opcode!");
7653     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7654     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7655     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7656     }
7657     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7658     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7659       MIB.addOperand(MI->getOperand(i));
7660     MI->eraseFromParent();
7661     return BB;
7662   }
7663   case ARM::ATOMIC_LOAD_ADD_I8:
7664      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7665   case ARM::ATOMIC_LOAD_ADD_I16:
7666      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7667   case ARM::ATOMIC_LOAD_ADD_I32:
7668      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7669
7670   case ARM::ATOMIC_LOAD_AND_I8:
7671      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7672   case ARM::ATOMIC_LOAD_AND_I16:
7673      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7674   case ARM::ATOMIC_LOAD_AND_I32:
7675      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7676
7677   case ARM::ATOMIC_LOAD_OR_I8:
7678      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7679   case ARM::ATOMIC_LOAD_OR_I16:
7680      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7681   case ARM::ATOMIC_LOAD_OR_I32:
7682      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7683
7684   case ARM::ATOMIC_LOAD_XOR_I8:
7685      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7686   case ARM::ATOMIC_LOAD_XOR_I16:
7687      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7688   case ARM::ATOMIC_LOAD_XOR_I32:
7689      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7690
7691   case ARM::ATOMIC_LOAD_NAND_I8:
7692      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7693   case ARM::ATOMIC_LOAD_NAND_I16:
7694      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7695   case ARM::ATOMIC_LOAD_NAND_I32:
7696      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7697
7698   case ARM::ATOMIC_LOAD_SUB_I8:
7699      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7700   case ARM::ATOMIC_LOAD_SUB_I16:
7701      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7702   case ARM::ATOMIC_LOAD_SUB_I32:
7703      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7704
7705   case ARM::ATOMIC_LOAD_MIN_I8:
7706      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7707   case ARM::ATOMIC_LOAD_MIN_I16:
7708      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7709   case ARM::ATOMIC_LOAD_MIN_I32:
7710      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7711
7712   case ARM::ATOMIC_LOAD_MAX_I8:
7713      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7714   case ARM::ATOMIC_LOAD_MAX_I16:
7715      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7716   case ARM::ATOMIC_LOAD_MAX_I32:
7717      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7718
7719   case ARM::ATOMIC_LOAD_UMIN_I8:
7720      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7721   case ARM::ATOMIC_LOAD_UMIN_I16:
7722      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7723   case ARM::ATOMIC_LOAD_UMIN_I32:
7724      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7725
7726   case ARM::ATOMIC_LOAD_UMAX_I8:
7727      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7728   case ARM::ATOMIC_LOAD_UMAX_I16:
7729      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7730   case ARM::ATOMIC_LOAD_UMAX_I32:
7731      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7732
7733   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
7734   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7735   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7736
7737   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
7738   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7739   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7740
7741   case ARM::ATOMIC_LOAD_I64:
7742     return EmitAtomicLoad64(MI, BB);
7743
7744   case ARM::ATOMIC_LOAD_ADD_I64:
7745     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7746                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7747                               /*NeedsCarry*/ true);
7748   case ARM::ATOMIC_LOAD_SUB_I64:
7749     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7750                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7751                               /*NeedsCarry*/ true);
7752   case ARM::ATOMIC_LOAD_OR_I64:
7753     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7754                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7755   case ARM::ATOMIC_LOAD_XOR_I64:
7756     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7757                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7758   case ARM::ATOMIC_LOAD_AND_I64:
7759     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7760                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7761   case ARM::ATOMIC_SWAP_I64:
7762     return EmitAtomicBinary64(MI, BB, 0, 0, false);
7763   case ARM::ATOMIC_CMP_SWAP_I64:
7764     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7765                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7766                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7767   case ARM::ATOMIC_LOAD_MIN_I64:
7768     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7769                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7770                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7771                               /*IsMinMax*/ true, ARMCC::LT);
7772   case ARM::ATOMIC_LOAD_MAX_I64:
7773     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7774                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7775                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7776                               /*IsMinMax*/ true, ARMCC::GE);
7777   case ARM::ATOMIC_LOAD_UMIN_I64:
7778     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7779                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7780                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7781                               /*IsMinMax*/ true, ARMCC::LO);
7782   case ARM::ATOMIC_LOAD_UMAX_I64:
7783     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7784                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7785                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7786                               /*IsMinMax*/ true, ARMCC::HS);
7787
7788   case ARM::tMOVCCr_pseudo: {
7789     // To "insert" a SELECT_CC instruction, we actually have to insert the
7790     // diamond control-flow pattern.  The incoming instruction knows the
7791     // destination vreg to set, the condition code register to branch on, the
7792     // true/false values to select between, and a branch opcode to use.
7793     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7794     MachineFunction::iterator It = BB;
7795     ++It;
7796
7797     //  thisMBB:
7798     //  ...
7799     //   TrueVal = ...
7800     //   cmpTY ccX, r1, r2
7801     //   bCC copy1MBB
7802     //   fallthrough --> copy0MBB
7803     MachineBasicBlock *thisMBB  = BB;
7804     MachineFunction *F = BB->getParent();
7805     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7806     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7807     F->insert(It, copy0MBB);
7808     F->insert(It, sinkMBB);
7809
7810     // Transfer the remainder of BB and its successor edges to sinkMBB.
7811     sinkMBB->splice(sinkMBB->begin(), BB,
7812                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7813     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7814
7815     BB->addSuccessor(copy0MBB);
7816     BB->addSuccessor(sinkMBB);
7817
7818     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7819       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7820
7821     //  copy0MBB:
7822     //   %FalseValue = ...
7823     //   # fallthrough to sinkMBB
7824     BB = copy0MBB;
7825
7826     // Update machine-CFG edges
7827     BB->addSuccessor(sinkMBB);
7828
7829     //  sinkMBB:
7830     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7831     //  ...
7832     BB = sinkMBB;
7833     BuildMI(*BB, BB->begin(), dl,
7834             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7835       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7836       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7837
7838     MI->eraseFromParent();   // The pseudo instruction is gone now.
7839     return BB;
7840   }
7841
7842   case ARM::BCCi64:
7843   case ARM::BCCZi64: {
7844     // If there is an unconditional branch to the other successor, remove it.
7845     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7846
7847     // Compare both parts that make up the double comparison separately for
7848     // equality.
7849     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7850
7851     unsigned LHS1 = MI->getOperand(1).getReg();
7852     unsigned LHS2 = MI->getOperand(2).getReg();
7853     if (RHSisZero) {
7854       AddDefaultPred(BuildMI(BB, dl,
7855                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7856                      .addReg(LHS1).addImm(0));
7857       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7858         .addReg(LHS2).addImm(0)
7859         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7860     } else {
7861       unsigned RHS1 = MI->getOperand(3).getReg();
7862       unsigned RHS2 = MI->getOperand(4).getReg();
7863       AddDefaultPred(BuildMI(BB, dl,
7864                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7865                      .addReg(LHS1).addReg(RHS1));
7866       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7867         .addReg(LHS2).addReg(RHS2)
7868         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7869     }
7870
7871     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7872     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7873     if (MI->getOperand(0).getImm() == ARMCC::NE)
7874       std::swap(destMBB, exitMBB);
7875
7876     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7877       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7878     if (isThumb2)
7879       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7880     else
7881       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7882
7883     MI->eraseFromParent();   // The pseudo instruction is gone now.
7884     return BB;
7885   }
7886
7887   case ARM::Int_eh_sjlj_setjmp:
7888   case ARM::Int_eh_sjlj_setjmp_nofp:
7889   case ARM::tInt_eh_sjlj_setjmp:
7890   case ARM::t2Int_eh_sjlj_setjmp:
7891   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7892     EmitSjLjDispatchBlock(MI, BB);
7893     return BB;
7894
7895   case ARM::ABS:
7896   case ARM::t2ABS: {
7897     // To insert an ABS instruction, we have to insert the
7898     // diamond control-flow pattern.  The incoming instruction knows the
7899     // source vreg to test against 0, the destination vreg to set,
7900     // the condition code register to branch on, the
7901     // true/false values to select between, and a branch opcode to use.
7902     // It transforms
7903     //     V1 = ABS V0
7904     // into
7905     //     V2 = MOVS V0
7906     //     BCC                      (branch to SinkBB if V0 >= 0)
7907     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7908     //     SinkBB: V1 = PHI(V2, V3)
7909     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7910     MachineFunction::iterator BBI = BB;
7911     ++BBI;
7912     MachineFunction *Fn = BB->getParent();
7913     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7914     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7915     Fn->insert(BBI, RSBBB);
7916     Fn->insert(BBI, SinkBB);
7917
7918     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7919     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7920     bool isThumb2 = Subtarget->isThumb2();
7921     MachineRegisterInfo &MRI = Fn->getRegInfo();
7922     // In Thumb mode S must not be specified if source register is the SP or
7923     // PC and if destination register is the SP, so restrict register class
7924     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7925       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7926       (const TargetRegisterClass*)&ARM::GPRRegClass);
7927
7928     // Transfer the remainder of BB and its successor edges to sinkMBB.
7929     SinkBB->splice(SinkBB->begin(), BB,
7930                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7931     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7932
7933     BB->addSuccessor(RSBBB);
7934     BB->addSuccessor(SinkBB);
7935
7936     // fall through to SinkMBB
7937     RSBBB->addSuccessor(SinkBB);
7938
7939     // insert a cmp at the end of BB
7940     AddDefaultPred(BuildMI(BB, dl,
7941                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7942                    .addReg(ABSSrcReg).addImm(0));
7943
7944     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7945     BuildMI(BB, dl,
7946       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7947       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7948
7949     // insert rsbri in RSBBB
7950     // Note: BCC and rsbri will be converted into predicated rsbmi
7951     // by if-conversion pass
7952     BuildMI(*RSBBB, RSBBB->begin(), dl,
7953       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7954       .addReg(ABSSrcReg, RegState::Kill)
7955       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7956
7957     // insert PHI in SinkBB,
7958     // reuse ABSDstReg to not change uses of ABS instruction
7959     BuildMI(*SinkBB, SinkBB->begin(), dl,
7960       TII->get(ARM::PHI), ABSDstReg)
7961       .addReg(NewRsbDstReg).addMBB(RSBBB)
7962       .addReg(ABSSrcReg).addMBB(BB);
7963
7964     // remove ABS instruction
7965     MI->eraseFromParent();
7966
7967     // return last added BB
7968     return SinkBB;
7969   }
7970   case ARM::COPY_STRUCT_BYVAL_I32:
7971     ++NumLoopByVals;
7972     return EmitStructByval(MI, BB);
7973   }
7974 }
7975
7976 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7977                                                       SDNode *Node) const {
7978   if (!MI->hasPostISelHook()) {
7979     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7980            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7981     return;
7982   }
7983
7984   const MCInstrDesc *MCID = &MI->getDesc();
7985   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7986   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7987   // operand is still set to noreg. If needed, set the optional operand's
7988   // register to CPSR, and remove the redundant implicit def.
7989   //
7990   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7991
7992   // Rename pseudo opcodes.
7993   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7994   if (NewOpc) {
7995     const ARMBaseInstrInfo *TII =
7996       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7997     MCID = &TII->get(NewOpc);
7998
7999     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
8000            "converted opcode should be the same except for cc_out");
8001
8002     MI->setDesc(*MCID);
8003
8004     // Add the optional cc_out operand
8005     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
8006   }
8007   unsigned ccOutIdx = MCID->getNumOperands() - 1;
8008
8009   // Any ARM instruction that sets the 's' bit should specify an optional
8010   // "cc_out" operand in the last operand position.
8011   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
8012     assert(!NewOpc && "Optional cc_out operand required");
8013     return;
8014   }
8015   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8016   // since we already have an optional CPSR def.
8017   bool definesCPSR = false;
8018   bool deadCPSR = false;
8019   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
8020        i != e; ++i) {
8021     const MachineOperand &MO = MI->getOperand(i);
8022     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8023       definesCPSR = true;
8024       if (MO.isDead())
8025         deadCPSR = true;
8026       MI->RemoveOperand(i);
8027       break;
8028     }
8029   }
8030   if (!definesCPSR) {
8031     assert(!NewOpc && "Optional cc_out operand required");
8032     return;
8033   }
8034   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8035   if (deadCPSR) {
8036     assert(!MI->getOperand(ccOutIdx).getReg() &&
8037            "expect uninitialized optional cc_out operand");
8038     return;
8039   }
8040
8041   // If this instruction was defined with an optional CPSR def and its dag node
8042   // had a live implicit CPSR def, then activate the optional CPSR def.
8043   MachineOperand &MO = MI->getOperand(ccOutIdx);
8044   MO.setReg(ARM::CPSR);
8045   MO.setIsDef(true);
8046 }
8047
8048 //===----------------------------------------------------------------------===//
8049 //                           ARM Optimization Hooks
8050 //===----------------------------------------------------------------------===//
8051
8052 // Helper function that checks if N is a null or all ones constant.
8053 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8054   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8055   if (!C)
8056     return false;
8057   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8058 }
8059
8060 // Return true if N is conditionally 0 or all ones.
8061 // Detects these expressions where cc is an i1 value:
8062 //
8063 //   (select cc 0, y)   [AllOnes=0]
8064 //   (select cc y, 0)   [AllOnes=0]
8065 //   (zext cc)          [AllOnes=0]
8066 //   (sext cc)          [AllOnes=0/1]
8067 //   (select cc -1, y)  [AllOnes=1]
8068 //   (select cc y, -1)  [AllOnes=1]
8069 //
8070 // Invert is set when N is the null/all ones constant when CC is false.
8071 // OtherOp is set to the alternative value of N.
8072 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8073                                        SDValue &CC, bool &Invert,
8074                                        SDValue &OtherOp,
8075                                        SelectionDAG &DAG) {
8076   switch (N->getOpcode()) {
8077   default: return false;
8078   case ISD::SELECT: {
8079     CC = N->getOperand(0);
8080     SDValue N1 = N->getOperand(1);
8081     SDValue N2 = N->getOperand(2);
8082     if (isZeroOrAllOnes(N1, AllOnes)) {
8083       Invert = false;
8084       OtherOp = N2;
8085       return true;
8086     }
8087     if (isZeroOrAllOnes(N2, AllOnes)) {
8088       Invert = true;
8089       OtherOp = N1;
8090       return true;
8091     }
8092     return false;
8093   }
8094   case ISD::ZERO_EXTEND:
8095     // (zext cc) can never be the all ones value.
8096     if (AllOnes)
8097       return false;
8098     // Fall through.
8099   case ISD::SIGN_EXTEND: {
8100     EVT VT = N->getValueType(0);
8101     CC = N->getOperand(0);
8102     if (CC.getValueType() != MVT::i1)
8103       return false;
8104     Invert = !AllOnes;
8105     if (AllOnes)
8106       // When looking for an AllOnes constant, N is an sext, and the 'other'
8107       // value is 0.
8108       OtherOp = DAG.getConstant(0, VT);
8109     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8110       // When looking for a 0 constant, N can be zext or sext.
8111       OtherOp = DAG.getConstant(1, VT);
8112     else
8113       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
8114     return true;
8115   }
8116   }
8117 }
8118
8119 // Combine a constant select operand into its use:
8120 //
8121 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
8122 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
8123 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
8124 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
8125 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
8126 //
8127 // The transform is rejected if the select doesn't have a constant operand that
8128 // is null, or all ones when AllOnes is set.
8129 //
8130 // Also recognize sext/zext from i1:
8131 //
8132 //   (add (zext cc), x) -> (select cc (add x, 1), x)
8133 //   (add (sext cc), x) -> (select cc (add x, -1), x)
8134 //
8135 // These transformations eventually create predicated instructions.
8136 //
8137 // @param N       The node to transform.
8138 // @param Slct    The N operand that is a select.
8139 // @param OtherOp The other N operand (x above).
8140 // @param DCI     Context.
8141 // @param AllOnes Require the select constant to be all ones instead of null.
8142 // @returns The new node, or SDValue() on failure.
8143 static
8144 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8145                             TargetLowering::DAGCombinerInfo &DCI,
8146                             bool AllOnes = false) {
8147   SelectionDAG &DAG = DCI.DAG;
8148   EVT VT = N->getValueType(0);
8149   SDValue NonConstantVal;
8150   SDValue CCOp;
8151   bool SwapSelectOps;
8152   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8153                                   NonConstantVal, DAG))
8154     return SDValue();
8155
8156   // Slct is now know to be the desired identity constant when CC is true.
8157   SDValue TrueVal = OtherOp;
8158   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8159                                  OtherOp, NonConstantVal);
8160   // Unless SwapSelectOps says CC should be false.
8161   if (SwapSelectOps)
8162     std::swap(TrueVal, FalseVal);
8163
8164   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8165                      CCOp, TrueVal, FalseVal);
8166 }
8167
8168 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8169 static
8170 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8171                                        TargetLowering::DAGCombinerInfo &DCI) {
8172   SDValue N0 = N->getOperand(0);
8173   SDValue N1 = N->getOperand(1);
8174   if (N0.getNode()->hasOneUse()) {
8175     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8176     if (Result.getNode())
8177       return Result;
8178   }
8179   if (N1.getNode()->hasOneUse()) {
8180     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8181     if (Result.getNode())
8182       return Result;
8183   }
8184   return SDValue();
8185 }
8186
8187 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8188 // (only after legalization).
8189 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8190                                  TargetLowering::DAGCombinerInfo &DCI,
8191                                  const ARMSubtarget *Subtarget) {
8192
8193   // Only perform optimization if after legalize, and if NEON is available. We
8194   // also expected both operands to be BUILD_VECTORs.
8195   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8196       || N0.getOpcode() != ISD::BUILD_VECTOR
8197       || N1.getOpcode() != ISD::BUILD_VECTOR)
8198     return SDValue();
8199
8200   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8201   EVT VT = N->getValueType(0);
8202   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8203     return SDValue();
8204
8205   // Check that the vector operands are of the right form.
8206   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8207   // operands, where N is the size of the formed vector.
8208   // Each EXTRACT_VECTOR should have the same input vector and odd or even
8209   // index such that we have a pair wise add pattern.
8210
8211   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8212   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8213     return SDValue();
8214   SDValue Vec = N0->getOperand(0)->getOperand(0);
8215   SDNode *V = Vec.getNode();
8216   unsigned nextIndex = 0;
8217
8218   // For each operands to the ADD which are BUILD_VECTORs,
8219   // check to see if each of their operands are an EXTRACT_VECTOR with
8220   // the same vector and appropriate index.
8221   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8222     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8223         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8224
8225       SDValue ExtVec0 = N0->getOperand(i);
8226       SDValue ExtVec1 = N1->getOperand(i);
8227
8228       // First operand is the vector, verify its the same.
8229       if (V != ExtVec0->getOperand(0).getNode() ||
8230           V != ExtVec1->getOperand(0).getNode())
8231         return SDValue();
8232
8233       // Second is the constant, verify its correct.
8234       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8235       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8236
8237       // For the constant, we want to see all the even or all the odd.
8238       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8239           || C1->getZExtValue() != nextIndex+1)
8240         return SDValue();
8241
8242       // Increment index.
8243       nextIndex+=2;
8244     } else
8245       return SDValue();
8246   }
8247
8248   // Create VPADDL node.
8249   SelectionDAG &DAG = DCI.DAG;
8250   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8251
8252   // Build operand list.
8253   SmallVector<SDValue, 8> Ops;
8254   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
8255                                 TLI.getPointerTy()));
8256
8257   // Input is the vector.
8258   Ops.push_back(Vec);
8259
8260   // Get widened type and narrowed type.
8261   MVT widenType;
8262   unsigned numElem = VT.getVectorNumElements();
8263   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8264     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8265     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8266     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8267     default:
8268       llvm_unreachable("Invalid vector element type for padd optimization.");
8269   }
8270
8271   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
8272                             widenType, &Ops[0], Ops.size());
8273   return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, tmp);
8274 }
8275
8276 static SDValue findMUL_LOHI(SDValue V) {
8277   if (V->getOpcode() == ISD::UMUL_LOHI ||
8278       V->getOpcode() == ISD::SMUL_LOHI)
8279     return V;
8280   return SDValue();
8281 }
8282
8283 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8284                                      TargetLowering::DAGCombinerInfo &DCI,
8285                                      const ARMSubtarget *Subtarget) {
8286
8287   if (Subtarget->isThumb1Only()) return SDValue();
8288
8289   // Only perform the checks after legalize when the pattern is available.
8290   if (DCI.isBeforeLegalize()) return SDValue();
8291
8292   // Look for multiply add opportunities.
8293   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8294   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8295   // a glue link from the first add to the second add.
8296   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8297   // a S/UMLAL instruction.
8298   //          loAdd   UMUL_LOHI
8299   //            \    / :lo    \ :hi
8300   //             \  /          \          [no multiline comment]
8301   //              ADDC         |  hiAdd
8302   //                 \ :glue  /  /
8303   //                  \      /  /
8304   //                    ADDE
8305   //
8306   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8307   SDValue AddcOp0 = AddcNode->getOperand(0);
8308   SDValue AddcOp1 = AddcNode->getOperand(1);
8309
8310   // Check if the two operands are from the same mul_lohi node.
8311   if (AddcOp0.getNode() == AddcOp1.getNode())
8312     return SDValue();
8313
8314   assert(AddcNode->getNumValues() == 2 &&
8315          AddcNode->getValueType(0) == MVT::i32 &&
8316          "Expect ADDC with two result values. First: i32");
8317
8318   // Check that we have a glued ADDC node.
8319   if (AddcNode->getValueType(1) != MVT::Glue)
8320     return SDValue();
8321
8322   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8323   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8324       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8325       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8326       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8327     return SDValue();
8328
8329   // Look for the glued ADDE.
8330   SDNode* AddeNode = AddcNode->getGluedUser();
8331   if (AddeNode == NULL)
8332     return SDValue();
8333
8334   // Make sure it is really an ADDE.
8335   if (AddeNode->getOpcode() != ISD::ADDE)
8336     return SDValue();
8337
8338   assert(AddeNode->getNumOperands() == 3 &&
8339          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8340          "ADDE node has the wrong inputs");
8341
8342   // Check for the triangle shape.
8343   SDValue AddeOp0 = AddeNode->getOperand(0);
8344   SDValue AddeOp1 = AddeNode->getOperand(1);
8345
8346   // Make sure that the ADDE operands are not coming from the same node.
8347   if (AddeOp0.getNode() == AddeOp1.getNode())
8348     return SDValue();
8349
8350   // Find the MUL_LOHI node walking up ADDE's operands.
8351   bool IsLeftOperandMUL = false;
8352   SDValue MULOp = findMUL_LOHI(AddeOp0);
8353   if (MULOp == SDValue())
8354    MULOp = findMUL_LOHI(AddeOp1);
8355   else
8356     IsLeftOperandMUL = true;
8357   if (MULOp == SDValue())
8358      return SDValue();
8359
8360   // Figure out the right opcode.
8361   unsigned Opc = MULOp->getOpcode();
8362   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8363
8364   // Figure out the high and low input values to the MLAL node.
8365   SDValue* HiMul = &MULOp;
8366   SDValue* HiAdd = NULL;
8367   SDValue* LoMul = NULL;
8368   SDValue* LowAdd = NULL;
8369
8370   if (IsLeftOperandMUL)
8371     HiAdd = &AddeOp1;
8372   else
8373     HiAdd = &AddeOp0;
8374
8375
8376   if (AddcOp0->getOpcode() == Opc) {
8377     LoMul = &AddcOp0;
8378     LowAdd = &AddcOp1;
8379   }
8380   if (AddcOp1->getOpcode() == Opc) {
8381     LoMul = &AddcOp1;
8382     LowAdd = &AddcOp0;
8383   }
8384
8385   if (LoMul == NULL)
8386     return SDValue();
8387
8388   if (LoMul->getNode() != HiMul->getNode())
8389     return SDValue();
8390
8391   // Create the merged node.
8392   SelectionDAG &DAG = DCI.DAG;
8393
8394   // Build operand list.
8395   SmallVector<SDValue, 8> Ops;
8396   Ops.push_back(LoMul->getOperand(0));
8397   Ops.push_back(LoMul->getOperand(1));
8398   Ops.push_back(*LowAdd);
8399   Ops.push_back(*HiAdd);
8400
8401   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8402                                  DAG.getVTList(MVT::i32, MVT::i32),
8403                                  &Ops[0], Ops.size());
8404
8405   // Replace the ADDs' nodes uses by the MLA node's values.
8406   SDValue HiMLALResult(MLALNode.getNode(), 1);
8407   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8408
8409   SDValue LoMLALResult(MLALNode.getNode(), 0);
8410   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8411
8412   // Return original node to notify the driver to stop replacing.
8413   SDValue resNode(AddcNode, 0);
8414   return resNode;
8415 }
8416
8417 /// PerformADDCCombine - Target-specific dag combine transform from
8418 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8419 static SDValue PerformADDCCombine(SDNode *N,
8420                                  TargetLowering::DAGCombinerInfo &DCI,
8421                                  const ARMSubtarget *Subtarget) {
8422
8423   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8424
8425 }
8426
8427 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8428 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8429 /// called with the default operands, and if that fails, with commuted
8430 /// operands.
8431 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8432                                           TargetLowering::DAGCombinerInfo &DCI,
8433                                           const ARMSubtarget *Subtarget){
8434
8435   // Attempt to create vpaddl for this add.
8436   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8437   if (Result.getNode())
8438     return Result;
8439
8440   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8441   if (N0.getNode()->hasOneUse()) {
8442     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8443     if (Result.getNode()) return Result;
8444   }
8445   return SDValue();
8446 }
8447
8448 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8449 ///
8450 static SDValue PerformADDCombine(SDNode *N,
8451                                  TargetLowering::DAGCombinerInfo &DCI,
8452                                  const ARMSubtarget *Subtarget) {
8453   SDValue N0 = N->getOperand(0);
8454   SDValue N1 = N->getOperand(1);
8455
8456   // First try with the default operand order.
8457   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8458   if (Result.getNode())
8459     return Result;
8460
8461   // If that didn't work, try again with the operands commuted.
8462   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8463 }
8464
8465 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8466 ///
8467 static SDValue PerformSUBCombine(SDNode *N,
8468                                  TargetLowering::DAGCombinerInfo &DCI) {
8469   SDValue N0 = N->getOperand(0);
8470   SDValue N1 = N->getOperand(1);
8471
8472   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8473   if (N1.getNode()->hasOneUse()) {
8474     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8475     if (Result.getNode()) return Result;
8476   }
8477
8478   return SDValue();
8479 }
8480
8481 /// PerformVMULCombine
8482 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8483 /// special multiplier accumulator forwarding.
8484 ///   vmul d3, d0, d2
8485 ///   vmla d3, d1, d2
8486 /// is faster than
8487 ///   vadd d3, d0, d1
8488 ///   vmul d3, d3, d2
8489 //  However, for (A + B) * (A + B),
8490 //    vadd d2, d0, d1
8491 //    vmul d3, d0, d2
8492 //    vmla d3, d1, d2
8493 //  is slower than
8494 //    vadd d2, d0, d1
8495 //    vmul d3, d2, d2
8496 static SDValue PerformVMULCombine(SDNode *N,
8497                                   TargetLowering::DAGCombinerInfo &DCI,
8498                                   const ARMSubtarget *Subtarget) {
8499   if (!Subtarget->hasVMLxForwarding())
8500     return SDValue();
8501
8502   SelectionDAG &DAG = DCI.DAG;
8503   SDValue N0 = N->getOperand(0);
8504   SDValue N1 = N->getOperand(1);
8505   unsigned Opcode = N0.getOpcode();
8506   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8507       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8508     Opcode = N1.getOpcode();
8509     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8510         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8511       return SDValue();
8512     std::swap(N0, N1);
8513   }
8514
8515   if (N0 == N1)
8516     return SDValue();
8517
8518   EVT VT = N->getValueType(0);
8519   SDLoc DL(N);
8520   SDValue N00 = N0->getOperand(0);
8521   SDValue N01 = N0->getOperand(1);
8522   return DAG.getNode(Opcode, DL, VT,
8523                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8524                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8525 }
8526
8527 static SDValue PerformMULCombine(SDNode *N,
8528                                  TargetLowering::DAGCombinerInfo &DCI,
8529                                  const ARMSubtarget *Subtarget) {
8530   SelectionDAG &DAG = DCI.DAG;
8531
8532   if (Subtarget->isThumb1Only())
8533     return SDValue();
8534
8535   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8536     return SDValue();
8537
8538   EVT VT = N->getValueType(0);
8539   if (VT.is64BitVector() || VT.is128BitVector())
8540     return PerformVMULCombine(N, DCI, Subtarget);
8541   if (VT != MVT::i32)
8542     return SDValue();
8543
8544   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8545   if (!C)
8546     return SDValue();
8547
8548   int64_t MulAmt = C->getSExtValue();
8549   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8550
8551   ShiftAmt = ShiftAmt & (32 - 1);
8552   SDValue V = N->getOperand(0);
8553   SDLoc DL(N);
8554
8555   SDValue Res;
8556   MulAmt >>= ShiftAmt;
8557
8558   if (MulAmt >= 0) {
8559     if (isPowerOf2_32(MulAmt - 1)) {
8560       // (mul x, 2^N + 1) => (add (shl x, N), x)
8561       Res = DAG.getNode(ISD::ADD, DL, VT,
8562                         V,
8563                         DAG.getNode(ISD::SHL, DL, VT,
8564                                     V,
8565                                     DAG.getConstant(Log2_32(MulAmt - 1),
8566                                                     MVT::i32)));
8567     } else if (isPowerOf2_32(MulAmt + 1)) {
8568       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8569       Res = DAG.getNode(ISD::SUB, DL, VT,
8570                         DAG.getNode(ISD::SHL, DL, VT,
8571                                     V,
8572                                     DAG.getConstant(Log2_32(MulAmt + 1),
8573                                                     MVT::i32)),
8574                         V);
8575     } else
8576       return SDValue();
8577   } else {
8578     uint64_t MulAmtAbs = -MulAmt;
8579     if (isPowerOf2_32(MulAmtAbs + 1)) {
8580       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8581       Res = DAG.getNode(ISD::SUB, DL, VT,
8582                         V,
8583                         DAG.getNode(ISD::SHL, DL, VT,
8584                                     V,
8585                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8586                                                     MVT::i32)));
8587     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8588       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8589       Res = DAG.getNode(ISD::ADD, DL, VT,
8590                         V,
8591                         DAG.getNode(ISD::SHL, DL, VT,
8592                                     V,
8593                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8594                                                     MVT::i32)));
8595       Res = DAG.getNode(ISD::SUB, DL, VT,
8596                         DAG.getConstant(0, MVT::i32),Res);
8597
8598     } else
8599       return SDValue();
8600   }
8601
8602   if (ShiftAmt != 0)
8603     Res = DAG.getNode(ISD::SHL, DL, VT,
8604                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8605
8606   // Do not add new nodes to DAG combiner worklist.
8607   DCI.CombineTo(N, Res, false);
8608   return SDValue();
8609 }
8610
8611 static SDValue PerformANDCombine(SDNode *N,
8612                                  TargetLowering::DAGCombinerInfo &DCI,
8613                                  const ARMSubtarget *Subtarget) {
8614
8615   // Attempt to use immediate-form VBIC
8616   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8617   SDLoc dl(N);
8618   EVT VT = N->getValueType(0);
8619   SelectionDAG &DAG = DCI.DAG;
8620
8621   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8622     return SDValue();
8623
8624   APInt SplatBits, SplatUndef;
8625   unsigned SplatBitSize;
8626   bool HasAnyUndefs;
8627   if (BVN &&
8628       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8629     if (SplatBitSize <= 64) {
8630       EVT VbicVT;
8631       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8632                                       SplatUndef.getZExtValue(), SplatBitSize,
8633                                       DAG, VbicVT, VT.is128BitVector(),
8634                                       OtherModImm);
8635       if (Val.getNode()) {
8636         SDValue Input =
8637           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8638         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8639         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8640       }
8641     }
8642   }
8643
8644   if (!Subtarget->isThumb1Only()) {
8645     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8646     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8647     if (Result.getNode())
8648       return Result;
8649   }
8650
8651   return SDValue();
8652 }
8653
8654 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8655 static SDValue PerformORCombine(SDNode *N,
8656                                 TargetLowering::DAGCombinerInfo &DCI,
8657                                 const ARMSubtarget *Subtarget) {
8658   // Attempt to use immediate-form VORR
8659   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8660   SDLoc dl(N);
8661   EVT VT = N->getValueType(0);
8662   SelectionDAG &DAG = DCI.DAG;
8663
8664   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8665     return SDValue();
8666
8667   APInt SplatBits, SplatUndef;
8668   unsigned SplatBitSize;
8669   bool HasAnyUndefs;
8670   if (BVN && Subtarget->hasNEON() &&
8671       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8672     if (SplatBitSize <= 64) {
8673       EVT VorrVT;
8674       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8675                                       SplatUndef.getZExtValue(), SplatBitSize,
8676                                       DAG, VorrVT, VT.is128BitVector(),
8677                                       OtherModImm);
8678       if (Val.getNode()) {
8679         SDValue Input =
8680           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8681         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8682         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8683       }
8684     }
8685   }
8686
8687   if (!Subtarget->isThumb1Only()) {
8688     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8689     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8690     if (Result.getNode())
8691       return Result;
8692   }
8693
8694   // The code below optimizes (or (and X, Y), Z).
8695   // The AND operand needs to have a single user to make these optimizations
8696   // profitable.
8697   SDValue N0 = N->getOperand(0);
8698   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8699     return SDValue();
8700   SDValue N1 = N->getOperand(1);
8701
8702   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8703   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8704       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8705     APInt SplatUndef;
8706     unsigned SplatBitSize;
8707     bool HasAnyUndefs;
8708
8709     APInt SplatBits0, SplatBits1;
8710     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8711     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8712     // Ensure that the second operand of both ands are constants
8713     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8714                                       HasAnyUndefs) && !HasAnyUndefs) {
8715         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8716                                           HasAnyUndefs) && !HasAnyUndefs) {
8717             // Ensure that the bit width of the constants are the same and that
8718             // the splat arguments are logical inverses as per the pattern we
8719             // are trying to simplify.
8720             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8721                 SplatBits0 == ~SplatBits1) {
8722                 // Canonicalize the vector type to make instruction selection
8723                 // simpler.
8724                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8725                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8726                                              N0->getOperand(1),
8727                                              N0->getOperand(0),
8728                                              N1->getOperand(0));
8729                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8730             }
8731         }
8732     }
8733   }
8734
8735   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8736   // reasonable.
8737
8738   // BFI is only available on V6T2+
8739   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8740     return SDValue();
8741
8742   SDLoc DL(N);
8743   // 1) or (and A, mask), val => ARMbfi A, val, mask
8744   //      iff (val & mask) == val
8745   //
8746   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8747   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8748   //          && mask == ~mask2
8749   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8750   //          && ~mask == mask2
8751   //  (i.e., copy a bitfield value into another bitfield of the same width)
8752
8753   if (VT != MVT::i32)
8754     return SDValue();
8755
8756   SDValue N00 = N0.getOperand(0);
8757
8758   // The value and the mask need to be constants so we can verify this is
8759   // actually a bitfield set. If the mask is 0xffff, we can do better
8760   // via a movt instruction, so don't use BFI in that case.
8761   SDValue MaskOp = N0.getOperand(1);
8762   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8763   if (!MaskC)
8764     return SDValue();
8765   unsigned Mask = MaskC->getZExtValue();
8766   if (Mask == 0xffff)
8767     return SDValue();
8768   SDValue Res;
8769   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8770   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8771   if (N1C) {
8772     unsigned Val = N1C->getZExtValue();
8773     if ((Val & ~Mask) != Val)
8774       return SDValue();
8775
8776     if (ARM::isBitFieldInvertedMask(Mask)) {
8777       Val >>= countTrailingZeros(~Mask);
8778
8779       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8780                         DAG.getConstant(Val, MVT::i32),
8781                         DAG.getConstant(Mask, MVT::i32));
8782
8783       // Do not add new nodes to DAG combiner worklist.
8784       DCI.CombineTo(N, Res, false);
8785       return SDValue();
8786     }
8787   } else if (N1.getOpcode() == ISD::AND) {
8788     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8789     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8790     if (!N11C)
8791       return SDValue();
8792     unsigned Mask2 = N11C->getZExtValue();
8793
8794     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8795     // as is to match.
8796     if (ARM::isBitFieldInvertedMask(Mask) &&
8797         (Mask == ~Mask2)) {
8798       // The pack halfword instruction works better for masks that fit it,
8799       // so use that when it's available.
8800       if (Subtarget->hasT2ExtractPack() &&
8801           (Mask == 0xffff || Mask == 0xffff0000))
8802         return SDValue();
8803       // 2a
8804       unsigned amt = countTrailingZeros(Mask2);
8805       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8806                         DAG.getConstant(amt, MVT::i32));
8807       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8808                         DAG.getConstant(Mask, MVT::i32));
8809       // Do not add new nodes to DAG combiner worklist.
8810       DCI.CombineTo(N, Res, false);
8811       return SDValue();
8812     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8813                (~Mask == Mask2)) {
8814       // The pack halfword instruction works better for masks that fit it,
8815       // so use that when it's available.
8816       if (Subtarget->hasT2ExtractPack() &&
8817           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8818         return SDValue();
8819       // 2b
8820       unsigned lsb = countTrailingZeros(Mask);
8821       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8822                         DAG.getConstant(lsb, MVT::i32));
8823       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8824                         DAG.getConstant(Mask2, MVT::i32));
8825       // Do not add new nodes to DAG combiner worklist.
8826       DCI.CombineTo(N, Res, false);
8827       return SDValue();
8828     }
8829   }
8830
8831   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8832       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8833       ARM::isBitFieldInvertedMask(~Mask)) {
8834     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8835     // where lsb(mask) == #shamt and masked bits of B are known zero.
8836     SDValue ShAmt = N00.getOperand(1);
8837     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8838     unsigned LSB = countTrailingZeros(Mask);
8839     if (ShAmtC != LSB)
8840       return SDValue();
8841
8842     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8843                       DAG.getConstant(~Mask, MVT::i32));
8844
8845     // Do not add new nodes to DAG combiner worklist.
8846     DCI.CombineTo(N, Res, false);
8847   }
8848
8849   return SDValue();
8850 }
8851
8852 static SDValue PerformXORCombine(SDNode *N,
8853                                  TargetLowering::DAGCombinerInfo &DCI,
8854                                  const ARMSubtarget *Subtarget) {
8855   EVT VT = N->getValueType(0);
8856   SelectionDAG &DAG = DCI.DAG;
8857
8858   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8859     return SDValue();
8860
8861   if (!Subtarget->isThumb1Only()) {
8862     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8863     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8864     if (Result.getNode())
8865       return Result;
8866   }
8867
8868   return SDValue();
8869 }
8870
8871 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8872 /// the bits being cleared by the AND are not demanded by the BFI.
8873 static SDValue PerformBFICombine(SDNode *N,
8874                                  TargetLowering::DAGCombinerInfo &DCI) {
8875   SDValue N1 = N->getOperand(1);
8876   if (N1.getOpcode() == ISD::AND) {
8877     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8878     if (!N11C)
8879       return SDValue();
8880     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8881     unsigned LSB = countTrailingZeros(~InvMask);
8882     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8883     unsigned Mask = (1 << Width)-1;
8884     unsigned Mask2 = N11C->getZExtValue();
8885     if ((Mask & (~Mask2)) == 0)
8886       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8887                              N->getOperand(0), N1.getOperand(0),
8888                              N->getOperand(2));
8889   }
8890   return SDValue();
8891 }
8892
8893 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8894 /// ARMISD::VMOVRRD.
8895 static SDValue PerformVMOVRRDCombine(SDNode *N,
8896                                      TargetLowering::DAGCombinerInfo &DCI) {
8897   // vmovrrd(vmovdrr x, y) -> x,y
8898   SDValue InDouble = N->getOperand(0);
8899   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8900     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8901
8902   // vmovrrd(load f64) -> (load i32), (load i32)
8903   SDNode *InNode = InDouble.getNode();
8904   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8905       InNode->getValueType(0) == MVT::f64 &&
8906       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8907       !cast<LoadSDNode>(InNode)->isVolatile()) {
8908     // TODO: Should this be done for non-FrameIndex operands?
8909     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8910
8911     SelectionDAG &DAG = DCI.DAG;
8912     SDLoc DL(LD);
8913     SDValue BasePtr = LD->getBasePtr();
8914     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8915                                  LD->getPointerInfo(), LD->isVolatile(),
8916                                  LD->isNonTemporal(), LD->isInvariant(),
8917                                  LD->getAlignment());
8918
8919     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8920                                     DAG.getConstant(4, MVT::i32));
8921     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8922                                  LD->getPointerInfo(), LD->isVolatile(),
8923                                  LD->isNonTemporal(), LD->isInvariant(),
8924                                  std::min(4U, LD->getAlignment() / 2));
8925
8926     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8927     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8928     DCI.RemoveFromWorklist(LD);
8929     DAG.DeleteNode(LD);
8930     return Result;
8931   }
8932
8933   return SDValue();
8934 }
8935
8936 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8937 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8938 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8939   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8940   SDValue Op0 = N->getOperand(0);
8941   SDValue Op1 = N->getOperand(1);
8942   if (Op0.getOpcode() == ISD::BITCAST)
8943     Op0 = Op0.getOperand(0);
8944   if (Op1.getOpcode() == ISD::BITCAST)
8945     Op1 = Op1.getOperand(0);
8946   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8947       Op0.getNode() == Op1.getNode() &&
8948       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8949     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8950                        N->getValueType(0), Op0.getOperand(0));
8951   return SDValue();
8952 }
8953
8954 /// PerformSTORECombine - Target-specific dag combine xforms for
8955 /// ISD::STORE.
8956 static SDValue PerformSTORECombine(SDNode *N,
8957                                    TargetLowering::DAGCombinerInfo &DCI) {
8958   StoreSDNode *St = cast<StoreSDNode>(N);
8959   if (St->isVolatile())
8960     return SDValue();
8961
8962   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8963   // pack all of the elements in one place.  Next, store to memory in fewer
8964   // chunks.
8965   SDValue StVal = St->getValue();
8966   EVT VT = StVal.getValueType();
8967   if (St->isTruncatingStore() && VT.isVector()) {
8968     SelectionDAG &DAG = DCI.DAG;
8969     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8970     EVT StVT = St->getMemoryVT();
8971     unsigned NumElems = VT.getVectorNumElements();
8972     assert(StVT != VT && "Cannot truncate to the same type");
8973     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8974     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8975
8976     // From, To sizes and ElemCount must be pow of two
8977     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8978
8979     // We are going to use the original vector elt for storing.
8980     // Accumulated smaller vector elements must be a multiple of the store size.
8981     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8982
8983     unsigned SizeRatio  = FromEltSz / ToEltSz;
8984     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8985
8986     // Create a type on which we perform the shuffle.
8987     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8988                                      NumElems*SizeRatio);
8989     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8990
8991     SDLoc DL(St);
8992     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8993     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8994     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8995
8996     // Can't shuffle using an illegal type.
8997     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8998
8999     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9000                                 DAG.getUNDEF(WideVec.getValueType()),
9001                                 ShuffleVec.data());
9002     // At this point all of the data is stored at the bottom of the
9003     // register. We now need to save it to mem.
9004
9005     // Find the largest store unit
9006     MVT StoreType = MVT::i8;
9007     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
9008          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
9009       MVT Tp = (MVT::SimpleValueType)tp;
9010       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9011         StoreType = Tp;
9012     }
9013     // Didn't find a legal store type.
9014     if (!TLI.isTypeLegal(StoreType))
9015       return SDValue();
9016
9017     // Bitcast the original vector into a vector of store-size units
9018     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9019             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9020     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9021     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9022     SmallVector<SDValue, 8> Chains;
9023     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
9024                                         TLI.getPointerTy());
9025     SDValue BasePtr = St->getBasePtr();
9026
9027     // Perform one or more big stores into memory.
9028     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9029     for (unsigned I = 0; I < E; I++) {
9030       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9031                                    StoreType, ShuffWide,
9032                                    DAG.getIntPtrConstant(I));
9033       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9034                                 St->getPointerInfo(), St->isVolatile(),
9035                                 St->isNonTemporal(), St->getAlignment());
9036       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9037                             Increment);
9038       Chains.push_back(Ch);
9039     }
9040     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
9041                        Chains.size());
9042   }
9043
9044   if (!ISD::isNormalStore(St))
9045     return SDValue();
9046
9047   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9048   // ARM stores of arguments in the same cache line.
9049   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9050       StVal.getNode()->hasOneUse()) {
9051     SelectionDAG  &DAG = DCI.DAG;
9052     SDLoc DL(St);
9053     SDValue BasePtr = St->getBasePtr();
9054     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9055                                   StVal.getNode()->getOperand(0), BasePtr,
9056                                   St->getPointerInfo(), St->isVolatile(),
9057                                   St->isNonTemporal(), St->getAlignment());
9058
9059     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9060                                     DAG.getConstant(4, MVT::i32));
9061     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
9062                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9063                         St->isNonTemporal(),
9064                         std::min(4U, St->getAlignment() / 2));
9065   }
9066
9067   if (StVal.getValueType() != MVT::i64 ||
9068       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9069     return SDValue();
9070
9071   // Bitcast an i64 store extracted from a vector to f64.
9072   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9073   SelectionDAG &DAG = DCI.DAG;
9074   SDLoc dl(StVal);
9075   SDValue IntVec = StVal.getOperand(0);
9076   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9077                                  IntVec.getValueType().getVectorNumElements());
9078   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9079   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9080                                Vec, StVal.getOperand(1));
9081   dl = SDLoc(N);
9082   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9083   // Make the DAGCombiner fold the bitcasts.
9084   DCI.AddToWorklist(Vec.getNode());
9085   DCI.AddToWorklist(ExtElt.getNode());
9086   DCI.AddToWorklist(V.getNode());
9087   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9088                       St->getPointerInfo(), St->isVolatile(),
9089                       St->isNonTemporal(), St->getAlignment(),
9090                       St->getTBAAInfo());
9091 }
9092
9093 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9094 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
9095 /// i64 vector to have f64 elements, since the value can then be loaded
9096 /// directly into a VFP register.
9097 static bool hasNormalLoadOperand(SDNode *N) {
9098   unsigned NumElts = N->getValueType(0).getVectorNumElements();
9099   for (unsigned i = 0; i < NumElts; ++i) {
9100     SDNode *Elt = N->getOperand(i).getNode();
9101     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9102       return true;
9103   }
9104   return false;
9105 }
9106
9107 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9108 /// ISD::BUILD_VECTOR.
9109 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9110                                           TargetLowering::DAGCombinerInfo &DCI){
9111   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9112   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
9113   // into a pair of GPRs, which is fine when the value is used as a scalar,
9114   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9115   SelectionDAG &DAG = DCI.DAG;
9116   if (N->getNumOperands() == 2) {
9117     SDValue RV = PerformVMOVDRRCombine(N, DAG);
9118     if (RV.getNode())
9119       return RV;
9120   }
9121
9122   // Load i64 elements as f64 values so that type legalization does not split
9123   // them up into i32 values.
9124   EVT VT = N->getValueType(0);
9125   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9126     return SDValue();
9127   SDLoc dl(N);
9128   SmallVector<SDValue, 8> Ops;
9129   unsigned NumElts = VT.getVectorNumElements();
9130   for (unsigned i = 0; i < NumElts; ++i) {
9131     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9132     Ops.push_back(V);
9133     // Make the DAGCombiner fold the bitcast.
9134     DCI.AddToWorklist(V.getNode());
9135   }
9136   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9137   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
9138   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9139 }
9140
9141 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9142 static SDValue
9143 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9144   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9145   // At that time, we may have inserted bitcasts from integer to float.
9146   // If these bitcasts have survived DAGCombine, change the lowering of this
9147   // BUILD_VECTOR in something more vector friendly, i.e., that does not
9148   // force to use floating point types.
9149
9150   // Make sure we can change the type of the vector.
9151   // This is possible iff:
9152   // 1. The vector is only used in a bitcast to a integer type. I.e.,
9153   //    1.1. Vector is used only once.
9154   //    1.2. Use is a bit convert to an integer type.
9155   // 2. The size of its operands are 32-bits (64-bits are not legal).
9156   EVT VT = N->getValueType(0);
9157   EVT EltVT = VT.getVectorElementType();
9158
9159   // Check 1.1. and 2.
9160   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9161     return SDValue();
9162
9163   // By construction, the input type must be float.
9164   assert(EltVT == MVT::f32 && "Unexpected type!");
9165
9166   // Check 1.2.
9167   SDNode *Use = *N->use_begin();
9168   if (Use->getOpcode() != ISD::BITCAST ||
9169       Use->getValueType(0).isFloatingPoint())
9170     return SDValue();
9171
9172   // Check profitability.
9173   // Model is, if more than half of the relevant operands are bitcast from
9174   // i32, turn the build_vector into a sequence of insert_vector_elt.
9175   // Relevant operands are everything that is not statically
9176   // (i.e., at compile time) bitcasted.
9177   unsigned NumOfBitCastedElts = 0;
9178   unsigned NumElts = VT.getVectorNumElements();
9179   unsigned NumOfRelevantElts = NumElts;
9180   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9181     SDValue Elt = N->getOperand(Idx);
9182     if (Elt->getOpcode() == ISD::BITCAST) {
9183       // Assume only bit cast to i32 will go away.
9184       if (Elt->getOperand(0).getValueType() == MVT::i32)
9185         ++NumOfBitCastedElts;
9186     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9187       // Constants are statically casted, thus do not count them as
9188       // relevant operands.
9189       --NumOfRelevantElts;
9190   }
9191
9192   // Check if more than half of the elements require a non-free bitcast.
9193   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9194     return SDValue();
9195
9196   SelectionDAG &DAG = DCI.DAG;
9197   // Create the new vector type.
9198   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9199   // Check if the type is legal.
9200   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9201   if (!TLI.isTypeLegal(VecVT))
9202     return SDValue();
9203
9204   // Combine:
9205   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9206   // => BITCAST INSERT_VECTOR_ELT
9207   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9208   //                      (BITCAST EN), N.
9209   SDValue Vec = DAG.getUNDEF(VecVT);
9210   SDLoc dl(N);
9211   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9212     SDValue V = N->getOperand(Idx);
9213     if (V.getOpcode() == ISD::UNDEF)
9214       continue;
9215     if (V.getOpcode() == ISD::BITCAST &&
9216         V->getOperand(0).getValueType() == MVT::i32)
9217       // Fold obvious case.
9218       V = V.getOperand(0);
9219     else {
9220       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 
9221       // Make the DAGCombiner fold the bitcasts.
9222       DCI.AddToWorklist(V.getNode());
9223     }
9224     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
9225     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9226   }
9227   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9228   // Make the DAGCombiner fold the bitcasts.
9229   DCI.AddToWorklist(Vec.getNode());
9230   return Vec;
9231 }
9232
9233 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9234 /// ISD::INSERT_VECTOR_ELT.
9235 static SDValue PerformInsertEltCombine(SDNode *N,
9236                                        TargetLowering::DAGCombinerInfo &DCI) {
9237   // Bitcast an i64 load inserted into a vector to f64.
9238   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9239   EVT VT = N->getValueType(0);
9240   SDNode *Elt = N->getOperand(1).getNode();
9241   if (VT.getVectorElementType() != MVT::i64 ||
9242       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9243     return SDValue();
9244
9245   SelectionDAG &DAG = DCI.DAG;
9246   SDLoc dl(N);
9247   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9248                                  VT.getVectorNumElements());
9249   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9250   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9251   // Make the DAGCombiner fold the bitcasts.
9252   DCI.AddToWorklist(Vec.getNode());
9253   DCI.AddToWorklist(V.getNode());
9254   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9255                                Vec, V, N->getOperand(2));
9256   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9257 }
9258
9259 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9260 /// ISD::VECTOR_SHUFFLE.
9261 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9262   // The LLVM shufflevector instruction does not require the shuffle mask
9263   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9264   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
9265   // operands do not match the mask length, they are extended by concatenating
9266   // them with undef vectors.  That is probably the right thing for other
9267   // targets, but for NEON it is better to concatenate two double-register
9268   // size vector operands into a single quad-register size vector.  Do that
9269   // transformation here:
9270   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
9271   //   shuffle(concat(v1, v2), undef)
9272   SDValue Op0 = N->getOperand(0);
9273   SDValue Op1 = N->getOperand(1);
9274   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9275       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9276       Op0.getNumOperands() != 2 ||
9277       Op1.getNumOperands() != 2)
9278     return SDValue();
9279   SDValue Concat0Op1 = Op0.getOperand(1);
9280   SDValue Concat1Op1 = Op1.getOperand(1);
9281   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9282       Concat1Op1.getOpcode() != ISD::UNDEF)
9283     return SDValue();
9284   // Skip the transformation if any of the types are illegal.
9285   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9286   EVT VT = N->getValueType(0);
9287   if (!TLI.isTypeLegal(VT) ||
9288       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9289       !TLI.isTypeLegal(Concat1Op1.getValueType()))
9290     return SDValue();
9291
9292   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9293                                   Op0.getOperand(0), Op1.getOperand(0));
9294   // Translate the shuffle mask.
9295   SmallVector<int, 16> NewMask;
9296   unsigned NumElts = VT.getVectorNumElements();
9297   unsigned HalfElts = NumElts/2;
9298   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9299   for (unsigned n = 0; n < NumElts; ++n) {
9300     int MaskElt = SVN->getMaskElt(n);
9301     int NewElt = -1;
9302     if (MaskElt < (int)HalfElts)
9303       NewElt = MaskElt;
9304     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9305       NewElt = HalfElts + MaskElt - NumElts;
9306     NewMask.push_back(NewElt);
9307   }
9308   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9309                               DAG.getUNDEF(VT), NewMask.data());
9310 }
9311
9312 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
9313 /// NEON load/store intrinsics to merge base address updates.
9314 static SDValue CombineBaseUpdate(SDNode *N,
9315                                  TargetLowering::DAGCombinerInfo &DCI) {
9316   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9317     return SDValue();
9318
9319   SelectionDAG &DAG = DCI.DAG;
9320   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9321                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9322   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
9323   SDValue Addr = N->getOperand(AddrOpIdx);
9324
9325   // Search for a use of the address operand that is an increment.
9326   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9327          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9328     SDNode *User = *UI;
9329     if (User->getOpcode() != ISD::ADD ||
9330         UI.getUse().getResNo() != Addr.getResNo())
9331       continue;
9332
9333     // Check that the add is independent of the load/store.  Otherwise, folding
9334     // it would create a cycle.
9335     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9336       continue;
9337
9338     // Find the new opcode for the updating load/store.
9339     bool isLoad = true;
9340     bool isLaneOp = false;
9341     unsigned NewOpc = 0;
9342     unsigned NumVecs = 0;
9343     if (isIntrinsic) {
9344       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9345       switch (IntNo) {
9346       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9347       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9348         NumVecs = 1; break;
9349       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9350         NumVecs = 2; break;
9351       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9352         NumVecs = 3; break;
9353       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9354         NumVecs = 4; break;
9355       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9356         NumVecs = 2; isLaneOp = true; break;
9357       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9358         NumVecs = 3; isLaneOp = true; break;
9359       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9360         NumVecs = 4; isLaneOp = true; break;
9361       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9362         NumVecs = 1; isLoad = false; break;
9363       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9364         NumVecs = 2; isLoad = false; break;
9365       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9366         NumVecs = 3; isLoad = false; break;
9367       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9368         NumVecs = 4; isLoad = false; break;
9369       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9370         NumVecs = 2; isLoad = false; isLaneOp = true; break;
9371       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9372         NumVecs = 3; isLoad = false; isLaneOp = true; break;
9373       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9374         NumVecs = 4; isLoad = false; isLaneOp = true; break;
9375       }
9376     } else {
9377       isLaneOp = true;
9378       switch (N->getOpcode()) {
9379       default: llvm_unreachable("unexpected opcode for Neon base update");
9380       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9381       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9382       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9383       }
9384     }
9385
9386     // Find the size of memory referenced by the load/store.
9387     EVT VecTy;
9388     if (isLoad)
9389       VecTy = N->getValueType(0);
9390     else
9391       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9392     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9393     if (isLaneOp)
9394       NumBytes /= VecTy.getVectorNumElements();
9395
9396     // If the increment is a constant, it must match the memory ref size.
9397     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9398     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9399       uint64_t IncVal = CInc->getZExtValue();
9400       if (IncVal != NumBytes)
9401         continue;
9402     } else if (NumBytes >= 3 * 16) {
9403       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9404       // separate instructions that make it harder to use a non-constant update.
9405       continue;
9406     }
9407
9408     // Create the new updating load/store node.
9409     EVT Tys[6];
9410     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
9411     unsigned n;
9412     for (n = 0; n < NumResultVecs; ++n)
9413       Tys[n] = VecTy;
9414     Tys[n++] = MVT::i32;
9415     Tys[n] = MVT::Other;
9416     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
9417     SmallVector<SDValue, 8> Ops;
9418     Ops.push_back(N->getOperand(0)); // incoming chain
9419     Ops.push_back(N->getOperand(AddrOpIdx));
9420     Ops.push_back(Inc);
9421     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
9422       Ops.push_back(N->getOperand(i));
9423     }
9424     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9425     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9426                                            Ops.data(), Ops.size(),
9427                                            MemInt->getMemoryVT(),
9428                                            MemInt->getMemOperand());
9429
9430     // Update the uses.
9431     std::vector<SDValue> NewResults;
9432     for (unsigned i = 0; i < NumResultVecs; ++i) {
9433       NewResults.push_back(SDValue(UpdN.getNode(), i));
9434     }
9435     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9436     DCI.CombineTo(N, NewResults);
9437     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9438
9439     break;
9440   }
9441   return SDValue();
9442 }
9443
9444 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9445 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9446 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9447 /// return true.
9448 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9449   SelectionDAG &DAG = DCI.DAG;
9450   EVT VT = N->getValueType(0);
9451   // vldN-dup instructions only support 64-bit vectors for N > 1.
9452   if (!VT.is64BitVector())
9453     return false;
9454
9455   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9456   SDNode *VLD = N->getOperand(0).getNode();
9457   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9458     return false;
9459   unsigned NumVecs = 0;
9460   unsigned NewOpc = 0;
9461   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9462   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9463     NumVecs = 2;
9464     NewOpc = ARMISD::VLD2DUP;
9465   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9466     NumVecs = 3;
9467     NewOpc = ARMISD::VLD3DUP;
9468   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9469     NumVecs = 4;
9470     NewOpc = ARMISD::VLD4DUP;
9471   } else {
9472     return false;
9473   }
9474
9475   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9476   // numbers match the load.
9477   unsigned VLDLaneNo =
9478     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9479   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9480        UI != UE; ++UI) {
9481     // Ignore uses of the chain result.
9482     if (UI.getUse().getResNo() == NumVecs)
9483       continue;
9484     SDNode *User = *UI;
9485     if (User->getOpcode() != ARMISD::VDUPLANE ||
9486         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9487       return false;
9488   }
9489
9490   // Create the vldN-dup node.
9491   EVT Tys[5];
9492   unsigned n;
9493   for (n = 0; n < NumVecs; ++n)
9494     Tys[n] = VT;
9495   Tys[n] = MVT::Other;
9496   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
9497   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9498   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9499   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9500                                            Ops, 2, VLDMemInt->getMemoryVT(),
9501                                            VLDMemInt->getMemOperand());
9502
9503   // Update the uses.
9504   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9505        UI != UE; ++UI) {
9506     unsigned ResNo = UI.getUse().getResNo();
9507     // Ignore uses of the chain result.
9508     if (ResNo == NumVecs)
9509       continue;
9510     SDNode *User = *UI;
9511     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9512   }
9513
9514   // Now the vldN-lane intrinsic is dead except for its chain result.
9515   // Update uses of the chain.
9516   std::vector<SDValue> VLDDupResults;
9517   for (unsigned n = 0; n < NumVecs; ++n)
9518     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9519   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9520   DCI.CombineTo(VLD, VLDDupResults);
9521
9522   return true;
9523 }
9524
9525 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9526 /// ARMISD::VDUPLANE.
9527 static SDValue PerformVDUPLANECombine(SDNode *N,
9528                                       TargetLowering::DAGCombinerInfo &DCI) {
9529   SDValue Op = N->getOperand(0);
9530
9531   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9532   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9533   if (CombineVLDDUP(N, DCI))
9534     return SDValue(N, 0);
9535
9536   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9537   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9538   while (Op.getOpcode() == ISD::BITCAST)
9539     Op = Op.getOperand(0);
9540   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9541     return SDValue();
9542
9543   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9544   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9545   // The canonical VMOV for a zero vector uses a 32-bit element size.
9546   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9547   unsigned EltBits;
9548   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9549     EltSize = 8;
9550   EVT VT = N->getValueType(0);
9551   if (EltSize > VT.getVectorElementType().getSizeInBits())
9552     return SDValue();
9553
9554   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9555 }
9556
9557 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9558 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9559 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9560 {
9561   integerPart cN;
9562   integerPart c0 = 0;
9563   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9564        I != E; I++) {
9565     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9566     if (!C)
9567       return false;
9568
9569     bool isExact;
9570     APFloat APF = C->getValueAPF();
9571     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9572         != APFloat::opOK || !isExact)
9573       return false;
9574
9575     c0 = (I == 0) ? cN : c0;
9576     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9577       return false;
9578   }
9579   C = c0;
9580   return true;
9581 }
9582
9583 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9584 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9585 /// when the VMUL has a constant operand that is a power of 2.
9586 ///
9587 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9588 ///  vmul.f32        d16, d17, d16
9589 ///  vcvt.s32.f32    d16, d16
9590 /// becomes:
9591 ///  vcvt.s32.f32    d16, d16, #3
9592 static SDValue PerformVCVTCombine(SDNode *N,
9593                                   TargetLowering::DAGCombinerInfo &DCI,
9594                                   const ARMSubtarget *Subtarget) {
9595   SelectionDAG &DAG = DCI.DAG;
9596   SDValue Op = N->getOperand(0);
9597
9598   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9599       Op.getOpcode() != ISD::FMUL)
9600     return SDValue();
9601
9602   uint64_t C;
9603   SDValue N0 = Op->getOperand(0);
9604   SDValue ConstVec = Op->getOperand(1);
9605   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9606
9607   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9608       !isConstVecPow2(ConstVec, isSigned, C))
9609     return SDValue();
9610
9611   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9612   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9613   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9614     // These instructions only exist converting from f32 to i32. We can handle
9615     // smaller integers by generating an extra truncate, but larger ones would
9616     // be lossy.
9617     return SDValue();
9618   }
9619
9620   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9621     Intrinsic::arm_neon_vcvtfp2fxu;
9622   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9623   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9624                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9625                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9626                                  DAG.getConstant(Log2_64(C), MVT::i32));
9627
9628   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9629     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9630
9631   return FixConv;
9632 }
9633
9634 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9635 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9636 /// when the VDIV has a constant operand that is a power of 2.
9637 ///
9638 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9639 ///  vcvt.f32.s32    d16, d16
9640 ///  vdiv.f32        d16, d17, d16
9641 /// becomes:
9642 ///  vcvt.f32.s32    d16, d16, #3
9643 static SDValue PerformVDIVCombine(SDNode *N,
9644                                   TargetLowering::DAGCombinerInfo &DCI,
9645                                   const ARMSubtarget *Subtarget) {
9646   SelectionDAG &DAG = DCI.DAG;
9647   SDValue Op = N->getOperand(0);
9648   unsigned OpOpcode = Op.getNode()->getOpcode();
9649
9650   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9651       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9652     return SDValue();
9653
9654   uint64_t C;
9655   SDValue ConstVec = N->getOperand(1);
9656   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9657
9658   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9659       !isConstVecPow2(ConstVec, isSigned, C))
9660     return SDValue();
9661
9662   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9663   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9664   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9665     // These instructions only exist converting from i32 to f32. We can handle
9666     // smaller integers by generating an extra extend, but larger ones would
9667     // be lossy.
9668     return SDValue();
9669   }
9670
9671   SDValue ConvInput = Op.getOperand(0);
9672   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9673   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9674     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9675                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9676                             ConvInput);
9677
9678   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9679     Intrinsic::arm_neon_vcvtfxu2fp;
9680   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9681                      Op.getValueType(),
9682                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9683                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9684 }
9685
9686 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9687 /// operand of a vector shift operation, where all the elements of the
9688 /// build_vector must have the same constant integer value.
9689 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9690   // Ignore bit_converts.
9691   while (Op.getOpcode() == ISD::BITCAST)
9692     Op = Op.getOperand(0);
9693   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9694   APInt SplatBits, SplatUndef;
9695   unsigned SplatBitSize;
9696   bool HasAnyUndefs;
9697   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9698                                       HasAnyUndefs, ElementBits) ||
9699       SplatBitSize > ElementBits)
9700     return false;
9701   Cnt = SplatBits.getSExtValue();
9702   return true;
9703 }
9704
9705 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9706 /// operand of a vector shift left operation.  That value must be in the range:
9707 ///   0 <= Value < ElementBits for a left shift; or
9708 ///   0 <= Value <= ElementBits for a long left shift.
9709 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9710   assert(VT.isVector() && "vector shift count is not a vector type");
9711   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9712   if (! getVShiftImm(Op, ElementBits, Cnt))
9713     return false;
9714   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9715 }
9716
9717 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9718 /// operand of a vector shift right operation.  For a shift opcode, the value
9719 /// is positive, but for an intrinsic the value count must be negative. The
9720 /// absolute value must be in the range:
9721 ///   1 <= |Value| <= ElementBits for a right shift; or
9722 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9723 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9724                          int64_t &Cnt) {
9725   assert(VT.isVector() && "vector shift count is not a vector type");
9726   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9727   if (! getVShiftImm(Op, ElementBits, Cnt))
9728     return false;
9729   if (isIntrinsic)
9730     Cnt = -Cnt;
9731   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9732 }
9733
9734 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9735 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9736   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9737   switch (IntNo) {
9738   default:
9739     // Don't do anything for most intrinsics.
9740     break;
9741
9742   // Vector shifts: check for immediate versions and lower them.
9743   // Note: This is done during DAG combining instead of DAG legalizing because
9744   // the build_vectors for 64-bit vector element shift counts are generally
9745   // not legal, and it is hard to see their values after they get legalized to
9746   // loads from a constant pool.
9747   case Intrinsic::arm_neon_vshifts:
9748   case Intrinsic::arm_neon_vshiftu:
9749   case Intrinsic::arm_neon_vrshifts:
9750   case Intrinsic::arm_neon_vrshiftu:
9751   case Intrinsic::arm_neon_vrshiftn:
9752   case Intrinsic::arm_neon_vqshifts:
9753   case Intrinsic::arm_neon_vqshiftu:
9754   case Intrinsic::arm_neon_vqshiftsu:
9755   case Intrinsic::arm_neon_vqshiftns:
9756   case Intrinsic::arm_neon_vqshiftnu:
9757   case Intrinsic::arm_neon_vqshiftnsu:
9758   case Intrinsic::arm_neon_vqrshiftns:
9759   case Intrinsic::arm_neon_vqrshiftnu:
9760   case Intrinsic::arm_neon_vqrshiftnsu: {
9761     EVT VT = N->getOperand(1).getValueType();
9762     int64_t Cnt;
9763     unsigned VShiftOpc = 0;
9764
9765     switch (IntNo) {
9766     case Intrinsic::arm_neon_vshifts:
9767     case Intrinsic::arm_neon_vshiftu:
9768       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9769         VShiftOpc = ARMISD::VSHL;
9770         break;
9771       }
9772       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9773         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9774                      ARMISD::VSHRs : ARMISD::VSHRu);
9775         break;
9776       }
9777       return SDValue();
9778
9779     case Intrinsic::arm_neon_vrshifts:
9780     case Intrinsic::arm_neon_vrshiftu:
9781       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9782         break;
9783       return SDValue();
9784
9785     case Intrinsic::arm_neon_vqshifts:
9786     case Intrinsic::arm_neon_vqshiftu:
9787       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9788         break;
9789       return SDValue();
9790
9791     case Intrinsic::arm_neon_vqshiftsu:
9792       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9793         break;
9794       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9795
9796     case Intrinsic::arm_neon_vrshiftn:
9797     case Intrinsic::arm_neon_vqshiftns:
9798     case Intrinsic::arm_neon_vqshiftnu:
9799     case Intrinsic::arm_neon_vqshiftnsu:
9800     case Intrinsic::arm_neon_vqrshiftns:
9801     case Intrinsic::arm_neon_vqrshiftnu:
9802     case Intrinsic::arm_neon_vqrshiftnsu:
9803       // Narrowing shifts require an immediate right shift.
9804       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9805         break;
9806       llvm_unreachable("invalid shift count for narrowing vector shift "
9807                        "intrinsic");
9808
9809     default:
9810       llvm_unreachable("unhandled vector shift");
9811     }
9812
9813     switch (IntNo) {
9814     case Intrinsic::arm_neon_vshifts:
9815     case Intrinsic::arm_neon_vshiftu:
9816       // Opcode already set above.
9817       break;
9818     case Intrinsic::arm_neon_vrshifts:
9819       VShiftOpc = ARMISD::VRSHRs; break;
9820     case Intrinsic::arm_neon_vrshiftu:
9821       VShiftOpc = ARMISD::VRSHRu; break;
9822     case Intrinsic::arm_neon_vrshiftn:
9823       VShiftOpc = ARMISD::VRSHRN; break;
9824     case Intrinsic::arm_neon_vqshifts:
9825       VShiftOpc = ARMISD::VQSHLs; break;
9826     case Intrinsic::arm_neon_vqshiftu:
9827       VShiftOpc = ARMISD::VQSHLu; break;
9828     case Intrinsic::arm_neon_vqshiftsu:
9829       VShiftOpc = ARMISD::VQSHLsu; break;
9830     case Intrinsic::arm_neon_vqshiftns:
9831       VShiftOpc = ARMISD::VQSHRNs; break;
9832     case Intrinsic::arm_neon_vqshiftnu:
9833       VShiftOpc = ARMISD::VQSHRNu; break;
9834     case Intrinsic::arm_neon_vqshiftnsu:
9835       VShiftOpc = ARMISD::VQSHRNsu; break;
9836     case Intrinsic::arm_neon_vqrshiftns:
9837       VShiftOpc = ARMISD::VQRSHRNs; break;
9838     case Intrinsic::arm_neon_vqrshiftnu:
9839       VShiftOpc = ARMISD::VQRSHRNu; break;
9840     case Intrinsic::arm_neon_vqrshiftnsu:
9841       VShiftOpc = ARMISD::VQRSHRNsu; break;
9842     }
9843
9844     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9845                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9846   }
9847
9848   case Intrinsic::arm_neon_vshiftins: {
9849     EVT VT = N->getOperand(1).getValueType();
9850     int64_t Cnt;
9851     unsigned VShiftOpc = 0;
9852
9853     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9854       VShiftOpc = ARMISD::VSLI;
9855     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9856       VShiftOpc = ARMISD::VSRI;
9857     else {
9858       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9859     }
9860
9861     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9862                        N->getOperand(1), N->getOperand(2),
9863                        DAG.getConstant(Cnt, MVT::i32));
9864   }
9865
9866   case Intrinsic::arm_neon_vqrshifts:
9867   case Intrinsic::arm_neon_vqrshiftu:
9868     // No immediate versions of these to check for.
9869     break;
9870   }
9871
9872   return SDValue();
9873 }
9874
9875 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9876 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9877 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9878 /// vector element shift counts are generally not legal, and it is hard to see
9879 /// their values after they get legalized to loads from a constant pool.
9880 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9881                                    const ARMSubtarget *ST) {
9882   EVT VT = N->getValueType(0);
9883   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9884     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9885     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9886     SDValue N1 = N->getOperand(1);
9887     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9888       SDValue N0 = N->getOperand(0);
9889       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9890           DAG.MaskedValueIsZero(N0.getOperand(0),
9891                                 APInt::getHighBitsSet(32, 16)))
9892         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9893     }
9894   }
9895
9896   // Nothing to be done for scalar shifts.
9897   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9898   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9899     return SDValue();
9900
9901   assert(ST->hasNEON() && "unexpected vector shift");
9902   int64_t Cnt;
9903
9904   switch (N->getOpcode()) {
9905   default: llvm_unreachable("unexpected shift opcode");
9906
9907   case ISD::SHL:
9908     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9909       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9910                          DAG.getConstant(Cnt, MVT::i32));
9911     break;
9912
9913   case ISD::SRA:
9914   case ISD::SRL:
9915     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9916       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9917                             ARMISD::VSHRs : ARMISD::VSHRu);
9918       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9919                          DAG.getConstant(Cnt, MVT::i32));
9920     }
9921   }
9922   return SDValue();
9923 }
9924
9925 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9926 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9927 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9928                                     const ARMSubtarget *ST) {
9929   SDValue N0 = N->getOperand(0);
9930
9931   // Check for sign- and zero-extensions of vector extract operations of 8-
9932   // and 16-bit vector elements.  NEON supports these directly.  They are
9933   // handled during DAG combining because type legalization will promote them
9934   // to 32-bit types and it is messy to recognize the operations after that.
9935   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9936     SDValue Vec = N0.getOperand(0);
9937     SDValue Lane = N0.getOperand(1);
9938     EVT VT = N->getValueType(0);
9939     EVT EltVT = N0.getValueType();
9940     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9941
9942     if (VT == MVT::i32 &&
9943         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9944         TLI.isTypeLegal(Vec.getValueType()) &&
9945         isa<ConstantSDNode>(Lane)) {
9946
9947       unsigned Opc = 0;
9948       switch (N->getOpcode()) {
9949       default: llvm_unreachable("unexpected opcode");
9950       case ISD::SIGN_EXTEND:
9951         Opc = ARMISD::VGETLANEs;
9952         break;
9953       case ISD::ZERO_EXTEND:
9954       case ISD::ANY_EXTEND:
9955         Opc = ARMISD::VGETLANEu;
9956         break;
9957       }
9958       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9959     }
9960   }
9961
9962   return SDValue();
9963 }
9964
9965 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9966 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9967 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9968                                        const ARMSubtarget *ST) {
9969   // If the target supports NEON, try to use vmax/vmin instructions for f32
9970   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9971   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9972   // a NaN; only do the transformation when it matches that behavior.
9973
9974   // For now only do this when using NEON for FP operations; if using VFP, it
9975   // is not obvious that the benefit outweighs the cost of switching to the
9976   // NEON pipeline.
9977   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9978       N->getValueType(0) != MVT::f32)
9979     return SDValue();
9980
9981   SDValue CondLHS = N->getOperand(0);
9982   SDValue CondRHS = N->getOperand(1);
9983   SDValue LHS = N->getOperand(2);
9984   SDValue RHS = N->getOperand(3);
9985   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9986
9987   unsigned Opcode = 0;
9988   bool IsReversed;
9989   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9990     IsReversed = false; // x CC y ? x : y
9991   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9992     IsReversed = true ; // x CC y ? y : x
9993   } else {
9994     return SDValue();
9995   }
9996
9997   bool IsUnordered;
9998   switch (CC) {
9999   default: break;
10000   case ISD::SETOLT:
10001   case ISD::SETOLE:
10002   case ISD::SETLT:
10003   case ISD::SETLE:
10004   case ISD::SETULT:
10005   case ISD::SETULE:
10006     // If LHS is NaN, an ordered comparison will be false and the result will
10007     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
10008     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
10009     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
10010     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10011       break;
10012     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
10013     // will return -0, so vmin can only be used for unsafe math or if one of
10014     // the operands is known to be nonzero.
10015     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
10016         !DAG.getTarget().Options.UnsafeFPMath &&
10017         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10018       break;
10019     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
10020     break;
10021
10022   case ISD::SETOGT:
10023   case ISD::SETOGE:
10024   case ISD::SETGT:
10025   case ISD::SETGE:
10026   case ISD::SETUGT:
10027   case ISD::SETUGE:
10028     // If LHS is NaN, an ordered comparison will be false and the result will
10029     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
10030     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
10031     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
10032     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10033       break;
10034     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
10035     // will return +0, so vmax can only be used for unsafe math or if one of
10036     // the operands is known to be nonzero.
10037     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
10038         !DAG.getTarget().Options.UnsafeFPMath &&
10039         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10040       break;
10041     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
10042     break;
10043   }
10044
10045   if (!Opcode)
10046     return SDValue();
10047   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
10048 }
10049
10050 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10051 SDValue
10052 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10053   SDValue Cmp = N->getOperand(4);
10054   if (Cmp.getOpcode() != ARMISD::CMPZ)
10055     // Only looking at EQ and NE cases.
10056     return SDValue();
10057
10058   EVT VT = N->getValueType(0);
10059   SDLoc dl(N);
10060   SDValue LHS = Cmp.getOperand(0);
10061   SDValue RHS = Cmp.getOperand(1);
10062   SDValue FalseVal = N->getOperand(0);
10063   SDValue TrueVal = N->getOperand(1);
10064   SDValue ARMcc = N->getOperand(2);
10065   ARMCC::CondCodes CC =
10066     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10067
10068   // Simplify
10069   //   mov     r1, r0
10070   //   cmp     r1, x
10071   //   mov     r0, y
10072   //   moveq   r0, x
10073   // to
10074   //   cmp     r0, x
10075   //   movne   r0, y
10076   //
10077   //   mov     r1, r0
10078   //   cmp     r1, x
10079   //   mov     r0, x
10080   //   movne   r0, y
10081   // to
10082   //   cmp     r0, x
10083   //   movne   r0, y
10084   /// FIXME: Turn this into a target neutral optimization?
10085   SDValue Res;
10086   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10087     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10088                       N->getOperand(3), Cmp);
10089   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10090     SDValue ARMcc;
10091     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10092     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10093                       N->getOperand(3), NewCmp);
10094   }
10095
10096   if (Res.getNode()) {
10097     APInt KnownZero, KnownOne;
10098     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
10099     // Capture demanded bits information that would be otherwise lost.
10100     if (KnownZero == 0xfffffffe)
10101       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10102                         DAG.getValueType(MVT::i1));
10103     else if (KnownZero == 0xffffff00)
10104       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10105                         DAG.getValueType(MVT::i8));
10106     else if (KnownZero == 0xffff0000)
10107       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10108                         DAG.getValueType(MVT::i16));
10109   }
10110
10111   return Res;
10112 }
10113
10114 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10115                                              DAGCombinerInfo &DCI) const {
10116   switch (N->getOpcode()) {
10117   default: break;
10118   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
10119   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
10120   case ISD::SUB:        return PerformSUBCombine(N, DCI);
10121   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
10122   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
10123   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
10124   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
10125   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
10126   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
10127   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10128   case ISD::STORE:      return PerformSTORECombine(N, DCI);
10129   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
10130   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10131   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10132   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10133   case ISD::FP_TO_SINT:
10134   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10135   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
10136   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10137   case ISD::SHL:
10138   case ISD::SRA:
10139   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10140   case ISD::SIGN_EXTEND:
10141   case ISD::ZERO_EXTEND:
10142   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10143   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
10144   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10145   case ARMISD::VLD2DUP:
10146   case ARMISD::VLD3DUP:
10147   case ARMISD::VLD4DUP:
10148     return CombineBaseUpdate(N, DCI);
10149   case ARMISD::BUILD_VECTOR:
10150     return PerformARMBUILD_VECTORCombine(N, DCI);
10151   case ISD::INTRINSIC_VOID:
10152   case ISD::INTRINSIC_W_CHAIN:
10153     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10154     case Intrinsic::arm_neon_vld1:
10155     case Intrinsic::arm_neon_vld2:
10156     case Intrinsic::arm_neon_vld3:
10157     case Intrinsic::arm_neon_vld4:
10158     case Intrinsic::arm_neon_vld2lane:
10159     case Intrinsic::arm_neon_vld3lane:
10160     case Intrinsic::arm_neon_vld4lane:
10161     case Intrinsic::arm_neon_vst1:
10162     case Intrinsic::arm_neon_vst2:
10163     case Intrinsic::arm_neon_vst3:
10164     case Intrinsic::arm_neon_vst4:
10165     case Intrinsic::arm_neon_vst2lane:
10166     case Intrinsic::arm_neon_vst3lane:
10167     case Intrinsic::arm_neon_vst4lane:
10168       return CombineBaseUpdate(N, DCI);
10169     default: break;
10170     }
10171     break;
10172   }
10173   return SDValue();
10174 }
10175
10176 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10177                                                           EVT VT) const {
10178   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10179 }
10180
10181 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, unsigned,
10182                                                       bool *Fast) const {
10183   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10184   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10185
10186   switch (VT.getSimpleVT().SimpleTy) {
10187   default:
10188     return false;
10189   case MVT::i8:
10190   case MVT::i16:
10191   case MVT::i32: {
10192     // Unaligned access can use (for example) LRDB, LRDH, LDR
10193     if (AllowsUnaligned) {
10194       if (Fast)
10195         *Fast = Subtarget->hasV7Ops();
10196       return true;
10197     }
10198     return false;
10199   }
10200   case MVT::f64:
10201   case MVT::v2f64: {
10202     // For any little-endian targets with neon, we can support unaligned ld/st
10203     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10204     // A big-endian target may also explicitly support unaligned accesses
10205     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
10206       if (Fast)
10207         *Fast = true;
10208       return true;
10209     }
10210     return false;
10211   }
10212   }
10213 }
10214
10215 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10216                        unsigned AlignCheck) {
10217   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10218           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10219 }
10220
10221 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10222                                            unsigned DstAlign, unsigned SrcAlign,
10223                                            bool IsMemset, bool ZeroMemset,
10224                                            bool MemcpyStrSrc,
10225                                            MachineFunction &MF) const {
10226   const Function *F = MF.getFunction();
10227
10228   // See if we can use NEON instructions for this...
10229   if ((!IsMemset || ZeroMemset) &&
10230       Subtarget->hasNEON() &&
10231       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
10232                                        Attribute::NoImplicitFloat)) {
10233     bool Fast;
10234     if (Size >= 16 &&
10235         (memOpAlign(SrcAlign, DstAlign, 16) ||
10236          (allowsUnalignedMemoryAccesses(MVT::v2f64, 0, &Fast) && Fast))) {
10237       return MVT::v2f64;
10238     } else if (Size >= 8 &&
10239                (memOpAlign(SrcAlign, DstAlign, 8) ||
10240                 (allowsUnalignedMemoryAccesses(MVT::f64, 0, &Fast) && Fast))) {
10241       return MVT::f64;
10242     }
10243   }
10244
10245   // Lowering to i32/i16 if the size permits.
10246   if (Size >= 4)
10247     return MVT::i32;
10248   else if (Size >= 2)
10249     return MVT::i16;
10250
10251   // Let the target-independent logic figure it out.
10252   return MVT::Other;
10253 }
10254
10255 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10256   if (Val.getOpcode() != ISD::LOAD)
10257     return false;
10258
10259   EVT VT1 = Val.getValueType();
10260   if (!VT1.isSimple() || !VT1.isInteger() ||
10261       !VT2.isSimple() || !VT2.isInteger())
10262     return false;
10263
10264   switch (VT1.getSimpleVT().SimpleTy) {
10265   default: break;
10266   case MVT::i1:
10267   case MVT::i8:
10268   case MVT::i16:
10269     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10270     return true;
10271   }
10272
10273   return false;
10274 }
10275
10276 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10277   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10278     return false;
10279
10280   if (!isTypeLegal(EVT::getEVT(Ty1)))
10281     return false;
10282
10283   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10284
10285   // Assuming the caller doesn't have a zeroext or signext return parameter,
10286   // truncation all the way down to i1 is valid.
10287   return true;
10288 }
10289
10290
10291 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10292   if (V < 0)
10293     return false;
10294
10295   unsigned Scale = 1;
10296   switch (VT.getSimpleVT().SimpleTy) {
10297   default: return false;
10298   case MVT::i1:
10299   case MVT::i8:
10300     // Scale == 1;
10301     break;
10302   case MVT::i16:
10303     // Scale == 2;
10304     Scale = 2;
10305     break;
10306   case MVT::i32:
10307     // Scale == 4;
10308     Scale = 4;
10309     break;
10310   }
10311
10312   if ((V & (Scale - 1)) != 0)
10313     return false;
10314   V /= Scale;
10315   return V == (V & ((1LL << 5) - 1));
10316 }
10317
10318 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10319                                       const ARMSubtarget *Subtarget) {
10320   bool isNeg = false;
10321   if (V < 0) {
10322     isNeg = true;
10323     V = - V;
10324   }
10325
10326   switch (VT.getSimpleVT().SimpleTy) {
10327   default: return false;
10328   case MVT::i1:
10329   case MVT::i8:
10330   case MVT::i16:
10331   case MVT::i32:
10332     // + imm12 or - imm8
10333     if (isNeg)
10334       return V == (V & ((1LL << 8) - 1));
10335     return V == (V & ((1LL << 12) - 1));
10336   case MVT::f32:
10337   case MVT::f64:
10338     // Same as ARM mode. FIXME: NEON?
10339     if (!Subtarget->hasVFP2())
10340       return false;
10341     if ((V & 3) != 0)
10342       return false;
10343     V >>= 2;
10344     return V == (V & ((1LL << 8) - 1));
10345   }
10346 }
10347
10348 /// isLegalAddressImmediate - Return true if the integer value can be used
10349 /// as the offset of the target addressing mode for load / store of the
10350 /// given type.
10351 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10352                                     const ARMSubtarget *Subtarget) {
10353   if (V == 0)
10354     return true;
10355
10356   if (!VT.isSimple())
10357     return false;
10358
10359   if (Subtarget->isThumb1Only())
10360     return isLegalT1AddressImmediate(V, VT);
10361   else if (Subtarget->isThumb2())
10362     return isLegalT2AddressImmediate(V, VT, Subtarget);
10363
10364   // ARM mode.
10365   if (V < 0)
10366     V = - V;
10367   switch (VT.getSimpleVT().SimpleTy) {
10368   default: return false;
10369   case MVT::i1:
10370   case MVT::i8:
10371   case MVT::i32:
10372     // +- imm12
10373     return V == (V & ((1LL << 12) - 1));
10374   case MVT::i16:
10375     // +- imm8
10376     return V == (V & ((1LL << 8) - 1));
10377   case MVT::f32:
10378   case MVT::f64:
10379     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10380       return false;
10381     if ((V & 3) != 0)
10382       return false;
10383     V >>= 2;
10384     return V == (V & ((1LL << 8) - 1));
10385   }
10386 }
10387
10388 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10389                                                       EVT VT) const {
10390   int Scale = AM.Scale;
10391   if (Scale < 0)
10392     return false;
10393
10394   switch (VT.getSimpleVT().SimpleTy) {
10395   default: return false;
10396   case MVT::i1:
10397   case MVT::i8:
10398   case MVT::i16:
10399   case MVT::i32:
10400     if (Scale == 1)
10401       return true;
10402     // r + r << imm
10403     Scale = Scale & ~1;
10404     return Scale == 2 || Scale == 4 || Scale == 8;
10405   case MVT::i64:
10406     // r + r
10407     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10408       return true;
10409     return false;
10410   case MVT::isVoid:
10411     // Note, we allow "void" uses (basically, uses that aren't loads or
10412     // stores), because arm allows folding a scale into many arithmetic
10413     // operations.  This should be made more precise and revisited later.
10414
10415     // Allow r << imm, but the imm has to be a multiple of two.
10416     if (Scale & 1) return false;
10417     return isPowerOf2_32(Scale);
10418   }
10419 }
10420
10421 /// isLegalAddressingMode - Return true if the addressing mode represented
10422 /// by AM is legal for this target, for a load/store of the specified type.
10423 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10424                                               Type *Ty) const {
10425   EVT VT = getValueType(Ty, true);
10426   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10427     return false;
10428
10429   // Can never fold addr of global into load/store.
10430   if (AM.BaseGV)
10431     return false;
10432
10433   switch (AM.Scale) {
10434   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10435     break;
10436   case 1:
10437     if (Subtarget->isThumb1Only())
10438       return false;
10439     // FALL THROUGH.
10440   default:
10441     // ARM doesn't support any R+R*scale+imm addr modes.
10442     if (AM.BaseOffs)
10443       return false;
10444
10445     if (!VT.isSimple())
10446       return false;
10447
10448     if (Subtarget->isThumb2())
10449       return isLegalT2ScaledAddressingMode(AM, VT);
10450
10451     int Scale = AM.Scale;
10452     switch (VT.getSimpleVT().SimpleTy) {
10453     default: return false;
10454     case MVT::i1:
10455     case MVT::i8:
10456     case MVT::i32:
10457       if (Scale < 0) Scale = -Scale;
10458       if (Scale == 1)
10459         return true;
10460       // r + r << imm
10461       return isPowerOf2_32(Scale & ~1);
10462     case MVT::i16:
10463     case MVT::i64:
10464       // r + r
10465       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10466         return true;
10467       return false;
10468
10469     case MVT::isVoid:
10470       // Note, we allow "void" uses (basically, uses that aren't loads or
10471       // stores), because arm allows folding a scale into many arithmetic
10472       // operations.  This should be made more precise and revisited later.
10473
10474       // Allow r << imm, but the imm has to be a multiple of two.
10475       if (Scale & 1) return false;
10476       return isPowerOf2_32(Scale);
10477     }
10478   }
10479   return true;
10480 }
10481
10482 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10483 /// icmp immediate, that is the target has icmp instructions which can compare
10484 /// a register against the immediate without having to materialize the
10485 /// immediate into a register.
10486 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10487   // Thumb2 and ARM modes can use cmn for negative immediates.
10488   if (!Subtarget->isThumb())
10489     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10490   if (Subtarget->isThumb2())
10491     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10492   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10493   return Imm >= 0 && Imm <= 255;
10494 }
10495
10496 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10497 /// *or sub* immediate, that is the target has add or sub instructions which can
10498 /// add a register with the immediate without having to materialize the
10499 /// immediate into a register.
10500 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10501   // Same encoding for add/sub, just flip the sign.
10502   int64_t AbsImm = llvm::abs64(Imm);
10503   if (!Subtarget->isThumb())
10504     return ARM_AM::getSOImmVal(AbsImm) != -1;
10505   if (Subtarget->isThumb2())
10506     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10507   // Thumb1 only has 8-bit unsigned immediate.
10508   return AbsImm >= 0 && AbsImm <= 255;
10509 }
10510
10511 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10512                                       bool isSEXTLoad, SDValue &Base,
10513                                       SDValue &Offset, bool &isInc,
10514                                       SelectionDAG &DAG) {
10515   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10516     return false;
10517
10518   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10519     // AddressingMode 3
10520     Base = Ptr->getOperand(0);
10521     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10522       int RHSC = (int)RHS->getZExtValue();
10523       if (RHSC < 0 && RHSC > -256) {
10524         assert(Ptr->getOpcode() == ISD::ADD);
10525         isInc = false;
10526         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10527         return true;
10528       }
10529     }
10530     isInc = (Ptr->getOpcode() == ISD::ADD);
10531     Offset = Ptr->getOperand(1);
10532     return true;
10533   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10534     // AddressingMode 2
10535     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10536       int RHSC = (int)RHS->getZExtValue();
10537       if (RHSC < 0 && RHSC > -0x1000) {
10538         assert(Ptr->getOpcode() == ISD::ADD);
10539         isInc = false;
10540         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10541         Base = Ptr->getOperand(0);
10542         return true;
10543       }
10544     }
10545
10546     if (Ptr->getOpcode() == ISD::ADD) {
10547       isInc = true;
10548       ARM_AM::ShiftOpc ShOpcVal=
10549         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10550       if (ShOpcVal != ARM_AM::no_shift) {
10551         Base = Ptr->getOperand(1);
10552         Offset = Ptr->getOperand(0);
10553       } else {
10554         Base = Ptr->getOperand(0);
10555         Offset = Ptr->getOperand(1);
10556       }
10557       return true;
10558     }
10559
10560     isInc = (Ptr->getOpcode() == ISD::ADD);
10561     Base = Ptr->getOperand(0);
10562     Offset = Ptr->getOperand(1);
10563     return true;
10564   }
10565
10566   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10567   return false;
10568 }
10569
10570 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10571                                      bool isSEXTLoad, SDValue &Base,
10572                                      SDValue &Offset, bool &isInc,
10573                                      SelectionDAG &DAG) {
10574   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10575     return false;
10576
10577   Base = Ptr->getOperand(0);
10578   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10579     int RHSC = (int)RHS->getZExtValue();
10580     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10581       assert(Ptr->getOpcode() == ISD::ADD);
10582       isInc = false;
10583       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10584       return true;
10585     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10586       isInc = Ptr->getOpcode() == ISD::ADD;
10587       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10588       return true;
10589     }
10590   }
10591
10592   return false;
10593 }
10594
10595 /// getPreIndexedAddressParts - returns true by value, base pointer and
10596 /// offset pointer and addressing mode by reference if the node's address
10597 /// can be legally represented as pre-indexed load / store address.
10598 bool
10599 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10600                                              SDValue &Offset,
10601                                              ISD::MemIndexedMode &AM,
10602                                              SelectionDAG &DAG) const {
10603   if (Subtarget->isThumb1Only())
10604     return false;
10605
10606   EVT VT;
10607   SDValue Ptr;
10608   bool isSEXTLoad = false;
10609   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10610     Ptr = LD->getBasePtr();
10611     VT  = LD->getMemoryVT();
10612     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10613   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10614     Ptr = ST->getBasePtr();
10615     VT  = ST->getMemoryVT();
10616   } else
10617     return false;
10618
10619   bool isInc;
10620   bool isLegal = false;
10621   if (Subtarget->isThumb2())
10622     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10623                                        Offset, isInc, DAG);
10624   else
10625     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10626                                         Offset, isInc, DAG);
10627   if (!isLegal)
10628     return false;
10629
10630   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10631   return true;
10632 }
10633
10634 /// getPostIndexedAddressParts - returns true by value, base pointer and
10635 /// offset pointer and addressing mode by reference if this node can be
10636 /// combined with a load / store to form a post-indexed load / store.
10637 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10638                                                    SDValue &Base,
10639                                                    SDValue &Offset,
10640                                                    ISD::MemIndexedMode &AM,
10641                                                    SelectionDAG &DAG) const {
10642   if (Subtarget->isThumb1Only())
10643     return false;
10644
10645   EVT VT;
10646   SDValue Ptr;
10647   bool isSEXTLoad = false;
10648   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10649     VT  = LD->getMemoryVT();
10650     Ptr = LD->getBasePtr();
10651     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10652   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10653     VT  = ST->getMemoryVT();
10654     Ptr = ST->getBasePtr();
10655   } else
10656     return false;
10657
10658   bool isInc;
10659   bool isLegal = false;
10660   if (Subtarget->isThumb2())
10661     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10662                                        isInc, DAG);
10663   else
10664     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10665                                         isInc, DAG);
10666   if (!isLegal)
10667     return false;
10668
10669   if (Ptr != Base) {
10670     // Swap base ptr and offset to catch more post-index load / store when
10671     // it's legal. In Thumb2 mode, offset must be an immediate.
10672     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10673         !Subtarget->isThumb2())
10674       std::swap(Base, Offset);
10675
10676     // Post-indexed load / store update the base pointer.
10677     if (Ptr != Base)
10678       return false;
10679   }
10680
10681   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10682   return true;
10683 }
10684
10685 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10686                                                        APInt &KnownZero,
10687                                                        APInt &KnownOne,
10688                                                        const SelectionDAG &DAG,
10689                                                        unsigned Depth) const {
10690   unsigned BitWidth = KnownOne.getBitWidth();
10691   KnownZero = KnownOne = APInt(BitWidth, 0);
10692   switch (Op.getOpcode()) {
10693   default: break;
10694   case ARMISD::ADDC:
10695   case ARMISD::ADDE:
10696   case ARMISD::SUBC:
10697   case ARMISD::SUBE:
10698     // These nodes' second result is a boolean
10699     if (Op.getResNo() == 0)
10700       break;
10701     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10702     break;
10703   case ARMISD::CMOV: {
10704     // Bits are known zero/one if known on the LHS and RHS.
10705     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10706     if (KnownZero == 0 && KnownOne == 0) return;
10707
10708     APInt KnownZeroRHS, KnownOneRHS;
10709     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10710     KnownZero &= KnownZeroRHS;
10711     KnownOne  &= KnownOneRHS;
10712     return;
10713   }
10714   }
10715 }
10716
10717 //===----------------------------------------------------------------------===//
10718 //                           ARM Inline Assembly Support
10719 //===----------------------------------------------------------------------===//
10720
10721 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10722   // Looking for "rev" which is V6+.
10723   if (!Subtarget->hasV6Ops())
10724     return false;
10725
10726   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10727   std::string AsmStr = IA->getAsmString();
10728   SmallVector<StringRef, 4> AsmPieces;
10729   SplitString(AsmStr, AsmPieces, ";\n");
10730
10731   switch (AsmPieces.size()) {
10732   default: return false;
10733   case 1:
10734     AsmStr = AsmPieces[0];
10735     AsmPieces.clear();
10736     SplitString(AsmStr, AsmPieces, " \t,");
10737
10738     // rev $0, $1
10739     if (AsmPieces.size() == 3 &&
10740         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10741         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10742       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10743       if (Ty && Ty->getBitWidth() == 32)
10744         return IntrinsicLowering::LowerToByteSwap(CI);
10745     }
10746     break;
10747   }
10748
10749   return false;
10750 }
10751
10752 /// getConstraintType - Given a constraint letter, return the type of
10753 /// constraint it is for this target.
10754 ARMTargetLowering::ConstraintType
10755 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10756   if (Constraint.size() == 1) {
10757     switch (Constraint[0]) {
10758     default:  break;
10759     case 'l': return C_RegisterClass;
10760     case 'w': return C_RegisterClass;
10761     case 'h': return C_RegisterClass;
10762     case 'x': return C_RegisterClass;
10763     case 't': return C_RegisterClass;
10764     case 'j': return C_Other; // Constant for movw.
10765       // An address with a single base register. Due to the way we
10766       // currently handle addresses it is the same as an 'r' memory constraint.
10767     case 'Q': return C_Memory;
10768     }
10769   } else if (Constraint.size() == 2) {
10770     switch (Constraint[0]) {
10771     default: break;
10772     // All 'U+' constraints are addresses.
10773     case 'U': return C_Memory;
10774     }
10775   }
10776   return TargetLowering::getConstraintType(Constraint);
10777 }
10778
10779 /// Examine constraint type and operand type and determine a weight value.
10780 /// This object must already have been set up with the operand type
10781 /// and the current alternative constraint selected.
10782 TargetLowering::ConstraintWeight
10783 ARMTargetLowering::getSingleConstraintMatchWeight(
10784     AsmOperandInfo &info, const char *constraint) const {
10785   ConstraintWeight weight = CW_Invalid;
10786   Value *CallOperandVal = info.CallOperandVal;
10787     // If we don't have a value, we can't do a match,
10788     // but allow it at the lowest weight.
10789   if (CallOperandVal == NULL)
10790     return CW_Default;
10791   Type *type = CallOperandVal->getType();
10792   // Look at the constraint type.
10793   switch (*constraint) {
10794   default:
10795     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10796     break;
10797   case 'l':
10798     if (type->isIntegerTy()) {
10799       if (Subtarget->isThumb())
10800         weight = CW_SpecificReg;
10801       else
10802         weight = CW_Register;
10803     }
10804     break;
10805   case 'w':
10806     if (type->isFloatingPointTy())
10807       weight = CW_Register;
10808     break;
10809   }
10810   return weight;
10811 }
10812
10813 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10814 RCPair
10815 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10816                                                 MVT VT) const {
10817   if (Constraint.size() == 1) {
10818     // GCC ARM Constraint Letters
10819     switch (Constraint[0]) {
10820     case 'l': // Low regs or general regs.
10821       if (Subtarget->isThumb())
10822         return RCPair(0U, &ARM::tGPRRegClass);
10823       return RCPair(0U, &ARM::GPRRegClass);
10824     case 'h': // High regs or no regs.
10825       if (Subtarget->isThumb())
10826         return RCPair(0U, &ARM::hGPRRegClass);
10827       break;
10828     case 'r':
10829       return RCPair(0U, &ARM::GPRRegClass);
10830     case 'w':
10831       if (VT == MVT::Other)
10832         break;
10833       if (VT == MVT::f32)
10834         return RCPair(0U, &ARM::SPRRegClass);
10835       if (VT.getSizeInBits() == 64)
10836         return RCPair(0U, &ARM::DPRRegClass);
10837       if (VT.getSizeInBits() == 128)
10838         return RCPair(0U, &ARM::QPRRegClass);
10839       break;
10840     case 'x':
10841       if (VT == MVT::Other)
10842         break;
10843       if (VT == MVT::f32)
10844         return RCPair(0U, &ARM::SPR_8RegClass);
10845       if (VT.getSizeInBits() == 64)
10846         return RCPair(0U, &ARM::DPR_8RegClass);
10847       if (VT.getSizeInBits() == 128)
10848         return RCPair(0U, &ARM::QPR_8RegClass);
10849       break;
10850     case 't':
10851       if (VT == MVT::f32)
10852         return RCPair(0U, &ARM::SPRRegClass);
10853       break;
10854     }
10855   }
10856   if (StringRef("{cc}").equals_lower(Constraint))
10857     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10858
10859   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10860 }
10861
10862 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10863 /// vector.  If it is invalid, don't add anything to Ops.
10864 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10865                                                      std::string &Constraint,
10866                                                      std::vector<SDValue>&Ops,
10867                                                      SelectionDAG &DAG) const {
10868   SDValue Result(0, 0);
10869
10870   // Currently only support length 1 constraints.
10871   if (Constraint.length() != 1) return;
10872
10873   char ConstraintLetter = Constraint[0];
10874   switch (ConstraintLetter) {
10875   default: break;
10876   case 'j':
10877   case 'I': case 'J': case 'K': case 'L':
10878   case 'M': case 'N': case 'O':
10879     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10880     if (!C)
10881       return;
10882
10883     int64_t CVal64 = C->getSExtValue();
10884     int CVal = (int) CVal64;
10885     // None of these constraints allow values larger than 32 bits.  Check
10886     // that the value fits in an int.
10887     if (CVal != CVal64)
10888       return;
10889
10890     switch (ConstraintLetter) {
10891       case 'j':
10892         // Constant suitable for movw, must be between 0 and
10893         // 65535.
10894         if (Subtarget->hasV6T2Ops())
10895           if (CVal >= 0 && CVal <= 65535)
10896             break;
10897         return;
10898       case 'I':
10899         if (Subtarget->isThumb1Only()) {
10900           // This must be a constant between 0 and 255, for ADD
10901           // immediates.
10902           if (CVal >= 0 && CVal <= 255)
10903             break;
10904         } else if (Subtarget->isThumb2()) {
10905           // A constant that can be used as an immediate value in a
10906           // data-processing instruction.
10907           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10908             break;
10909         } else {
10910           // A constant that can be used as an immediate value in a
10911           // data-processing instruction.
10912           if (ARM_AM::getSOImmVal(CVal) != -1)
10913             break;
10914         }
10915         return;
10916
10917       case 'J':
10918         if (Subtarget->isThumb()) {  // FIXME thumb2
10919           // This must be a constant between -255 and -1, for negated ADD
10920           // immediates. This can be used in GCC with an "n" modifier that
10921           // prints the negated value, for use with SUB instructions. It is
10922           // not useful otherwise but is implemented for compatibility.
10923           if (CVal >= -255 && CVal <= -1)
10924             break;
10925         } else {
10926           // This must be a constant between -4095 and 4095. It is not clear
10927           // what this constraint is intended for. Implemented for
10928           // compatibility with GCC.
10929           if (CVal >= -4095 && CVal <= 4095)
10930             break;
10931         }
10932         return;
10933
10934       case 'K':
10935         if (Subtarget->isThumb1Only()) {
10936           // A 32-bit value where only one byte has a nonzero value. Exclude
10937           // zero to match GCC. This constraint is used by GCC internally for
10938           // constants that can be loaded with a move/shift combination.
10939           // It is not useful otherwise but is implemented for compatibility.
10940           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10941             break;
10942         } else if (Subtarget->isThumb2()) {
10943           // A constant whose bitwise inverse can be used as an immediate
10944           // value in a data-processing instruction. This can be used in GCC
10945           // with a "B" modifier that prints the inverted value, for use with
10946           // BIC and MVN instructions. It is not useful otherwise but is
10947           // implemented for compatibility.
10948           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10949             break;
10950         } else {
10951           // A constant whose bitwise inverse can be used as an immediate
10952           // value in a data-processing instruction. This can be used in GCC
10953           // with a "B" modifier that prints the inverted value, for use with
10954           // BIC and MVN instructions. It is not useful otherwise but is
10955           // implemented for compatibility.
10956           if (ARM_AM::getSOImmVal(~CVal) != -1)
10957             break;
10958         }
10959         return;
10960
10961       case 'L':
10962         if (Subtarget->isThumb1Only()) {
10963           // This must be a constant between -7 and 7,
10964           // for 3-operand ADD/SUB immediate instructions.
10965           if (CVal >= -7 && CVal < 7)
10966             break;
10967         } else if (Subtarget->isThumb2()) {
10968           // A constant whose negation can be used as an immediate value in a
10969           // data-processing instruction. This can be used in GCC with an "n"
10970           // modifier that prints the negated value, for use with SUB
10971           // instructions. It is not useful otherwise but is implemented for
10972           // compatibility.
10973           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10974             break;
10975         } else {
10976           // A constant whose negation can be used as an immediate value in a
10977           // data-processing instruction. This can be used in GCC with an "n"
10978           // modifier that prints the negated value, for use with SUB
10979           // instructions. It is not useful otherwise but is implemented for
10980           // compatibility.
10981           if (ARM_AM::getSOImmVal(-CVal) != -1)
10982             break;
10983         }
10984         return;
10985
10986       case 'M':
10987         if (Subtarget->isThumb()) { // FIXME thumb2
10988           // This must be a multiple of 4 between 0 and 1020, for
10989           // ADD sp + immediate.
10990           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10991             break;
10992         } else {
10993           // A power of two or a constant between 0 and 32.  This is used in
10994           // GCC for the shift amount on shifted register operands, but it is
10995           // useful in general for any shift amounts.
10996           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10997             break;
10998         }
10999         return;
11000
11001       case 'N':
11002         if (Subtarget->isThumb()) {  // FIXME thumb2
11003           // This must be a constant between 0 and 31, for shift amounts.
11004           if (CVal >= 0 && CVal <= 31)
11005             break;
11006         }
11007         return;
11008
11009       case 'O':
11010         if (Subtarget->isThumb()) {  // FIXME thumb2
11011           // This must be a multiple of 4 between -508 and 508, for
11012           // ADD/SUB sp = sp + immediate.
11013           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11014             break;
11015         }
11016         return;
11017     }
11018     Result = DAG.getTargetConstant(CVal, Op.getValueType());
11019     break;
11020   }
11021
11022   if (Result.getNode()) {
11023     Ops.push_back(Result);
11024     return;
11025   }
11026   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11027 }
11028
11029 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11030   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
11031   unsigned Opcode = Op->getOpcode();
11032   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11033       "Invalid opcode for Div/Rem lowering");
11034   bool isSigned = (Opcode == ISD::SDIVREM);
11035   EVT VT = Op->getValueType(0);
11036   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11037
11038   RTLIB::Libcall LC;
11039   switch (VT.getSimpleVT().SimpleTy) {
11040   default: llvm_unreachable("Unexpected request for libcall!");
11041   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
11042   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11043   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11044   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11045   }
11046
11047   SDValue InChain = DAG.getEntryNode();
11048
11049   TargetLowering::ArgListTy Args;
11050   TargetLowering::ArgListEntry Entry;
11051   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
11052     EVT ArgVT = Op->getOperand(i).getValueType();
11053     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11054     Entry.Node = Op->getOperand(i);
11055     Entry.Ty = ArgTy;
11056     Entry.isSExt = isSigned;
11057     Entry.isZExt = !isSigned;
11058     Args.push_back(Entry);
11059   }
11060
11061   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11062                                          getPointerTy());
11063
11064   Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
11065
11066   SDLoc dl(Op);
11067   TargetLowering::
11068   CallLoweringInfo CLI(InChain, RetTy, isSigned, !isSigned, false, true,
11069                     0, getLibcallCallingConv(LC), /*isTailCall=*/false,
11070                     /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
11071                     Callee, Args, DAG, dl);
11072   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11073
11074   return CallInfo.first;
11075 }
11076
11077 bool
11078 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11079   // The ARM target isn't yet aware of offsets.
11080   return false;
11081 }
11082
11083 bool ARM::isBitFieldInvertedMask(unsigned v) {
11084   if (v == 0xffffffff)
11085     return false;
11086
11087   // there can be 1's on either or both "outsides", all the "inside"
11088   // bits must be 0's
11089   unsigned TO = CountTrailingOnes_32(v);
11090   unsigned LO = CountLeadingOnes_32(v);
11091   v = (v >> TO) << TO;
11092   v = (v << LO) >> LO;
11093   return v == 0;
11094 }
11095
11096 /// isFPImmLegal - Returns true if the target can instruction select the
11097 /// specified FP immediate natively. If false, the legalizer will
11098 /// materialize the FP immediate as a load from a constant pool.
11099 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11100   if (!Subtarget->hasVFP3())
11101     return false;
11102   if (VT == MVT::f32)
11103     return ARM_AM::getFP32Imm(Imm) != -1;
11104   if (VT == MVT::f64)
11105     return ARM_AM::getFP64Imm(Imm) != -1;
11106   return false;
11107 }
11108
11109 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11110 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11111 /// specified in the intrinsic calls.
11112 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11113                                            const CallInst &I,
11114                                            unsigned Intrinsic) const {
11115   switch (Intrinsic) {
11116   case Intrinsic::arm_neon_vld1:
11117   case Intrinsic::arm_neon_vld2:
11118   case Intrinsic::arm_neon_vld3:
11119   case Intrinsic::arm_neon_vld4:
11120   case Intrinsic::arm_neon_vld2lane:
11121   case Intrinsic::arm_neon_vld3lane:
11122   case Intrinsic::arm_neon_vld4lane: {
11123     Info.opc = ISD::INTRINSIC_W_CHAIN;
11124     // Conservatively set memVT to the entire set of vectors loaded.
11125     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
11126     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11127     Info.ptrVal = I.getArgOperand(0);
11128     Info.offset = 0;
11129     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11130     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11131     Info.vol = false; // volatile loads with NEON intrinsics not supported
11132     Info.readMem = true;
11133     Info.writeMem = false;
11134     return true;
11135   }
11136   case Intrinsic::arm_neon_vst1:
11137   case Intrinsic::arm_neon_vst2:
11138   case Intrinsic::arm_neon_vst3:
11139   case Intrinsic::arm_neon_vst4:
11140   case Intrinsic::arm_neon_vst2lane:
11141   case Intrinsic::arm_neon_vst3lane:
11142   case Intrinsic::arm_neon_vst4lane: {
11143     Info.opc = ISD::INTRINSIC_VOID;
11144     // Conservatively set memVT to the entire set of vectors stored.
11145     unsigned NumElts = 0;
11146     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11147       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11148       if (!ArgTy->isVectorTy())
11149         break;
11150       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
11151     }
11152     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11153     Info.ptrVal = I.getArgOperand(0);
11154     Info.offset = 0;
11155     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11156     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11157     Info.vol = false; // volatile stores with NEON intrinsics not supported
11158     Info.readMem = false;
11159     Info.writeMem = true;
11160     return true;
11161   }
11162   case Intrinsic::arm_ldrex: {
11163     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11164     Info.opc = ISD::INTRINSIC_W_CHAIN;
11165     Info.memVT = MVT::getVT(PtrTy->getElementType());
11166     Info.ptrVal = I.getArgOperand(0);
11167     Info.offset = 0;
11168     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11169     Info.vol = true;
11170     Info.readMem = true;
11171     Info.writeMem = false;
11172     return true;
11173   }
11174   case Intrinsic::arm_strex: {
11175     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11176     Info.opc = ISD::INTRINSIC_W_CHAIN;
11177     Info.memVT = MVT::getVT(PtrTy->getElementType());
11178     Info.ptrVal = I.getArgOperand(1);
11179     Info.offset = 0;
11180     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11181     Info.vol = true;
11182     Info.readMem = false;
11183     Info.writeMem = true;
11184     return true;
11185   }
11186   case Intrinsic::arm_strexd: {
11187     Info.opc = ISD::INTRINSIC_W_CHAIN;
11188     Info.memVT = MVT::i64;
11189     Info.ptrVal = I.getArgOperand(2);
11190     Info.offset = 0;
11191     Info.align = 8;
11192     Info.vol = true;
11193     Info.readMem = false;
11194     Info.writeMem = true;
11195     return true;
11196   }
11197   case Intrinsic::arm_ldrexd: {
11198     Info.opc = ISD::INTRINSIC_W_CHAIN;
11199     Info.memVT = MVT::i64;
11200     Info.ptrVal = I.getArgOperand(0);
11201     Info.offset = 0;
11202     Info.align = 8;
11203     Info.vol = true;
11204     Info.readMem = true;
11205     Info.writeMem = false;
11206     return true;
11207   }
11208   default:
11209     break;
11210   }
11211
11212   return false;
11213 }
11214
11215 /// \brief Returns true if it is beneficial to convert a load of a constant
11216 /// to just the constant itself.
11217 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11218                                                           Type *Ty) const {
11219   assert(Ty->isIntegerTy());
11220
11221   unsigned Bits = Ty->getPrimitiveSizeInBits();
11222   if (Bits == 0 || Bits > 32)
11223     return false;
11224   return true;
11225 }