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   // For in-prologue parameters handling, we also introduce stack offset
1830   // for byval registers: see CallingConvLower.cpp, CCState::HandleByVal.
1831   // This behaviour outsides AAPCS rules (5.5 Parameters Passing) of how
1832   // NSAA should be evaluted (NSAA means "next stacked argument address").
1833   // So: NextStackOffset = NSAAOffset + SizeOfByValParamsStoredInRegs.
1834   // Then: NSAAOffset = NextStackOffset - SizeOfByValParamsStoredInRegs.
1835   unsigned NSAAOffset = State->getNextStackOffset();
1836   if (State->getCallOrPrologue() != Call) {
1837     for (unsigned i = 0, e = State->getInRegsParamsCount(); i != e; ++i) {
1838       unsigned RB, RE;
1839       State->getInRegsParamInfo(i, RB, RE);
1840       assert(NSAAOffset >= (RE-RB)*4 &&
1841              "Stack offset for byval regs doesn't introduced anymore?");
1842       NSAAOffset -= (RE-RB)*4;
1843     }
1844   }
1845   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1846     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1847       unsigned AlignInRegs = Align / 4;
1848       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1849       for (unsigned i = 0; i < Waste; ++i)
1850         reg = State->AllocateReg(GPRArgRegs, 4);
1851     }
1852     if (reg != 0) {
1853       unsigned excess = 4 * (ARM::R4 - reg);
1854 
1855       // Special case when NSAA != SP and parameter size greater than size of
1856       // all remained GPR regs. In that case we can't split parameter, we must
1857       // send it to stack. We also must set NCRN to R4, so waste all
1858       // remained registers.
1859       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1860         while (State->AllocateReg(GPRArgRegs, 4))
1861           ;
1862         return;
1863       }
1864 
1865       // First register for byval parameter is the first register that wasn't
1866       // allocated before this method call, so it would be "reg".
1867       // If parameter is small enough to be saved in range [reg, r4), then
1868       // the end (first after last) register would be reg + param-size-in-regs,
1869       // else parameter would be splitted between registers and stack,
1870       // end register would be r4 in this case.
1871       unsigned ByValRegBegin = reg;
1872       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1873       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1874       // Note, first register is allocated in the beginning of function already,
1875       // allocate remained amount of registers we need.
1876       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1877         State->AllocateReg(GPRArgRegs, 4);
1878       // At a call site, a byval parameter that is split between
1879       // registers and memory needs its size truncated here.  In a
1880       // function prologue, such byval parameters are reassembled in
1881       // memory, and are not truncated.
1882       if (State->getCallOrPrologue() == Call) {
1883         // Make remained size equal to 0 in case, when
1884         // the whole structure may be stored into registers.
1885         if (size < excess)
1886           size = 0;
1887         else
1888           size -= excess;
1889       }
1890     }
1891   }
1892 }
1893 
1894 /// MatchingStackOffset - Return true if the given stack call argument is
1895 /// already available in the same position (relatively) of the caller's
1896 /// incoming argument stack.
1897 static
1898 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1899                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1900                          const TargetInstrInfo *TII) {
1901   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1902   int FI = INT_MAX;
1903   if (Arg.getOpcode() == ISD::CopyFromReg) {
1904     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1905     if (!TargetRegisterInfo::isVirtualRegister(VR))
1906       return false;
1907     MachineInstr *Def = MRI->getVRegDef(VR);
1908     if (!Def)
1909       return false;
1910     if (!Flags.isByVal()) {
1911       if (!TII->isLoadFromStackSlot(Def, FI))
1912         return false;
1913     } else {
1914       return false;
1915     }
1916   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1917     if (Flags.isByVal())
1918       // ByVal argument is passed in as a pointer but it's now being
1919       // dereferenced. e.g.
1920       // define @foo(%struct.X* %A) {
1921       //   tail call @bar(%struct.X* byval %A)
1922       // }
1923       return false;
1924     SDValue Ptr = Ld->getBasePtr();
1925     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1926     if (!FINode)
1927       return false;
1928     FI = FINode->getIndex();
1929   } else
1930     return false;
1931 
1932   assert(FI != INT_MAX);
1933   if (!MFI->isFixedObjectIndex(FI))
1934     return false;
1935   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1936 }
1937 
1938 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1939 /// for tail call optimization. Targets which want to do tail call
1940 /// optimization should implement this function.
1941 bool
1942 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1943                                                      CallingConv::ID CalleeCC,
1944                                                      bool isVarArg,
1945                                                      bool isCalleeStructRet,
1946                                                      bool isCallerStructRet,
1947                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1948                                     const SmallVectorImpl<SDValue> &OutVals,
1949                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1950                                                      SelectionDAG& DAG) const {
1951   const Function *CallerF = DAG.getMachineFunction().getFunction();
1952   CallingConv::ID CallerCC = CallerF->getCallingConv();
1953   bool CCMatch = CallerCC == CalleeCC;
1954 
1955   // Look for obvious safe cases to perform tail call optimization that do not
1956   // require ABI changes. This is what gcc calls sibcall.
1957 
1958   // Do not sibcall optimize vararg calls unless the call site is not passing
1959   // any arguments.
1960   if (isVarArg && !Outs.empty())
1961     return false;
1962 
1963   // Exception-handling functions need a special set of instructions to indicate
1964   // a return to the hardware. Tail-calling another function would probably
1965   // break this.
1966   if (CallerF->hasFnAttribute("interrupt"))
1967     return false;
1968 
1969   // Also avoid sibcall optimization if either caller or callee uses struct
1970   // return semantics.
1971   if (isCalleeStructRet || isCallerStructRet)
1972     return false;
1973 
1974   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1975   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1976   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1977   // support in the assembler and linker to be used. This would need to be
1978   // fixed to fully support tail calls in Thumb1.
1979   //
1980   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1981   // LR.  This means if we need to reload LR, it takes an extra instructions,
1982   // which outweighs the value of the tail call; but here we don't know yet
1983   // whether LR is going to be used.  Probably the right approach is to
1984   // generate the tail call here and turn it back into CALL/RET in
1985   // emitEpilogue if LR is used.
1986 
1987   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1988   // but we need to make sure there are enough registers; the only valid
1989   // registers are the 4 used for parameters.  We don't currently do this
1990   // case.
1991   if (Subtarget->isThumb1Only())
1992     return false;
1993 
1994   // If the calling conventions do not match, then we'd better make sure the
1995   // results are returned in the same way as what the caller expects.
1996   if (!CCMatch) {
1997     SmallVector<CCValAssign, 16> RVLocs1;
1998     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1999                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
2000     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2001 
2002     SmallVector<CCValAssign, 16> RVLocs2;
2003     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2004                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
2005     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2006 
2007     if (RVLocs1.size() != RVLocs2.size())
2008       return false;
2009     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2010       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2011         return false;
2012       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2013         return false;
2014       if (RVLocs1[i].isRegLoc()) {
2015         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2016           return false;
2017       } else {
2018         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2019           return false;
2020       }
2021     }
2022   }
2023 
2024   // If Caller's vararg or byval argument has been split between registers and
2025   // stack, do not perform tail call, since part of the argument is in caller's
2026   // local frame.
2027   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2028                                       getInfo<ARMFunctionInfo>();
2029   if (AFI_Caller->getArgRegsSaveSize())
2030     return false;
2031 
2032   // If the callee takes no arguments then go on to check the results of the
2033   // call.
2034   if (!Outs.empty()) {
2035     // Check if stack adjustment is needed. For now, do not do this if any
2036     // argument is passed on the stack.
2037     SmallVector<CCValAssign, 16> ArgLocs;
2038     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2039                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
2040     CCInfo.AnalyzeCallOperands(Outs,
2041                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2042     if (CCInfo.getNextStackOffset()) {
2043       MachineFunction &MF = DAG.getMachineFunction();
2044 
2045       // Check if the arguments are already laid out in the right way as
2046       // the caller's fixed stack objects.
2047       MachineFrameInfo *MFI = MF.getFrameInfo();
2048       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2049       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2050       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2051            i != e;
2052            ++i, ++realArgIdx) {
2053         CCValAssign &VA = ArgLocs[i];
2054         EVT RegVT = VA.getLocVT();
2055         SDValue Arg = OutVals[realArgIdx];
2056         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2057         if (VA.getLocInfo() == CCValAssign::Indirect)
2058           return false;
2059         if (VA.needsCustom()) {
2060           // f64 and vector types are split into multiple registers or
2061           // register/stack-slot combinations.  The types will not match
2062           // the registers; give up on memory f64 refs until we figure
2063           // out what to do about this.
2064           if (!VA.isRegLoc())
2065             return false;
2066           if (!ArgLocs[++i].isRegLoc())
2067             return false;
2068           if (RegVT == MVT::v2f64) {
2069             if (!ArgLocs[++i].isRegLoc())
2070               return false;
2071             if (!ArgLocs[++i].isRegLoc())
2072               return false;
2073           }
2074         } else if (!VA.isRegLoc()) {
2075           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2076                                    MFI, MRI, TII))
2077             return false;
2078         }
2079       }
2080     }
2081   }
2082 
2083   return true;
2084 }
2085 
2086 bool
2087 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2088                                   MachineFunction &MF, bool isVarArg,
2089                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2090                                   LLVMContext &Context) const {
2091   SmallVector<CCValAssign, 16> RVLocs;
2092   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2093   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2094                                                     isVarArg));
2095 }
2096 
2097 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2098                                     SDLoc DL, SelectionDAG &DAG) {
2099   const MachineFunction &MF = DAG.getMachineFunction();
2100   const Function *F = MF.getFunction();
2101 
2102   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2103 
2104   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2105   // version of the "preferred return address". These offsets affect the return
2106   // instruction if this is a return from PL1 without hypervisor extensions.
2107   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2108   //    SWI:     0      "subs pc, lr, #0"
2109   //    ABORT:   +4     "subs pc, lr, #4"
2110   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2111   // UNDEF varies depending on where the exception came from ARM or Thumb
2112   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2113 
2114   int64_t LROffset;
2115   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2116       IntKind == "ABORT")
2117     LROffset = 4;
2118   else if (IntKind == "SWI" || IntKind == "UNDEF")
2119     LROffset = 0;
2120   else
2121     report_fatal_error("Unsupported interrupt attribute. If present, value "
2122                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2123 
2124   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2125 
2126   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other,
2127                      RetOps.data(), RetOps.size());
2128 }
2129 
2130 SDValue
2131 ARMTargetLowering::LowerReturn(SDValue Chain,
2132                                CallingConv::ID CallConv, bool isVarArg,
2133                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2134                                const SmallVectorImpl<SDValue> &OutVals,
2135                                SDLoc dl, SelectionDAG &DAG) const {
2136 
2137   // CCValAssign - represent the assignment of the return value to a location.
2138   SmallVector<CCValAssign, 16> RVLocs;
2139 
2140   // CCState - Info about the registers and stack slots.
2141   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2142                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2143 
2144   // Analyze outgoing return values.
2145   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2146                                                isVarArg));
2147 
2148   SDValue Flag;
2149   SmallVector<SDValue, 4> RetOps;
2150   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2151 
2152   // Copy the result values into the output registers.
2153   for (unsigned i = 0, realRVLocIdx = 0;
2154        i != RVLocs.size();
2155        ++i, ++realRVLocIdx) {
2156     CCValAssign &VA = RVLocs[i];
2157     assert(VA.isRegLoc() && "Can only return in registers!");
2158 
2159     SDValue Arg = OutVals[realRVLocIdx];
2160 
2161     switch (VA.getLocInfo()) {
2162     default: llvm_unreachable("Unknown loc info!");
2163     case CCValAssign::Full: break;
2164     case CCValAssign::BCvt:
2165       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2166       break;
2167     }
2168 
2169     if (VA.needsCustom()) {
2170       if (VA.getLocVT() == MVT::v2f64) {
2171         // Extract the first half and return it in two registers.
2172         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2173                                    DAG.getConstant(0, MVT::i32));
2174         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2175                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2176 
2177         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
2178         Flag = Chain.getValue(1);
2179         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2180         VA = RVLocs[++i]; // skip ahead to next loc
2181         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2182                                  HalfGPRs.getValue(1), Flag);
2183         Flag = Chain.getValue(1);
2184         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2185         VA = RVLocs[++i]; // skip ahead to next loc
2186 
2187         // Extract the 2nd half and fall through to handle it as an f64 value.
2188         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2189                           DAG.getConstant(1, MVT::i32));
2190       }
2191       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2192       // available.
2193       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2194                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
2195       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
2196       Flag = Chain.getValue(1);
2197       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2198       VA = RVLocs[++i]; // skip ahead to next loc
2199       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
2200                                Flag);
2201     } else
2202       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2203 
2204     // Guarantee that all emitted copies are
2205     // stuck together, avoiding something bad.
2206     Flag = Chain.getValue(1);
2207     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2208   }
2209 
2210   // Update chain and glue.
2211   RetOps[0] = Chain;
2212   if (Flag.getNode())
2213     RetOps.push_back(Flag);
2214 
2215   // CPUs which aren't M-class use a special sequence to return from
2216   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2217   // though we use "subs pc, lr, #N").
2218   //
2219   // M-class CPUs actually use a normal return sequence with a special
2220   // (hardware-provided) value in LR, so the normal code path works.
2221   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2222       !Subtarget->isMClass()) {
2223     if (Subtarget->isThumb1Only())
2224       report_fatal_error("interrupt attribute is not supported in Thumb1");
2225     return LowerInterruptReturn(RetOps, dl, DAG);
2226   }
2227 
2228   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
2229                      RetOps.data(), RetOps.size());
2230 }
2231 
2232 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2233   if (N->getNumValues() != 1)
2234     return false;
2235   if (!N->hasNUsesOfValue(1, 0))
2236     return false;
2237 
2238   SDValue TCChain = Chain;
2239   SDNode *Copy = *N->use_begin();
2240   if (Copy->getOpcode() == ISD::CopyToReg) {
2241     // If the copy has a glue operand, we conservatively assume it isn't safe to
2242     // perform a tail call.
2243     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2244       return false;
2245     TCChain = Copy->getOperand(0);
2246   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2247     SDNode *VMov = Copy;
2248     // f64 returned in a pair of GPRs.
2249     SmallPtrSet<SDNode*, 2> Copies;
2250     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2251          UI != UE; ++UI) {
2252       if (UI->getOpcode() != ISD::CopyToReg)
2253         return false;
2254       Copies.insert(*UI);
2255     }
2256     if (Copies.size() > 2)
2257       return false;
2258 
2259     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2260          UI != UE; ++UI) {
2261       SDValue UseChain = UI->getOperand(0);
2262       if (Copies.count(UseChain.getNode()))
2263         // Second CopyToReg
2264         Copy = *UI;
2265       else
2266         // First CopyToReg
2267         TCChain = UseChain;
2268     }
2269   } else if (Copy->getOpcode() == ISD::BITCAST) {
2270     // f32 returned in a single GPR.
2271     if (!Copy->hasOneUse())
2272       return false;
2273     Copy = *Copy->use_begin();
2274     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2275       return false;
2276     TCChain = Copy->getOperand(0);
2277   } else {
2278     return false;
2279   }
2280 
2281   bool HasRet = false;
2282   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2283        UI != UE; ++UI) {
2284     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2285         UI->getOpcode() != ARMISD::INTRET_FLAG)
2286       return false;
2287     HasRet = true;
2288   }
2289 
2290   if (!HasRet)
2291     return false;
2292 
2293   Chain = TCChain;
2294   return true;
2295 }
2296 
2297 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2298   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2299     return false;
2300 
2301   if (!CI->isTailCall())
2302     return false;
2303 
2304   return !Subtarget->isThumb1Only();
2305 }
2306 
2307 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2308 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2309 // one of the above mentioned nodes. It has to be wrapped because otherwise
2310 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2311 // be used to form addressing mode. These wrapped nodes will be selected
2312 // into MOVi.
2313 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2314   EVT PtrVT = Op.getValueType();
2315   // FIXME there is no actual debug info here
2316   SDLoc dl(Op);
2317   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2318   SDValue Res;
2319   if (CP->isMachineConstantPoolEntry())
2320     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2321                                     CP->getAlignment());
2322   else
2323     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2324                                     CP->getAlignment());
2325   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2326 }
2327 
2328 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2329   return MachineJumpTableInfo::EK_Inline;
2330 }
2331 
2332 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2333                                              SelectionDAG &DAG) const {
2334   MachineFunction &MF = DAG.getMachineFunction();
2335   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2336   unsigned ARMPCLabelIndex = 0;
2337   SDLoc DL(Op);
2338   EVT PtrVT = getPointerTy();
2339   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2340   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2341   SDValue CPAddr;
2342   if (RelocM == Reloc::Static) {
2343     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2344   } else {
2345     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2346     ARMPCLabelIndex = AFI->createPICLabelUId();
2347     ARMConstantPoolValue *CPV =
2348       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2349                                       ARMCP::CPBlockAddress, PCAdj);
2350     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2351   }
2352   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2353   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2354                                MachinePointerInfo::getConstantPool(),
2355                                false, false, false, 0);
2356   if (RelocM == Reloc::Static)
2357     return Result;
2358   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2359   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2360 }
2361 
2362 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2363 SDValue
2364 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2365                                                  SelectionDAG &DAG) const {
2366   SDLoc dl(GA);
2367   EVT PtrVT = getPointerTy();
2368   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2369   MachineFunction &MF = DAG.getMachineFunction();
2370   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2371   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2372   ARMConstantPoolValue *CPV =
2373     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2374                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2375   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2376   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2377   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2378                          MachinePointerInfo::getConstantPool(),
2379                          false, false, false, 0);
2380   SDValue Chain = Argument.getValue(1);
2381 
2382   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2383   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2384 
2385   // call __tls_get_addr.
2386   ArgListTy Args;
2387   ArgListEntry Entry;
2388   Entry.Node = Argument;
2389   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2390   Args.push_back(Entry);
2391   // FIXME: is there useful debug info available here?
2392   TargetLowering::CallLoweringInfo CLI(Chain,
2393                 (Type *) Type::getInt32Ty(*DAG.getContext()),
2394                 false, false, false, false,
2395                 0, CallingConv::C, /*isTailCall=*/false,
2396                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2397                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2398   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2399   return CallResult.first;
2400 }
2401 
2402 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2403 // "local exec" model.
2404 SDValue
2405 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2406                                         SelectionDAG &DAG,
2407                                         TLSModel::Model model) const {
2408   const GlobalValue *GV = GA->getGlobal();
2409   SDLoc dl(GA);
2410   SDValue Offset;
2411   SDValue Chain = DAG.getEntryNode();
2412   EVT PtrVT = getPointerTy();
2413   // Get the Thread Pointer
2414   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2415 
2416   if (model == TLSModel::InitialExec) {
2417     MachineFunction &MF = DAG.getMachineFunction();
2418     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2419     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2420     // Initial exec model.
2421     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2422     ARMConstantPoolValue *CPV =
2423       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2424                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2425                                       true);
2426     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2427     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2428     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2429                          MachinePointerInfo::getConstantPool(),
2430                          false, false, false, 0);
2431     Chain = Offset.getValue(1);
2432 
2433     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2434     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2435 
2436     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2437                          MachinePointerInfo::getConstantPool(),
2438                          false, false, false, 0);
2439   } else {
2440     // local exec model
2441     assert(model == TLSModel::LocalExec);
2442     ARMConstantPoolValue *CPV =
2443       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2444     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2445     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2446     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2447                          MachinePointerInfo::getConstantPool(),
2448                          false, false, false, 0);
2449   }
2450 
2451   // The address of the thread local variable is the add of the thread
2452   // pointer with the offset of the variable.
2453   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2454 }
2455 
2456 SDValue
2457 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2458   // TODO: implement the "local dynamic" model
2459   assert(Subtarget->isTargetELF() &&
2460          "TLS not implemented for non-ELF targets");
2461   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2462 
2463   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2464 
2465   switch (model) {
2466     case TLSModel::GeneralDynamic:
2467     case TLSModel::LocalDynamic:
2468       return LowerToTLSGeneralDynamicModel(GA, DAG);
2469     case TLSModel::InitialExec:
2470     case TLSModel::LocalExec:
2471       return LowerToTLSExecModels(GA, DAG, model);
2472   }
2473   llvm_unreachable("bogus TLS model");
2474 }
2475 
2476 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2477                                                  SelectionDAG &DAG) const {
2478   EVT PtrVT = getPointerTy();
2479   SDLoc dl(Op);
2480   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2481   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2482     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2483     ARMConstantPoolValue *CPV =
2484       ARMConstantPoolConstant::Create(GV,
2485                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2486     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2487     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2488     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2489                                  CPAddr,
2490                                  MachinePointerInfo::getConstantPool(),
2491                                  false, false, false, 0);
2492     SDValue Chain = Result.getValue(1);
2493     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2494     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2495     if (!UseGOTOFF)
2496       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2497                            MachinePointerInfo::getGOT(),
2498                            false, false, false, 0);
2499     return Result;
2500   }
2501 
2502   // If we have T2 ops, we can materialize the address directly via movt/movw
2503   // pair. This is always cheaper.
2504   if (Subtarget->useMovt()) {
2505     ++NumMovwMovt;
2506     // FIXME: Once remat is capable of dealing with instructions with register
2507     // operands, expand this into two nodes.
2508     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2509                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2510   } else {
2511     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2512     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2513     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2514                        MachinePointerInfo::getConstantPool(),
2515                        false, false, false, 0);
2516   }
2517 }
2518 
2519 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2520                                                     SelectionDAG &DAG) const {
2521   EVT PtrVT = getPointerTy();
2522   SDLoc dl(Op);
2523   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2524   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2525 
2526   if (Subtarget->useMovt())
2527     ++NumMovwMovt;
2528 
2529   // FIXME: Once remat is capable of dealing with instructions with register
2530   // operands, expand this into multiple nodes
2531   unsigned Wrapper =
2532       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2533 
2534   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2535   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2536 
2537   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2538     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2539                          MachinePointerInfo::getGOT(), false, false, false, 0);
2540   return Result;
2541 }
2542 
2543 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2544                                                     SelectionDAG &DAG) const {
2545   assert(Subtarget->isTargetELF() &&
2546          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2547   MachineFunction &MF = DAG.getMachineFunction();
2548   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2549   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2550   EVT PtrVT = getPointerTy();
2551   SDLoc dl(Op);
2552   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2553   ARMConstantPoolValue *CPV =
2554     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2555                                   ARMPCLabelIndex, PCAdj);
2556   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2557   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2558   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2559                                MachinePointerInfo::getConstantPool(),
2560                                false, false, false, 0);
2561   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2562   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2563 }
2564 
2565 SDValue
2566 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2567   SDLoc dl(Op);
2568   SDValue Val = DAG.getConstant(0, MVT::i32);
2569   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2570                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2571                      Op.getOperand(1), Val);
2572 }
2573 
2574 SDValue
2575 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2576   SDLoc dl(Op);
2577   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2578                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2579 }
2580 
2581 SDValue
2582 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2583                                           const ARMSubtarget *Subtarget) const {
2584   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2585   SDLoc dl(Op);
2586   switch (IntNo) {
2587   default: return SDValue();    // Don't custom lower most intrinsics.
2588   case Intrinsic::arm_thread_pointer: {
2589     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2590     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2591   }
2592   case Intrinsic::eh_sjlj_lsda: {
2593     MachineFunction &MF = DAG.getMachineFunction();
2594     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2595     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2596     EVT PtrVT = getPointerTy();
2597     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2598     SDValue CPAddr;
2599     unsigned PCAdj = (RelocM != Reloc::PIC_)
2600       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2601     ARMConstantPoolValue *CPV =
2602       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2603                                       ARMCP::CPLSDA, PCAdj);
2604     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2605     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2606     SDValue Result =
2607       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2608                   MachinePointerInfo::getConstantPool(),
2609                   false, false, false, 0);
2610 
2611     if (RelocM == Reloc::PIC_) {
2612       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2613       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2614     }
2615     return Result;
2616   }
2617   case Intrinsic::arm_neon_vmulls:
2618   case Intrinsic::arm_neon_vmullu: {
2619     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2620       ? ARMISD::VMULLs : ARMISD::VMULLu;
2621     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2622                        Op.getOperand(1), Op.getOperand(2));
2623   }
2624   }
2625 }
2626 
2627 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2628                                  const ARMSubtarget *Subtarget) {
2629   // FIXME: handle "fence singlethread" more efficiently.
2630   SDLoc dl(Op);
2631   if (!Subtarget->hasDataBarrier()) {
2632     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2633     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2634     // here.
2635     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2636            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2637     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2638                        DAG.getConstant(0, MVT::i32));
2639   }
2640 
2641   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2642   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2643   unsigned Domain = ARM_MB::ISH;
2644   if (Subtarget->isMClass()) {
2645     // Only a full system barrier exists in the M-class architectures.
2646     Domain = ARM_MB::SY;
2647   } else if (Subtarget->isSwift() && Ord == Release) {
2648     // Swift happens to implement ISHST barriers in a way that's compatible with
2649     // Release semantics but weaker than ISH so we'd be fools not to use
2650     // it. Beware: other processors probably don't!
2651     Domain = ARM_MB::ISHST;
2652   }
2653 
2654   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2655                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2656                      DAG.getConstant(Domain, MVT::i32));
2657 }
2658 
2659 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2660                              const ARMSubtarget *Subtarget) {
2661   // ARM pre v5TE and Thumb1 does not have preload instructions.
2662   if (!(Subtarget->isThumb2() ||
2663         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2664     // Just preserve the chain.
2665     return Op.getOperand(0);
2666 
2667   SDLoc dl(Op);
2668   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2669   if (!isRead &&
2670       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2671     // ARMv7 with MP extension has PLDW.
2672     return Op.getOperand(0);
2673 
2674   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2675   if (Subtarget->isThumb()) {
2676     // Invert the bits.
2677     isRead = ~isRead & 1;
2678     isData = ~isData & 1;
2679   }
2680 
2681   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2682                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2683                      DAG.getConstant(isData, MVT::i32));
2684 }
2685 
2686 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2687   MachineFunction &MF = DAG.getMachineFunction();
2688   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2689 
2690   // vastart just stores the address of the VarArgsFrameIndex slot into the
2691   // memory location argument.
2692   SDLoc dl(Op);
2693   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2694   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2695   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2696   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2697                       MachinePointerInfo(SV), false, false, 0);
2698 }
2699 
2700 SDValue
2701 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2702                                         SDValue &Root, SelectionDAG &DAG,
2703                                         SDLoc dl) const {
2704   MachineFunction &MF = DAG.getMachineFunction();
2705   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2706 
2707   const TargetRegisterClass *RC;
2708   if (AFI->isThumb1OnlyFunction())
2709     RC = &ARM::tGPRRegClass;
2710   else
2711     RC = &ARM::GPRRegClass;
2712 
2713   // Transform the arguments stored in physical registers into virtual ones.
2714   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2715   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2716 
2717   SDValue ArgValue2;
2718   if (NextVA.isMemLoc()) {
2719     MachineFrameInfo *MFI = MF.getFrameInfo();
2720     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2721 
2722     // Create load node to retrieve arguments from the stack.
2723     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2724     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2725                             MachinePointerInfo::getFixedStack(FI),
2726                             false, false, false, 0);
2727   } else {
2728     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2729     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2730   }
2731 
2732   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2733 }
2734 
2735 void
2736 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2737                                   unsigned InRegsParamRecordIdx,
2738                                   unsigned ArgSize,
2739                                   unsigned &ArgRegsSize,
2740                                   unsigned &ArgRegsSaveSize)
2741   const {
2742   unsigned NumGPRs;
2743   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2744     unsigned RBegin, REnd;
2745     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2746     NumGPRs = REnd - RBegin;
2747   } else {
2748     unsigned int firstUnalloced;
2749     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2750                                                 sizeof(GPRArgRegs) /
2751                                                 sizeof(GPRArgRegs[0]));
2752     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2753   }
2754 
2755   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2756   ArgRegsSize = NumGPRs * 4;
2757 
2758   // If parameter is split between stack and GPRs...
2759   if (NumGPRs && Align == 8 &&
2760       (ArgRegsSize < ArgSize ||
2761         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2762     // Add padding for part of param recovered from GPRs, so
2763     // its last byte must be at address K*8 - 1.
2764     // We need to do it, since remained (stack) part of parameter has
2765     // stack alignment, and we need to "attach" "GPRs head" without gaps
2766     // to it:
2767     // Stack:
2768     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2769     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2770     //
2771     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2772     unsigned Padding =
2773         ((ArgRegsSize + AFI->getArgRegsSaveSize() + Align - 1) & ~(Align-1)) -
2774         (ArgRegsSize + AFI->getArgRegsSaveSize());
2775     ArgRegsSaveSize = ArgRegsSize + Padding;
2776   } else
2777     // We don't need to extend regs save size for byval parameters if they
2778     // are passed via GPRs only.
2779     ArgRegsSaveSize = ArgRegsSize;
2780 }
2781 
2782 // The remaining GPRs hold either the beginning of variable-argument
2783 // data, or the beginning of an aggregate passed by value (usually
2784 // byval).  Either way, we allocate stack slots adjacent to the data
2785 // provided by our caller, and store the unallocated registers there.
2786 // If this is a variadic function, the va_list pointer will begin with
2787 // these values; otherwise, this reassembles a (byval) structure that
2788 // was split between registers and memory.
2789 // Return: The frame index registers were stored into.
2790 int
2791 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2792                                   SDLoc dl, SDValue &Chain,
2793                                   const Value *OrigArg,
2794                                   unsigned InRegsParamRecordIdx,
2795                                   unsigned OffsetFromOrigArg,
2796                                   unsigned ArgOffset,
2797                                   unsigned ArgSize,
2798                                   bool ForceMutable) const {
2799 
2800   // Currently, two use-cases possible:
2801   // Case #1. Non-var-args function, and we meet first byval parameter.
2802   //          Setup first unallocated register as first byval register;
2803   //          eat all remained registers
2804   //          (these two actions are performed by HandleByVal method).
2805   //          Then, here, we initialize stack frame with
2806   //          "store-reg" instructions.
2807   // Case #2. Var-args function, that doesn't contain byval parameters.
2808   //          The same: eat all remained unallocated registers,
2809   //          initialize stack frame.
2810 
2811   MachineFunction &MF = DAG.getMachineFunction();
2812   MachineFrameInfo *MFI = MF.getFrameInfo();
2813   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2814   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2815   unsigned RBegin, REnd;
2816   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2817     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2818     firstRegToSaveIndex = RBegin - ARM::R0;
2819     lastRegToSaveIndex = REnd - ARM::R0;
2820   } else {
2821     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2822       (GPRArgRegs, array_lengthof(GPRArgRegs));
2823     lastRegToSaveIndex = 4;
2824   }
2825 
2826   unsigned ArgRegsSize, ArgRegsSaveSize;
2827   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2828                  ArgRegsSize, ArgRegsSaveSize);
2829 
2830   // Store any by-val regs to their spots on the stack so that they may be
2831   // loaded by deferencing the result of formal parameter pointer or va_next.
2832   // Note: once stack area for byval/varargs registers
2833   // was initialized, it can't be initialized again.
2834   if (ArgRegsSaveSize) {
2835 
2836     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2837 
2838     if (Padding) {
2839       assert(AFI->getStoredByValParamsPadding() == 0 &&
2840              "The only parameter may be padded.");
2841       AFI->setStoredByValParamsPadding(Padding);
2842     }
2843 
2844     int FrameIndex = MFI->CreateFixedObject(
2845                       ArgRegsSaveSize,
2846                       Padding + ArgOffset,
2847                       false);
2848     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2849 
2850     SmallVector<SDValue, 4> MemOps;
2851     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2852          ++firstRegToSaveIndex, ++i) {
2853       const TargetRegisterClass *RC;
2854       if (AFI->isThumb1OnlyFunction())
2855         RC = &ARM::tGPRRegClass;
2856       else
2857         RC = &ARM::GPRRegClass;
2858 
2859       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2860       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2861       SDValue Store =
2862         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2863                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2864                      false, false, 0);
2865       MemOps.push_back(Store);
2866       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2867                         DAG.getConstant(4, getPointerTy()));
2868     }
2869 
2870     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2871 
2872     if (!MemOps.empty())
2873       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2874                           &MemOps[0], MemOps.size());
2875     return FrameIndex;
2876   } else
2877     // This will point to the next argument passed via stack.
2878     return MFI->CreateFixedObject(
2879         4, AFI->getStoredByValParamsPadding() + ArgOffset, !ForceMutable);
2880 }
2881 
2882 // Setup stack frame, the va_list pointer will start from.
2883 void
2884 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2885                                         SDLoc dl, SDValue &Chain,
2886                                         unsigned ArgOffset,
2887                                         bool ForceMutable) const {
2888   MachineFunction &MF = DAG.getMachineFunction();
2889   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2890 
2891   // Try to store any remaining integer argument regs
2892   // to their spots on the stack so that they may be loaded by deferencing
2893   // the result of va_next.
2894   // If there is no regs to be stored, just point address after last
2895   // argument passed via stack.
2896   int FrameIndex =
2897     StoreByValRegs(CCInfo, DAG, dl, Chain, 0, CCInfo.getInRegsParamsCount(),
2898                    0, ArgOffset, 0, ForceMutable);
2899 
2900   AFI->setVarArgsFrameIndex(FrameIndex);
2901 }
2902 
2903 SDValue
2904 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2905                                         CallingConv::ID CallConv, bool isVarArg,
2906                                         const SmallVectorImpl<ISD::InputArg>
2907                                           &Ins,
2908                                         SDLoc dl, SelectionDAG &DAG,
2909                                         SmallVectorImpl<SDValue> &InVals)
2910                                           const {
2911   MachineFunction &MF = DAG.getMachineFunction();
2912   MachineFrameInfo *MFI = MF.getFrameInfo();
2913 
2914   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2915 
2916   // Assign locations to all of the incoming arguments.
2917   SmallVector<CCValAssign, 16> ArgLocs;
2918   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2919                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2920   CCInfo.AnalyzeFormalArguments(Ins,
2921                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2922                                                   isVarArg));
2923 
2924   SmallVector<SDValue, 16> ArgValues;
2925   int lastInsIndex = -1;
2926   SDValue ArgValue;
2927   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2928   unsigned CurArgIdx = 0;
2929 
2930   // Initially ArgRegsSaveSize is zero.
2931   // Then we increase this value each time we meet byval parameter.
2932   // We also increase this value in case of varargs function.
2933   AFI->setArgRegsSaveSize(0);
2934 
2935   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2936     CCValAssign &VA = ArgLocs[i];
2937     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2938     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2939     // Arguments stored in registers.
2940     if (VA.isRegLoc()) {
2941       EVT RegVT = VA.getLocVT();
2942 
2943       if (VA.needsCustom()) {
2944         // f64 and vector types are split up into multiple registers or
2945         // combinations of registers and stack slots.
2946         if (VA.getLocVT() == MVT::v2f64) {
2947           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2948                                                    Chain, DAG, dl);
2949           VA = ArgLocs[++i]; // skip ahead to next loc
2950           SDValue ArgValue2;
2951           if (VA.isMemLoc()) {
2952             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2953             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2954             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2955                                     MachinePointerInfo::getFixedStack(FI),
2956                                     false, false, false, 0);
2957           } else {
2958             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2959                                              Chain, DAG, dl);
2960           }
2961           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2962           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2963                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2964           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2965                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2966         } else
2967           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2968 
2969       } else {
2970         const TargetRegisterClass *RC;
2971 
2972         if (RegVT == MVT::f32)
2973           RC = &ARM::SPRRegClass;
2974         else if (RegVT == MVT::f64)
2975           RC = &ARM::DPRRegClass;
2976         else if (RegVT == MVT::v2f64)
2977           RC = &ARM::QPRRegClass;
2978         else if (RegVT == MVT::i32)
2979           RC = AFI->isThumb1OnlyFunction() ?
2980             (const TargetRegisterClass*)&ARM::tGPRRegClass :
2981             (const TargetRegisterClass*)&ARM::GPRRegClass;
2982         else
2983           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2984 
2985         // Transform the arguments in physical registers into virtual ones.
2986         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2987         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2988       }
2989 
2990       // If this is an 8 or 16-bit value, it is really passed promoted
2991       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2992       // truncate to the right size.
2993       switch (VA.getLocInfo()) {
2994       default: llvm_unreachable("Unknown loc info!");
2995       case CCValAssign::Full: break;
2996       case CCValAssign::BCvt:
2997         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2998         break;
2999       case CCValAssign::SExt:
3000         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3001                                DAG.getValueType(VA.getValVT()));
3002         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3003         break;
3004       case CCValAssign::ZExt:
3005         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3006                                DAG.getValueType(VA.getValVT()));
3007         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3008         break;
3009       }
3010 
3011       InVals.push_back(ArgValue);
3012 
3013     } else { // VA.isRegLoc()
3014 
3015       // sanity check
3016       assert(VA.isMemLoc());
3017       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3018 
3019       int index = ArgLocs[i].getValNo();
3020 
3021       // Some Ins[] entries become multiple ArgLoc[] entries.
3022       // Process them only once.
3023       if (index != lastInsIndex)
3024         {
3025           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3026           // FIXME: For now, all byval parameter objects are marked mutable.
3027           // This can be changed with more analysis.
3028           // In case of tail call optimization mark all arguments mutable.
3029           // Since they could be overwritten by lowering of arguments in case of
3030           // a tail call.
3031           if (Flags.isByVal()) {
3032             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3033             int FrameIndex = StoreByValRegs(
3034                 CCInfo, DAG, dl, Chain, CurOrigArg,
3035                 CurByValIndex,
3036                 Ins[VA.getValNo()].PartOffset,
3037                 VA.getLocMemOffset(),
3038                 Flags.getByValSize(),
3039                 true /*force mutable frames*/);
3040             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3041             CCInfo.nextInRegsParam();
3042           } else {
3043             unsigned FIOffset = VA.getLocMemOffset() +
3044                                 AFI->getStoredByValParamsPadding();
3045             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3046                                             FIOffset, true);
3047 
3048             // Create load nodes to retrieve arguments from the stack.
3049             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3050             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3051                                          MachinePointerInfo::getFixedStack(FI),
3052                                          false, false, false, 0));
3053           }
3054           lastInsIndex = index;
3055         }
3056     }
3057   }
3058 
3059   // varargs
3060   if (isVarArg)
3061     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3062                          CCInfo.getNextStackOffset());
3063 
3064   return Chain;
3065 }
3066 
3067 /// isFloatingPointZero - Return true if this is +0.0.
3068 static bool isFloatingPointZero(SDValue Op) {
3069   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3070     return CFP->getValueAPF().isPosZero();
3071   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3072     // Maybe this has already been legalized into the constant pool?
3073     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3074       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3075       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3076         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3077           return CFP->getValueAPF().isPosZero();
3078     }
3079   }
3080   return false;
3081 }
3082 
3083 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3084 /// the given operands.
3085 SDValue
3086 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3087                              SDValue &ARMcc, SelectionDAG &DAG,
3088                              SDLoc dl) const {
3089   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3090     unsigned C = RHSC->getZExtValue();
3091     if (!isLegalICmpImmediate(C)) {
3092       // Constant does not fit, try adjusting it by one?
3093       switch (CC) {
3094       default: break;
3095       case ISD::SETLT:
3096       case ISD::SETGE:
3097         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3098           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3099           RHS = DAG.getConstant(C-1, MVT::i32);
3100         }
3101         break;
3102       case ISD::SETULT:
3103       case ISD::SETUGE:
3104         if (C != 0 && isLegalICmpImmediate(C-1)) {
3105           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3106           RHS = DAG.getConstant(C-1, MVT::i32);
3107         }
3108         break;
3109       case ISD::SETLE:
3110       case ISD::SETGT:
3111         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3112           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3113           RHS = DAG.getConstant(C+1, MVT::i32);
3114         }
3115         break;
3116       case ISD::SETULE:
3117       case ISD::SETUGT:
3118         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3119           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3120           RHS = DAG.getConstant(C+1, MVT::i32);
3121         }
3122         break;
3123       }
3124     }
3125   }
3126 
3127   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3128   ARMISD::NodeType CompareType;
3129   switch (CondCode) {
3130   default:
3131     CompareType = ARMISD::CMP;
3132     break;
3133   case ARMCC::EQ:
3134   case ARMCC::NE:
3135     // Uses only Z Flag
3136     CompareType = ARMISD::CMPZ;
3137     break;
3138   }
3139   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3140   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3141 }
3142 
3143 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3144 SDValue
3145 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3146                              SDLoc dl) const {
3147   SDValue Cmp;
3148   if (!isFloatingPointZero(RHS))
3149     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3150   else
3151     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3152   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3153 }
3154 
3155 /// duplicateCmp - Glue values can have only one use, so this function
3156 /// duplicates a comparison node.
3157 SDValue
3158 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3159   unsigned Opc = Cmp.getOpcode();
3160   SDLoc DL(Cmp);
3161   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3162     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3163 
3164   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3165   Cmp = Cmp.getOperand(0);
3166   Opc = Cmp.getOpcode();
3167   if (Opc == ARMISD::CMPFP)
3168     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3169   else {
3170     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3171     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3172   }
3173   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3174 }
3175 
3176 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3177   SDValue Cond = Op.getOperand(0);
3178   SDValue SelectTrue = Op.getOperand(1);
3179   SDValue SelectFalse = Op.getOperand(2);
3180   SDLoc dl(Op);
3181 
3182   // Convert:
3183   //
3184   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3185   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3186   //
3187   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3188     const ConstantSDNode *CMOVTrue =
3189       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3190     const ConstantSDNode *CMOVFalse =
3191       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3192 
3193     if (CMOVTrue && CMOVFalse) {
3194       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3195       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3196 
3197       SDValue True;
3198       SDValue False;
3199       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3200         True = SelectTrue;
3201         False = SelectFalse;
3202       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3203         True = SelectFalse;
3204         False = SelectTrue;
3205       }
3206 
3207       if (True.getNode() && False.getNode()) {
3208         EVT VT = Op.getValueType();
3209         SDValue ARMcc = Cond.getOperand(2);
3210         SDValue CCR = Cond.getOperand(3);
3211         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3212         assert(True.getValueType() == VT);
3213         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3214       }
3215     }
3216   }
3217 
3218   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3219   // undefined bits before doing a full-word comparison with zero.
3220   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3221                      DAG.getConstant(1, Cond.getValueType()));
3222 
3223   return DAG.getSelectCC(dl, Cond,
3224                          DAG.getConstant(0, Cond.getValueType()),
3225                          SelectTrue, SelectFalse, ISD::SETNE);
3226 }
3227 
3228 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3229   if (CC == ISD::SETNE)
3230     return ISD::SETEQ;
3231   return ISD::getSetCCInverse(CC, true);
3232 }
3233 
3234 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3235                                  bool &swpCmpOps, bool &swpVselOps) {
3236   // Start by selecting the GE condition code for opcodes that return true for
3237   // 'equality'
3238   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3239       CC == ISD::SETULE)
3240     CondCode = ARMCC::GE;
3241 
3242   // and GT for opcodes that return false for 'equality'.
3243   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3244            CC == ISD::SETULT)
3245     CondCode = ARMCC::GT;
3246 
3247   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3248   // to swap the compare operands.
3249   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3250       CC == ISD::SETULT)
3251     swpCmpOps = true;
3252 
3253   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3254   // If we have an unordered opcode, we need to swap the operands to the VSEL
3255   // instruction (effectively negating the condition).
3256   //
3257   // This also has the effect of swapping which one of 'less' or 'greater'
3258   // returns true, so we also swap the compare operands. It also switches
3259   // whether we return true for 'equality', so we compensate by picking the
3260   // opposite condition code to our original choice.
3261   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3262       CC == ISD::SETUGT) {
3263     swpCmpOps = !swpCmpOps;
3264     swpVselOps = !swpVselOps;
3265     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3266   }
3267 
3268   // 'ordered' is 'anything but unordered', so use the VS condition code and
3269   // swap the VSEL operands.
3270   if (CC == ISD::SETO) {
3271     CondCode = ARMCC::VS;
3272     swpVselOps = true;
3273   }
3274 
3275   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3276   // code and swap the VSEL operands.
3277   if (CC == ISD::SETUNE) {
3278     CondCode = ARMCC::EQ;
3279     swpVselOps = true;
3280   }
3281 }
3282 
3283 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3284   EVT VT = Op.getValueType();
3285   SDValue LHS = Op.getOperand(0);
3286   SDValue RHS = Op.getOperand(1);
3287   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3288   SDValue TrueVal = Op.getOperand(2);
3289   SDValue FalseVal = Op.getOperand(3);
3290   SDLoc dl(Op);
3291 
3292   if (LHS.getValueType() == MVT::i32) {
3293     // Try to generate VSEL on ARMv8.
3294     // The VSEL instruction can't use all the usual ARM condition
3295     // codes: it only has two bits to select the condition code, so it's
3296     // constrained to use only GE, GT, VS and EQ.
3297     //
3298     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3299     // swap the operands of the previous compare instruction (effectively
3300     // inverting the compare condition, swapping 'less' and 'greater') and
3301     // sometimes need to swap the operands to the VSEL (which inverts the
3302     // condition in the sense of firing whenever the previous condition didn't)
3303     if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3304                                       TrueVal.getValueType() == MVT::f64)) {
3305       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3306       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3307           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3308         CC = getInverseCCForVSEL(CC);
3309         std::swap(TrueVal, FalseVal);
3310       }
3311     }
3312 
3313     SDValue ARMcc;
3314     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3315     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3316     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3317                        Cmp);
3318   }
3319 
3320   ARMCC::CondCodes CondCode, CondCode2;
3321   FPCCToARMCC(CC, CondCode, CondCode2);
3322 
3323   // Try to generate VSEL on ARMv8.
3324   if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3325                                     TrueVal.getValueType() == MVT::f64)) {
3326     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3327     // same operands, as follows:
3328     //   c = fcmp [ogt, olt, ugt, ult] a, b
3329     //   select c, a, b
3330     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3331     // handled differently than the original code sequence.
3332     if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3333         RHS == FalseVal) {
3334       if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3335         return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3336       if (CC == ISD::SETOLT || CC == ISD::SETULT)
3337         return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3338     }
3339 
3340     bool swpCmpOps = false;
3341     bool swpVselOps = false;
3342     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3343 
3344     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3345         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3346       if (swpCmpOps)
3347         std::swap(LHS, RHS);
3348       if (swpVselOps)
3349         std::swap(TrueVal, FalseVal);
3350     }
3351   }
3352 
3353   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3354   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3355   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3356   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3357                                ARMcc, CCR, Cmp);
3358   if (CondCode2 != ARMCC::AL) {
3359     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3360     // FIXME: Needs another CMP because flag can have but one use.
3361     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3362     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3363                          Result, TrueVal, ARMcc2, CCR, Cmp2);
3364   }
3365   return Result;
3366 }
3367 
3368 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3369 /// to morph to an integer compare sequence.
3370 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3371                            const ARMSubtarget *Subtarget) {
3372   SDNode *N = Op.getNode();
3373   if (!N->hasOneUse())
3374     // Otherwise it requires moving the value from fp to integer registers.
3375     return false;
3376   if (!N->getNumValues())
3377     return false;
3378   EVT VT = Op.getValueType();
3379   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3380     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3381     // vmrs are very slow, e.g. cortex-a8.
3382     return false;
3383 
3384   if (isFloatingPointZero(Op)) {
3385     SeenZero = true;
3386     return true;
3387   }
3388   return ISD::isNormalLoad(N);
3389 }
3390 
3391 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3392   if (isFloatingPointZero(Op))
3393     return DAG.getConstant(0, MVT::i32);
3394 
3395   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3396     return DAG.getLoad(MVT::i32, SDLoc(Op),
3397                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3398                        Ld->isVolatile(), Ld->isNonTemporal(),
3399                        Ld->isInvariant(), Ld->getAlignment());
3400 
3401   llvm_unreachable("Unknown VFP cmp argument!");
3402 }
3403 
3404 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3405                            SDValue &RetVal1, SDValue &RetVal2) {
3406   if (isFloatingPointZero(Op)) {
3407     RetVal1 = DAG.getConstant(0, MVT::i32);
3408     RetVal2 = DAG.getConstant(0, MVT::i32);
3409     return;
3410   }
3411 
3412   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3413     SDValue Ptr = Ld->getBasePtr();
3414     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3415                           Ld->getChain(), Ptr,
3416                           Ld->getPointerInfo(),
3417                           Ld->isVolatile(), Ld->isNonTemporal(),
3418                           Ld->isInvariant(), Ld->getAlignment());
3419 
3420     EVT PtrType = Ptr.getValueType();
3421     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3422     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3423                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3424     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3425                           Ld->getChain(), NewPtr,
3426                           Ld->getPointerInfo().getWithOffset(4),
3427                           Ld->isVolatile(), Ld->isNonTemporal(),
3428                           Ld->isInvariant(), NewAlign);
3429     return;
3430   }
3431 
3432   llvm_unreachable("Unknown VFP cmp argument!");
3433 }
3434 
3435 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3436 /// f32 and even f64 comparisons to integer ones.
3437 SDValue
3438 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3439   SDValue Chain = Op.getOperand(0);
3440   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3441   SDValue LHS = Op.getOperand(2);
3442   SDValue RHS = Op.getOperand(3);
3443   SDValue Dest = Op.getOperand(4);
3444   SDLoc dl(Op);
3445 
3446   bool LHSSeenZero = false;
3447   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3448   bool RHSSeenZero = false;
3449   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3450   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3451     // If unsafe fp math optimization is enabled and there are no other uses of
3452     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3453     // to an integer comparison.
3454     if (CC == ISD::SETOEQ)
3455       CC = ISD::SETEQ;
3456     else if (CC == ISD::SETUNE)
3457       CC = ISD::SETNE;
3458 
3459     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3460     SDValue ARMcc;
3461     if (LHS.getValueType() == MVT::f32) {
3462       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3463                         bitcastf32Toi32(LHS, DAG), Mask);
3464       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3465                         bitcastf32Toi32(RHS, DAG), Mask);
3466       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3467       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3468       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3469                          Chain, Dest, ARMcc, CCR, Cmp);
3470     }
3471 
3472     SDValue LHS1, LHS2;
3473     SDValue RHS1, RHS2;
3474     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3475     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3476     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3477     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3478     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3479     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3480     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3481     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3482     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3483   }
3484 
3485   return SDValue();
3486 }
3487 
3488 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3489   SDValue Chain = Op.getOperand(0);
3490   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3491   SDValue LHS = Op.getOperand(2);
3492   SDValue RHS = Op.getOperand(3);
3493   SDValue Dest = Op.getOperand(4);
3494   SDLoc dl(Op);
3495 
3496   if (LHS.getValueType() == MVT::i32) {
3497     SDValue ARMcc;
3498     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3499     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3500     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3501                        Chain, Dest, ARMcc, CCR, Cmp);
3502   }
3503 
3504   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3505 
3506   if (getTargetMachine().Options.UnsafeFPMath &&
3507       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3508        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3509     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3510     if (Result.getNode())
3511       return Result;
3512   }
3513 
3514   ARMCC::CondCodes CondCode, CondCode2;
3515   FPCCToARMCC(CC, CondCode, CondCode2);
3516 
3517   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3518   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3519   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3520   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3521   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3522   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3523   if (CondCode2 != ARMCC::AL) {
3524     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3525     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3526     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3527   }
3528   return Res;
3529 }
3530 
3531 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3532   SDValue Chain = Op.getOperand(0);
3533   SDValue Table = Op.getOperand(1);
3534   SDValue Index = Op.getOperand(2);
3535   SDLoc dl(Op);
3536 
3537   EVT PTy = getPointerTy();
3538   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3539   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3540   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3541   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3542   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3543   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3544   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3545   if (Subtarget->isThumb2()) {
3546     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3547     // which does another jump to the destination. This also makes it easier
3548     // to translate it to TBB / TBH later.
3549     // FIXME: This might not work if the function is extremely large.
3550     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3551                        Addr, Op.getOperand(2), JTI, UId);
3552   }
3553   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3554     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3555                        MachinePointerInfo::getJumpTable(),
3556                        false, false, false, 0);
3557     Chain = Addr.getValue(1);
3558     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3559     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3560   } else {
3561     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3562                        MachinePointerInfo::getJumpTable(),
3563                        false, false, false, 0);
3564     Chain = Addr.getValue(1);
3565     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3566   }
3567 }
3568 
3569 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3570   EVT VT = Op.getValueType();
3571   SDLoc dl(Op);
3572 
3573   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3574     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3575       return Op;
3576     return DAG.UnrollVectorOp(Op.getNode());
3577   }
3578 
3579   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3580          "Invalid type for custom lowering!");
3581   if (VT != MVT::v4i16)
3582     return DAG.UnrollVectorOp(Op.getNode());
3583 
3584   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3585   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3586 }
3587 
3588 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3589   EVT VT = Op.getValueType();
3590   if (VT.isVector())
3591     return LowerVectorFP_TO_INT(Op, DAG);
3592 
3593   SDLoc dl(Op);
3594   unsigned Opc;
3595 
3596   switch (Op.getOpcode()) {
3597   default: llvm_unreachable("Invalid opcode!");
3598   case ISD::FP_TO_SINT:
3599     Opc = ARMISD::FTOSI;
3600     break;
3601   case ISD::FP_TO_UINT:
3602     Opc = ARMISD::FTOUI;
3603     break;
3604   }
3605   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3606   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3607 }
3608 
3609 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3610   EVT VT = Op.getValueType();
3611   SDLoc dl(Op);
3612 
3613   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3614     if (VT.getVectorElementType() == MVT::f32)
3615       return Op;
3616     return DAG.UnrollVectorOp(Op.getNode());
3617   }
3618 
3619   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3620          "Invalid type for custom lowering!");
3621   if (VT != MVT::v4f32)
3622     return DAG.UnrollVectorOp(Op.getNode());
3623 
3624   unsigned CastOpc;
3625   unsigned Opc;
3626   switch (Op.getOpcode()) {
3627   default: llvm_unreachable("Invalid opcode!");
3628   case ISD::SINT_TO_FP:
3629     CastOpc = ISD::SIGN_EXTEND;
3630     Opc = ISD::SINT_TO_FP;
3631     break;
3632   case ISD::UINT_TO_FP:
3633     CastOpc = ISD::ZERO_EXTEND;
3634     Opc = ISD::UINT_TO_FP;
3635     break;
3636   }
3637 
3638   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3639   return DAG.getNode(Opc, dl, VT, Op);
3640 }
3641 
3642 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3643   EVT VT = Op.getValueType();
3644   if (VT.isVector())
3645     return LowerVectorINT_TO_FP(Op, DAG);
3646 
3647   SDLoc dl(Op);
3648   unsigned Opc;
3649 
3650   switch (Op.getOpcode()) {
3651   default: llvm_unreachable("Invalid opcode!");
3652   case ISD::SINT_TO_FP:
3653     Opc = ARMISD::SITOF;
3654     break;
3655   case ISD::UINT_TO_FP:
3656     Opc = ARMISD::UITOF;
3657     break;
3658   }
3659 
3660   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3661   return DAG.getNode(Opc, dl, VT, Op);
3662 }
3663 
3664 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3665   // Implement fcopysign with a fabs and a conditional fneg.
3666   SDValue Tmp0 = Op.getOperand(0);
3667   SDValue Tmp1 = Op.getOperand(1);
3668   SDLoc dl(Op);
3669   EVT VT = Op.getValueType();
3670   EVT SrcVT = Tmp1.getValueType();
3671   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3672     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3673   bool UseNEON = !InGPR && Subtarget->hasNEON();
3674 
3675   if (UseNEON) {
3676     // Use VBSL to copy the sign bit.
3677     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3678     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3679                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3680     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3681     if (VT == MVT::f64)
3682       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3683                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3684                          DAG.getConstant(32, MVT::i32));
3685     else /*if (VT == MVT::f32)*/
3686       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3687     if (SrcVT == MVT::f32) {
3688       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3689       if (VT == MVT::f64)
3690         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3691                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3692                            DAG.getConstant(32, MVT::i32));
3693     } else if (VT == MVT::f32)
3694       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3695                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3696                          DAG.getConstant(32, MVT::i32));
3697     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3698     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3699 
3700     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3701                                             MVT::i32);
3702     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3703     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3704                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3705 
3706     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3707                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3708                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3709     if (VT == MVT::f32) {
3710       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3711       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3712                         DAG.getConstant(0, MVT::i32));
3713     } else {
3714       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3715     }
3716 
3717     return Res;
3718   }
3719 
3720   // Bitcast operand 1 to i32.
3721   if (SrcVT == MVT::f64)
3722     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3723                        &Tmp1, 1).getValue(1);
3724   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3725 
3726   // Or in the signbit with integer operations.
3727   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3728   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3729   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3730   if (VT == MVT::f32) {
3731     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3732                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3733     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3734                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3735   }
3736 
3737   // f64: Or the high part with signbit and then combine two parts.
3738   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3739                      &Tmp0, 1);
3740   SDValue Lo = Tmp0.getValue(0);
3741   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3742   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3743   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3744 }
3745 
3746 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3747   MachineFunction &MF = DAG.getMachineFunction();
3748   MachineFrameInfo *MFI = MF.getFrameInfo();
3749   MFI->setReturnAddressIsTaken(true);
3750 
3751   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3752     return SDValue();
3753 
3754   EVT VT = Op.getValueType();
3755   SDLoc dl(Op);
3756   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3757   if (Depth) {
3758     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3759     SDValue Offset = DAG.getConstant(4, MVT::i32);
3760     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3761                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3762                        MachinePointerInfo(), false, false, false, 0);
3763   }
3764 
3765   // Return LR, which contains the return address. Mark it an implicit live-in.
3766   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3767   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3768 }
3769 
3770 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3771   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3772   MFI->setFrameAddressIsTaken(true);
3773 
3774   EVT VT = Op.getValueType();
3775   SDLoc dl(Op);  // FIXME probably not meaningful
3776   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3777   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetMachO())
3778     ? ARM::R7 : ARM::R11;
3779   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3780   while (Depth--)
3781     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3782                             MachinePointerInfo(),
3783                             false, false, false, 0);
3784   return FrameAddr;
3785 }
3786 
3787 /// ExpandBITCAST - If the target supports VFP, this function is called to
3788 /// expand a bit convert where either the source or destination type is i64 to
3789 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3790 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3791 /// vectors), since the legalizer won't know what to do with that.
3792 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3793   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3794   SDLoc dl(N);
3795   SDValue Op = N->getOperand(0);
3796 
3797   // This function is only supposed to be called for i64 types, either as the
3798   // source or destination of the bit convert.
3799   EVT SrcVT = Op.getValueType();
3800   EVT DstVT = N->getValueType(0);
3801   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3802          "ExpandBITCAST called for non-i64 type");
3803 
3804   // Turn i64->f64 into VMOVDRR.
3805   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3806     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3807                              DAG.getConstant(0, MVT::i32));
3808     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3809                              DAG.getConstant(1, MVT::i32));
3810     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3811                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3812   }
3813 
3814   // Turn f64->i64 into VMOVRRD.
3815   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3816     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3817                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3818     // Merge the pieces into a single i64 value.
3819     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3820   }
3821 
3822   return SDValue();
3823 }
3824 
3825 /// getZeroVector - Returns a vector of specified type with all zero elements.
3826 /// Zero vectors are used to represent vector negation and in those cases
3827 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3828 /// not support i64 elements, so sometimes the zero vectors will need to be
3829 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3830 /// zero vector.
3831 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3832   assert(VT.isVector() && "Expected a vector type");
3833   // The canonical modified immediate encoding of a zero vector is....0!
3834   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3835   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3836   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3837   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3838 }
3839 
3840 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3841 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3842 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3843                                                 SelectionDAG &DAG) const {
3844   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3845   EVT VT = Op.getValueType();
3846   unsigned VTBits = VT.getSizeInBits();
3847   SDLoc dl(Op);
3848   SDValue ShOpLo = Op.getOperand(0);
3849   SDValue ShOpHi = Op.getOperand(1);
3850   SDValue ShAmt  = Op.getOperand(2);
3851   SDValue ARMcc;
3852   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3853 
3854   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3855 
3856   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3857                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3858   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3859   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3860                                    DAG.getConstant(VTBits, MVT::i32));
3861   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3862   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3863   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3864 
3865   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3866   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3867                           ARMcc, DAG, dl);
3868   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3869   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3870                            CCR, Cmp);
3871 
3872   SDValue Ops[2] = { Lo, Hi };
3873   return DAG.getMergeValues(Ops, 2, dl);
3874 }
3875 
3876 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3877 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3878 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3879                                                SelectionDAG &DAG) const {
3880   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3881   EVT VT = Op.getValueType();
3882   unsigned VTBits = VT.getSizeInBits();
3883   SDLoc dl(Op);
3884   SDValue ShOpLo = Op.getOperand(0);
3885   SDValue ShOpHi = Op.getOperand(1);
3886   SDValue ShAmt  = Op.getOperand(2);
3887   SDValue ARMcc;
3888 
3889   assert(Op.getOpcode() == ISD::SHL_PARTS);
3890   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3891                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3892   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3893   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3894                                    DAG.getConstant(VTBits, MVT::i32));
3895   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3896   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3897 
3898   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3899   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3900   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3901                           ARMcc, DAG, dl);
3902   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3903   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3904                            CCR, Cmp);
3905 
3906   SDValue Ops[2] = { Lo, Hi };
3907   return DAG.getMergeValues(Ops, 2, dl);
3908 }
3909 
3910 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3911                                             SelectionDAG &DAG) const {
3912   // The rounding mode is in bits 23:22 of the FPSCR.
3913   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3914   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3915   // so that the shift + and get folded into a bitfield extract.
3916   SDLoc dl(Op);
3917   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3918                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3919                                               MVT::i32));
3920   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3921                                   DAG.getConstant(1U << 22, MVT::i32));
3922   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3923                               DAG.getConstant(22, MVT::i32));
3924   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3925                      DAG.getConstant(3, MVT::i32));
3926 }
3927 
3928 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3929                          const ARMSubtarget *ST) {
3930   EVT VT = N->getValueType(0);
3931   SDLoc dl(N);
3932 
3933   if (!ST->hasV6T2Ops())
3934     return SDValue();
3935 
3936   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3937   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3938 }
3939 
3940 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3941 /// for each 16-bit element from operand, repeated.  The basic idea is to
3942 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3943 ///
3944 /// Trace for v4i16:
3945 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
3946 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3947 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3948 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3949 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
3950 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
3951 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3952 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
3953 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3954   EVT VT = N->getValueType(0);
3955   SDLoc DL(N);
3956 
3957   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
3958   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
3959   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
3960   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
3961   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
3962   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
3963 }
3964 
3965 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
3966 /// bit-count for each 16-bit element from the operand.  We need slightly
3967 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
3968 /// 64/128-bit registers.
3969 ///
3970 /// Trace for v4i16:
3971 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
3972 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
3973 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
3974 /// v4i16:Extracted = [k0    k1    k2    k3    ]
3975 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
3976   EVT VT = N->getValueType(0);
3977   SDLoc DL(N);
3978 
3979   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
3980   if (VT.is64BitVector()) {
3981     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
3982     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
3983                        DAG.getIntPtrConstant(0));
3984   } else {
3985     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
3986                                     BitCounts, DAG.getIntPtrConstant(0));
3987     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
3988   }
3989 }
3990 
3991 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
3992 /// bit-count for each 32-bit element from the operand.  The idea here is
3993 /// to split the vector into 16-bit elements, leverage the 16-bit count
3994 /// routine, and then combine the results.
3995 ///
3996 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
3997 /// input    = [v0    v1    ] (vi: 32-bit elements)
3998 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
3999 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4000 /// vrev: N0 = [k1 k0 k3 k2 ]
4001 ///            [k0 k1 k2 k3 ]
4002 ///       N1 =+[k1 k0 k3 k2 ]
4003 ///            [k0 k2 k1 k3 ]
4004 ///       N2 =+[k1 k3 k0 k2 ]
4005 ///            [k0    k2    k1    k3    ]
4006 /// Extended =+[k1    k3    k0    k2    ]
4007 ///            [k0    k2    ]
4008 /// Extracted=+[k1    k3    ]
4009 ///
4010 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4011   EVT VT = N->getValueType(0);
4012   SDLoc DL(N);
4013 
4014   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4015 
4016   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4017   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4018   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4019   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4020   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4021 
4022   if (VT.is64BitVector()) {
4023     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4024     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4025                        DAG.getIntPtrConstant(0));
4026   } else {
4027     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4028                                     DAG.getIntPtrConstant(0));
4029     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4030   }
4031 }
4032 
4033 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4034                           const ARMSubtarget *ST) {
4035   EVT VT = N->getValueType(0);
4036 
4037   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4038   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4039           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4040          "Unexpected type for custom ctpop lowering");
4041 
4042   if (VT.getVectorElementType() == MVT::i32)
4043     return lowerCTPOP32BitElements(N, DAG);
4044   else
4045     return lowerCTPOP16BitElements(N, DAG);
4046 }
4047 
4048 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4049                           const ARMSubtarget *ST) {
4050   EVT VT = N->getValueType(0);
4051   SDLoc dl(N);
4052 
4053   if (!VT.isVector())
4054     return SDValue();
4055 
4056   // Lower vector shifts on NEON to use VSHL.
4057   assert(ST->hasNEON() && "unexpected vector shift");
4058 
4059   // Left shifts translate directly to the vshiftu intrinsic.
4060   if (N->getOpcode() == ISD::SHL)
4061     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4062                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4063                        N->getOperand(0), N->getOperand(1));
4064 
4065   assert((N->getOpcode() == ISD::SRA ||
4066           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4067 
4068   // NEON uses the same intrinsics for both left and right shifts.  For
4069   // right shifts, the shift amounts are negative, so negate the vector of
4070   // shift amounts.
4071   EVT ShiftVT = N->getOperand(1).getValueType();
4072   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4073                                      getZeroVector(ShiftVT, DAG, dl),
4074                                      N->getOperand(1));
4075   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4076                              Intrinsic::arm_neon_vshifts :
4077                              Intrinsic::arm_neon_vshiftu);
4078   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4079                      DAG.getConstant(vshiftInt, MVT::i32),
4080                      N->getOperand(0), NegatedCount);
4081 }
4082 
4083 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4084                                 const ARMSubtarget *ST) {
4085   EVT VT = N->getValueType(0);
4086   SDLoc dl(N);
4087 
4088   // We can get here for a node like i32 = ISD::SHL i32, i64
4089   if (VT != MVT::i64)
4090     return SDValue();
4091 
4092   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4093          "Unknown shift to lower!");
4094 
4095   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4096   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4097       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4098     return SDValue();
4099 
4100   // If we are in thumb mode, we don't have RRX.
4101   if (ST->isThumb1Only()) return SDValue();
4102 
4103   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4104   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4105                            DAG.getConstant(0, MVT::i32));
4106   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4107                            DAG.getConstant(1, MVT::i32));
4108 
4109   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4110   // captures the result into a carry flag.
4111   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4112   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
4113 
4114   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4115   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4116 
4117   // Merge the pieces into a single i64 value.
4118  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4119 }
4120 
4121 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4122   SDValue TmpOp0, TmpOp1;
4123   bool Invert = false;
4124   bool Swap = false;
4125   unsigned Opc = 0;
4126 
4127   SDValue Op0 = Op.getOperand(0);
4128   SDValue Op1 = Op.getOperand(1);
4129   SDValue CC = Op.getOperand(2);
4130   EVT VT = Op.getValueType();
4131   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4132   SDLoc dl(Op);
4133 
4134   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4135     switch (SetCCOpcode) {
4136     default: llvm_unreachable("Illegal FP comparison");
4137     case ISD::SETUNE:
4138     case ISD::SETNE:  Invert = true; // Fallthrough
4139     case ISD::SETOEQ:
4140     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4141     case ISD::SETOLT:
4142     case ISD::SETLT: Swap = true; // Fallthrough
4143     case ISD::SETOGT:
4144     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4145     case ISD::SETOLE:
4146     case ISD::SETLE:  Swap = true; // Fallthrough
4147     case ISD::SETOGE:
4148     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4149     case ISD::SETUGE: Swap = true; // Fallthrough
4150     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4151     case ISD::SETUGT: Swap = true; // Fallthrough
4152     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4153     case ISD::SETUEQ: Invert = true; // Fallthrough
4154     case ISD::SETONE:
4155       // Expand this to (OLT | OGT).
4156       TmpOp0 = Op0;
4157       TmpOp1 = Op1;
4158       Opc = ISD::OR;
4159       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4160       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4161       break;
4162     case ISD::SETUO: Invert = true; // Fallthrough
4163     case ISD::SETO:
4164       // Expand this to (OLT | OGE).
4165       TmpOp0 = Op0;
4166       TmpOp1 = Op1;
4167       Opc = ISD::OR;
4168       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4169       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4170       break;
4171     }
4172   } else {
4173     // Integer comparisons.
4174     switch (SetCCOpcode) {
4175     default: llvm_unreachable("Illegal integer comparison");
4176     case ISD::SETNE:  Invert = true;
4177     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4178     case ISD::SETLT:  Swap = true;
4179     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4180     case ISD::SETLE:  Swap = true;
4181     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4182     case ISD::SETULT: Swap = true;
4183     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4184     case ISD::SETULE: Swap = true;
4185     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4186     }
4187 
4188     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4189     if (Opc == ARMISD::VCEQ) {
4190 
4191       SDValue AndOp;
4192       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4193         AndOp = Op0;
4194       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4195         AndOp = Op1;
4196 
4197       // Ignore bitconvert.
4198       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4199         AndOp = AndOp.getOperand(0);
4200 
4201       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4202         Opc = ARMISD::VTST;
4203         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4204         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4205         Invert = !Invert;
4206       }
4207     }
4208   }
4209 
4210   if (Swap)
4211     std::swap(Op0, Op1);
4212 
4213   // If one of the operands is a constant vector zero, attempt to fold the
4214   // comparison to a specialized compare-against-zero form.
4215   SDValue SingleOp;
4216   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4217     SingleOp = Op0;
4218   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4219     if (Opc == ARMISD::VCGE)
4220       Opc = ARMISD::VCLEZ;
4221     else if (Opc == ARMISD::VCGT)
4222       Opc = ARMISD::VCLTZ;
4223     SingleOp = Op1;
4224   }
4225 
4226   SDValue Result;
4227   if (SingleOp.getNode()) {
4228     switch (Opc) {
4229     case ARMISD::VCEQ:
4230       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4231     case ARMISD::VCGE:
4232       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4233     case ARMISD::VCLEZ:
4234       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4235     case ARMISD::VCGT:
4236       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4237     case ARMISD::VCLTZ:
4238       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4239     default:
4240       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4241     }
4242   } else {
4243      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4244   }
4245 
4246   if (Invert)
4247     Result = DAG.getNOT(dl, Result, VT);
4248 
4249   return Result;
4250 }
4251 
4252 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4253 /// valid vector constant for a NEON instruction with a "modified immediate"
4254 /// operand (e.g., VMOV).  If so, return the encoded value.
4255 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4256                                  unsigned SplatBitSize, SelectionDAG &DAG,
4257                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4258   unsigned OpCmode, Imm;
4259 
4260   // SplatBitSize is set to the smallest size that splats the vector, so a
4261   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4262   // immediate instructions others than VMOV do not support the 8-bit encoding
4263   // of a zero vector, and the default encoding of zero is supposed to be the
4264   // 32-bit version.
4265   if (SplatBits == 0)
4266     SplatBitSize = 32;
4267 
4268   switch (SplatBitSize) {
4269   case 8:
4270     if (type != VMOVModImm)
4271       return SDValue();
4272     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4273     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4274     OpCmode = 0xe;
4275     Imm = SplatBits;
4276     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4277     break;
4278 
4279   case 16:
4280     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4281     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4282     if ((SplatBits & ~0xff) == 0) {
4283       // Value = 0x00nn: Op=x, Cmode=100x.
4284       OpCmode = 0x8;
4285       Imm = SplatBits;
4286       break;
4287     }
4288     if ((SplatBits & ~0xff00) == 0) {
4289       // Value = 0xnn00: Op=x, Cmode=101x.
4290       OpCmode = 0xa;
4291       Imm = SplatBits >> 8;
4292       break;
4293     }
4294     return SDValue();
4295 
4296   case 32:
4297     // NEON's 32-bit VMOV supports splat values where:
4298     // * only one byte is nonzero, or
4299     // * the least significant byte is 0xff and the second byte is nonzero, or
4300     // * the least significant 2 bytes are 0xff and the third is nonzero.
4301     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4302     if ((SplatBits & ~0xff) == 0) {
4303       // Value = 0x000000nn: Op=x, Cmode=000x.
4304       OpCmode = 0;
4305       Imm = SplatBits;
4306       break;
4307     }
4308     if ((SplatBits & ~0xff00) == 0) {
4309       // Value = 0x0000nn00: Op=x, Cmode=001x.
4310       OpCmode = 0x2;
4311       Imm = SplatBits >> 8;
4312       break;
4313     }
4314     if ((SplatBits & ~0xff0000) == 0) {
4315       // Value = 0x00nn0000: Op=x, Cmode=010x.
4316       OpCmode = 0x4;
4317       Imm = SplatBits >> 16;
4318       break;
4319     }
4320     if ((SplatBits & ~0xff000000) == 0) {
4321       // Value = 0xnn000000: Op=x, Cmode=011x.
4322       OpCmode = 0x6;
4323       Imm = SplatBits >> 24;
4324       break;
4325     }
4326 
4327     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4328     if (type == OtherModImm) return SDValue();
4329 
4330     if ((SplatBits & ~0xffff) == 0 &&
4331         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4332       // Value = 0x0000nnff: Op=x, Cmode=1100.
4333       OpCmode = 0xc;
4334       Imm = SplatBits >> 8;
4335       SplatBits |= 0xff;
4336       break;
4337     }
4338 
4339     if ((SplatBits & ~0xffffff) == 0 &&
4340         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4341       // Value = 0x00nnffff: Op=x, Cmode=1101.
4342       OpCmode = 0xd;
4343       Imm = SplatBits >> 16;
4344       SplatBits |= 0xffff;
4345       break;
4346     }
4347 
4348     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4349     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4350     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4351     // and fall through here to test for a valid 64-bit splat.  But, then the
4352     // caller would also need to check and handle the change in size.
4353     return SDValue();
4354 
4355   case 64: {
4356     if (type != VMOVModImm)
4357       return SDValue();
4358     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4359     uint64_t BitMask = 0xff;
4360     uint64_t Val = 0;
4361     unsigned ImmMask = 1;
4362     Imm = 0;
4363     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4364       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4365         Val |= BitMask;
4366         Imm |= ImmMask;
4367       } else if ((SplatBits & BitMask) != 0) {
4368         return SDValue();
4369       }
4370       BitMask <<= 8;
4371       ImmMask <<= 1;
4372     }
4373     // Op=1, Cmode=1110.
4374     OpCmode = 0x1e;
4375     SplatBits = Val;
4376     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4377     break;
4378   }
4379 
4380   default:
4381     llvm_unreachable("unexpected size for isNEONModifiedImm");
4382   }
4383 
4384   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4385   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4386 }
4387 
4388 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4389                                            const ARMSubtarget *ST) const {
4390   if (!ST->hasVFP3())
4391     return SDValue();
4392 
4393   bool IsDouble = Op.getValueType() == MVT::f64;
4394   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4395 
4396   // Try splatting with a VMOV.f32...
4397   APFloat FPVal = CFP->getValueAPF();
4398   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4399 
4400   if (ImmVal != -1) {
4401     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4402       // We have code in place to select a valid ConstantFP already, no need to
4403       // do any mangling.
4404       return Op;
4405     }
4406 
4407     // It's a float and we are trying to use NEON operations where
4408     // possible. Lower it to a splat followed by an extract.
4409     SDLoc DL(Op);
4410     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4411     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4412                                       NewVal);
4413     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4414                        DAG.getConstant(0, MVT::i32));
4415   }
4416 
4417   // The rest of our options are NEON only, make sure that's allowed before
4418   // proceeding..
4419   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4420     return SDValue();
4421 
4422   EVT VMovVT;
4423   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4424 
4425   // It wouldn't really be worth bothering for doubles except for one very
4426   // important value, which does happen to match: 0.0. So make sure we don't do
4427   // anything stupid.
4428   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4429     return SDValue();
4430 
4431   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4432   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4433                                      false, VMOVModImm);
4434   if (NewVal != SDValue()) {
4435     SDLoc DL(Op);
4436     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4437                                       NewVal);
4438     if (IsDouble)
4439       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4440 
4441     // It's a float: cast and extract a vector element.
4442     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4443                                        VecConstant);
4444     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4445                        DAG.getConstant(0, MVT::i32));
4446   }
4447 
4448   // Finally, try a VMVN.i32
4449   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4450                              false, VMVNModImm);
4451   if (NewVal != SDValue()) {
4452     SDLoc DL(Op);
4453     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4454 
4455     if (IsDouble)
4456       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4457 
4458     // It's a float: cast and extract a vector element.
4459     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4460                                        VecConstant);
4461     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4462                        DAG.getConstant(0, MVT::i32));
4463   }
4464 
4465   return SDValue();
4466 }
4467 
4468 // check if an VEXT instruction can handle the shuffle mask when the
4469 // vector sources of the shuffle are the same.
4470 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4471   unsigned NumElts = VT.getVectorNumElements();
4472 
4473   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4474   if (M[0] < 0)
4475     return false;
4476 
4477   Imm = M[0];
4478 
4479   // If this is a VEXT shuffle, the immediate value is the index of the first
4480   // element.  The other shuffle indices must be the successive elements after
4481   // the first one.
4482   unsigned ExpectedElt = Imm;
4483   for (unsigned i = 1; i < NumElts; ++i) {
4484     // Increment the expected index.  If it wraps around, just follow it
4485     // back to index zero and keep going.
4486     ++ExpectedElt;
4487     if (ExpectedElt == NumElts)
4488       ExpectedElt = 0;
4489 
4490     if (M[i] < 0) continue; // ignore UNDEF indices
4491     if (ExpectedElt != static_cast<unsigned>(M[i]))
4492       return false;
4493   }
4494 
4495   return true;
4496 }
4497 
4498 
4499 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4500                        bool &ReverseVEXT, unsigned &Imm) {
4501   unsigned NumElts = VT.getVectorNumElements();
4502   ReverseVEXT = false;
4503 
4504   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4505   if (M[0] < 0)
4506     return false;
4507 
4508   Imm = M[0];
4509 
4510   // If this is a VEXT shuffle, the immediate value is the index of the first
4511   // element.  The other shuffle indices must be the successive elements after
4512   // the first one.
4513   unsigned ExpectedElt = Imm;
4514   for (unsigned i = 1; i < NumElts; ++i) {
4515     // Increment the expected index.  If it wraps around, it may still be
4516     // a VEXT but the source vectors must be swapped.
4517     ExpectedElt += 1;
4518     if (ExpectedElt == NumElts * 2) {
4519       ExpectedElt = 0;
4520       ReverseVEXT = true;
4521     }
4522 
4523     if (M[i] < 0) continue; // ignore UNDEF indices
4524     if (ExpectedElt != static_cast<unsigned>(M[i]))
4525       return false;
4526   }
4527 
4528   // Adjust the index value if the source operands will be swapped.
4529   if (ReverseVEXT)
4530     Imm -= NumElts;
4531 
4532   return true;
4533 }
4534 
4535 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4536 /// instruction with the specified blocksize.  (The order of the elements
4537 /// within each block of the vector is reversed.)
4538 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4539   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4540          "Only possible block sizes for VREV are: 16, 32, 64");
4541 
4542   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4543   if (EltSz == 64)
4544     return false;
4545 
4546   unsigned NumElts = VT.getVectorNumElements();
4547   unsigned BlockElts = M[0] + 1;
4548   // If the first shuffle index is UNDEF, be optimistic.
4549   if (M[0] < 0)
4550     BlockElts = BlockSize / EltSz;
4551 
4552   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4553     return false;
4554 
4555   for (unsigned i = 0; i < NumElts; ++i) {
4556     if (M[i] < 0) continue; // ignore UNDEF indices
4557     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4558       return false;
4559   }
4560 
4561   return true;
4562 }
4563 
4564 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4565   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4566   // range, then 0 is placed into the resulting vector. So pretty much any mask
4567   // of 8 elements can work here.
4568   return VT == MVT::v8i8 && M.size() == 8;
4569 }
4570 
4571 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4572   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4573   if (EltSz == 64)
4574     return false;
4575 
4576   unsigned NumElts = VT.getVectorNumElements();
4577   WhichResult = (M[0] == 0 ? 0 : 1);
4578   for (unsigned i = 0; i < NumElts; i += 2) {
4579     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4580         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4581       return false;
4582   }
4583   return true;
4584 }
4585 
4586 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4587 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4588 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4589 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4590   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4591   if (EltSz == 64)
4592     return false;
4593 
4594   unsigned NumElts = VT.getVectorNumElements();
4595   WhichResult = (M[0] == 0 ? 0 : 1);
4596   for (unsigned i = 0; i < NumElts; i += 2) {
4597     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4598         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4599       return false;
4600   }
4601   return true;
4602 }
4603 
4604 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4605   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4606   if (EltSz == 64)
4607     return false;
4608 
4609   unsigned NumElts = VT.getVectorNumElements();
4610   WhichResult = (M[0] == 0 ? 0 : 1);
4611   for (unsigned i = 0; i != NumElts; ++i) {
4612     if (M[i] < 0) continue; // ignore UNDEF indices
4613     if ((unsigned) M[i] != 2 * i + WhichResult)
4614       return false;
4615   }
4616 
4617   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4618   if (VT.is64BitVector() && EltSz == 32)
4619     return false;
4620 
4621   return true;
4622 }
4623 
4624 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4625 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4626 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4627 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4628   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4629   if (EltSz == 64)
4630     return false;
4631 
4632   unsigned Half = VT.getVectorNumElements() / 2;
4633   WhichResult = (M[0] == 0 ? 0 : 1);
4634   for (unsigned j = 0; j != 2; ++j) {
4635     unsigned Idx = WhichResult;
4636     for (unsigned i = 0; i != Half; ++i) {
4637       int MIdx = M[i + j * Half];
4638       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4639         return false;
4640       Idx += 2;
4641     }
4642   }
4643 
4644   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4645   if (VT.is64BitVector() && EltSz == 32)
4646     return false;
4647 
4648   return true;
4649 }
4650 
4651 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4652   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4653   if (EltSz == 64)
4654     return false;
4655 
4656   unsigned NumElts = VT.getVectorNumElements();
4657   WhichResult = (M[0] == 0 ? 0 : 1);
4658   unsigned Idx = WhichResult * NumElts / 2;
4659   for (unsigned i = 0; i != NumElts; i += 2) {
4660     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4661         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4662       return false;
4663     Idx += 1;
4664   }
4665 
4666   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4667   if (VT.is64BitVector() && EltSz == 32)
4668     return false;
4669 
4670   return true;
4671 }
4672 
4673 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4674 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4675 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4676 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4677   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4678   if (EltSz == 64)
4679     return false;
4680 
4681   unsigned NumElts = VT.getVectorNumElements();
4682   WhichResult = (M[0] == 0 ? 0 : 1);
4683   unsigned Idx = WhichResult * NumElts / 2;
4684   for (unsigned i = 0; i != NumElts; i += 2) {
4685     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4686         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4687       return false;
4688     Idx += 1;
4689   }
4690 
4691   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4692   if (VT.is64BitVector() && EltSz == 32)
4693     return false;
4694 
4695   return true;
4696 }
4697 
4698 /// \return true if this is a reverse operation on an vector.
4699 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4700   unsigned NumElts = VT.getVectorNumElements();
4701   // Make sure the mask has the right size.
4702   if (NumElts != M.size())
4703       return false;
4704 
4705   // Look for <15, ..., 3, -1, 1, 0>.
4706   for (unsigned i = 0; i != NumElts; ++i)
4707     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4708       return false;
4709 
4710   return true;
4711 }
4712 
4713 // If N is an integer constant that can be moved into a register in one
4714 // instruction, return an SDValue of such a constant (will become a MOV
4715 // instruction).  Otherwise return null.
4716 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4717                                      const ARMSubtarget *ST, SDLoc dl) {
4718   uint64_t Val;
4719   if (!isa<ConstantSDNode>(N))
4720     return SDValue();
4721   Val = cast<ConstantSDNode>(N)->getZExtValue();
4722 
4723   if (ST->isThumb1Only()) {
4724     if (Val <= 255 || ~Val <= 255)
4725       return DAG.getConstant(Val, MVT::i32);
4726   } else {
4727     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4728       return DAG.getConstant(Val, MVT::i32);
4729   }
4730   return SDValue();
4731 }
4732 
4733 // If this is a case we can't handle, return null and let the default
4734 // expansion code take care of it.
4735 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4736                                              const ARMSubtarget *ST) const {
4737   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4738   SDLoc dl(Op);
4739   EVT VT = Op.getValueType();
4740 
4741   APInt SplatBits, SplatUndef;
4742   unsigned SplatBitSize;
4743   bool HasAnyUndefs;
4744   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4745     if (SplatBitSize <= 64) {
4746       // Check if an immediate VMOV works.
4747       EVT VmovVT;
4748       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4749                                       SplatUndef.getZExtValue(), SplatBitSize,
4750                                       DAG, VmovVT, VT.is128BitVector(),
4751                                       VMOVModImm);
4752       if (Val.getNode()) {
4753         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4754         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4755       }
4756 
4757       // Try an immediate VMVN.
4758       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4759       Val = isNEONModifiedImm(NegatedImm,
4760                                       SplatUndef.getZExtValue(), SplatBitSize,
4761                                       DAG, VmovVT, VT.is128BitVector(),
4762                                       VMVNModImm);
4763       if (Val.getNode()) {
4764         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4765         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4766       }
4767 
4768       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4769       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4770         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4771         if (ImmVal != -1) {
4772           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4773           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4774         }
4775       }
4776     }
4777   }
4778 
4779   // Scan through the operands to see if only one value is used.
4780   //
4781   // As an optimisation, even if more than one value is used it may be more
4782   // profitable to splat with one value then change some lanes.
4783   //
4784   // Heuristically we decide to do this if the vector has a "dominant" value,
4785   // defined as splatted to more than half of the lanes.
4786   unsigned NumElts = VT.getVectorNumElements();
4787   bool isOnlyLowElement = true;
4788   bool usesOnlyOneValue = true;
4789   bool hasDominantValue = false;
4790   bool isConstant = true;
4791 
4792   // Map of the number of times a particular SDValue appears in the
4793   // element list.
4794   DenseMap<SDValue, unsigned> ValueCounts;
4795   SDValue Value;
4796   for (unsigned i = 0; i < NumElts; ++i) {
4797     SDValue V = Op.getOperand(i);
4798     if (V.getOpcode() == ISD::UNDEF)
4799       continue;
4800     if (i > 0)
4801       isOnlyLowElement = false;
4802     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4803       isConstant = false;
4804 
4805     ValueCounts.insert(std::make_pair(V, 0));
4806     unsigned &Count = ValueCounts[V];
4807 
4808     // Is this value dominant? (takes up more than half of the lanes)
4809     if (++Count > (NumElts / 2)) {
4810       hasDominantValue = true;
4811       Value = V;
4812     }
4813   }
4814   if (ValueCounts.size() != 1)
4815     usesOnlyOneValue = false;
4816   if (!Value.getNode() && ValueCounts.size() > 0)
4817     Value = ValueCounts.begin()->first;
4818 
4819   if (ValueCounts.size() == 0)
4820     return DAG.getUNDEF(VT);
4821 
4822   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
4823   // Keep going if we are hitting this case.
4824   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
4825     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4826 
4827   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4828 
4829   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4830   // i32 and try again.
4831   if (hasDominantValue && EltSize <= 32) {
4832     if (!isConstant) {
4833       SDValue N;
4834 
4835       // If we are VDUPing a value that comes directly from a vector, that will
4836       // cause an unnecessary move to and from a GPR, where instead we could
4837       // just use VDUPLANE. We can only do this if the lane being extracted
4838       // is at a constant index, as the VDUP from lane instructions only have
4839       // constant-index forms.
4840       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4841           isa<ConstantSDNode>(Value->getOperand(1))) {
4842         // We need to create a new undef vector to use for the VDUPLANE if the
4843         // size of the vector from which we get the value is different than the
4844         // size of the vector that we need to create. We will insert the element
4845         // such that the register coalescer will remove unnecessary copies.
4846         if (VT != Value->getOperand(0).getValueType()) {
4847           ConstantSDNode *constIndex;
4848           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4849           assert(constIndex && "The index is not a constant!");
4850           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4851                              VT.getVectorNumElements();
4852           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4853                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4854                         Value, DAG.getConstant(index, MVT::i32)),
4855                            DAG.getConstant(index, MVT::i32));
4856         } else
4857           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4858                         Value->getOperand(0), Value->getOperand(1));
4859       } else
4860         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4861 
4862       if (!usesOnlyOneValue) {
4863         // The dominant value was splatted as 'N', but we now have to insert
4864         // all differing elements.
4865         for (unsigned I = 0; I < NumElts; ++I) {
4866           if (Op.getOperand(I) == Value)
4867             continue;
4868           SmallVector<SDValue, 3> Ops;
4869           Ops.push_back(N);
4870           Ops.push_back(Op.getOperand(I));
4871           Ops.push_back(DAG.getConstant(I, MVT::i32));
4872           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4873         }
4874       }
4875       return N;
4876     }
4877     if (VT.getVectorElementType().isFloatingPoint()) {
4878       SmallVector<SDValue, 8> Ops;
4879       for (unsigned i = 0; i < NumElts; ++i)
4880         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4881                                   Op.getOperand(i)));
4882       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4883       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4884       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4885       if (Val.getNode())
4886         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4887     }
4888     if (usesOnlyOneValue) {
4889       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4890       if (isConstant && Val.getNode())
4891         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4892     }
4893   }
4894 
4895   // If all elements are constants and the case above didn't get hit, fall back
4896   // to the default expansion, which will generate a load from the constant
4897   // pool.
4898   if (isConstant)
4899     return SDValue();
4900 
4901   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4902   if (NumElts >= 4) {
4903     SDValue shuffle = ReconstructShuffle(Op, DAG);
4904     if (shuffle != SDValue())
4905       return shuffle;
4906   }
4907 
4908   // Vectors with 32- or 64-bit elements can be built by directly assigning
4909   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4910   // will be legalized.
4911   if (EltSize >= 32) {
4912     // Do the expansion with floating-point types, since that is what the VFP
4913     // registers are defined to use, and since i64 is not legal.
4914     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4915     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4916     SmallVector<SDValue, 8> Ops;
4917     for (unsigned i = 0; i < NumElts; ++i)
4918       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4919     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4920     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4921   }
4922 
4923   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
4924   // know the default expansion would otherwise fall back on something even
4925   // worse. For a vector with one or two non-undef values, that's
4926   // scalar_to_vector for the elements followed by a shuffle (provided the
4927   // shuffle is valid for the target) and materialization element by element
4928   // on the stack followed by a load for everything else.
4929   if (!isConstant && !usesOnlyOneValue) {
4930     SDValue Vec = DAG.getUNDEF(VT);
4931     for (unsigned i = 0 ; i < NumElts; ++i) {
4932       SDValue V = Op.getOperand(i);
4933       if (V.getOpcode() == ISD::UNDEF)
4934         continue;
4935       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
4936       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
4937     }
4938     return Vec;
4939   }
4940 
4941   return SDValue();
4942 }
4943 
4944 // Gather data to see if the operation can be modelled as a
4945 // shuffle in combination with VEXTs.
4946 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4947                                               SelectionDAG &DAG) const {
4948   SDLoc dl(Op);
4949   EVT VT = Op.getValueType();
4950   unsigned NumElts = VT.getVectorNumElements();
4951 
4952   SmallVector<SDValue, 2> SourceVecs;
4953   SmallVector<unsigned, 2> MinElts;
4954   SmallVector<unsigned, 2> MaxElts;
4955 
4956   for (unsigned i = 0; i < NumElts; ++i) {
4957     SDValue V = Op.getOperand(i);
4958     if (V.getOpcode() == ISD::UNDEF)
4959       continue;
4960     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4961       // A shuffle can only come from building a vector from various
4962       // elements of other vectors.
4963       return SDValue();
4964     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4965                VT.getVectorElementType()) {
4966       // This code doesn't know how to handle shuffles where the vector
4967       // element types do not match (this happens because type legalization
4968       // promotes the return type of EXTRACT_VECTOR_ELT).
4969       // FIXME: It might be appropriate to extend this code to handle
4970       // mismatched types.
4971       return SDValue();
4972     }
4973 
4974     // Record this extraction against the appropriate vector if possible...
4975     SDValue SourceVec = V.getOperand(0);
4976     // If the element number isn't a constant, we can't effectively
4977     // analyze what's going on.
4978     if (!isa<ConstantSDNode>(V.getOperand(1)))
4979       return SDValue();
4980     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4981     bool FoundSource = false;
4982     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4983       if (SourceVecs[j] == SourceVec) {
4984         if (MinElts[j] > EltNo)
4985           MinElts[j] = EltNo;
4986         if (MaxElts[j] < EltNo)
4987           MaxElts[j] = EltNo;
4988         FoundSource = true;
4989         break;
4990       }
4991     }
4992 
4993     // Or record a new source if not...
4994     if (!FoundSource) {
4995       SourceVecs.push_back(SourceVec);
4996       MinElts.push_back(EltNo);
4997       MaxElts.push_back(EltNo);
4998     }
4999   }
5000 
5001   // Currently only do something sane when at most two source vectors
5002   // involved.
5003   if (SourceVecs.size() > 2)
5004     return SDValue();
5005 
5006   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5007   int VEXTOffsets[2] = {0, 0};
5008 
5009   // This loop extracts the usage patterns of the source vectors
5010   // and prepares appropriate SDValues for a shuffle if possible.
5011   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5012     if (SourceVecs[i].getValueType() == VT) {
5013       // No VEXT necessary
5014       ShuffleSrcs[i] = SourceVecs[i];
5015       VEXTOffsets[i] = 0;
5016       continue;
5017     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5018       // It probably isn't worth padding out a smaller vector just to
5019       // break it down again in a shuffle.
5020       return SDValue();
5021     }
5022 
5023     // Since only 64-bit and 128-bit vectors are legal on ARM and
5024     // we've eliminated the other cases...
5025     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5026            "unexpected vector sizes in ReconstructShuffle");
5027 
5028     if (MaxElts[i] - MinElts[i] >= NumElts) {
5029       // Span too large for a VEXT to cope
5030       return SDValue();
5031     }
5032 
5033     if (MinElts[i] >= NumElts) {
5034       // The extraction can just take the second half
5035       VEXTOffsets[i] = NumElts;
5036       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5037                                    SourceVecs[i],
5038                                    DAG.getIntPtrConstant(NumElts));
5039     } else if (MaxElts[i] < NumElts) {
5040       // The extraction can just take the first half
5041       VEXTOffsets[i] = 0;
5042       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5043                                    SourceVecs[i],
5044                                    DAG.getIntPtrConstant(0));
5045     } else {
5046       // An actual VEXT is needed
5047       VEXTOffsets[i] = MinElts[i];
5048       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5049                                      SourceVecs[i],
5050                                      DAG.getIntPtrConstant(0));
5051       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5052                                      SourceVecs[i],
5053                                      DAG.getIntPtrConstant(NumElts));
5054       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5055                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5056     }
5057   }
5058 
5059   SmallVector<int, 8> Mask;
5060 
5061   for (unsigned i = 0; i < NumElts; ++i) {
5062     SDValue Entry = Op.getOperand(i);
5063     if (Entry.getOpcode() == ISD::UNDEF) {
5064       Mask.push_back(-1);
5065       continue;
5066     }
5067 
5068     SDValue ExtractVec = Entry.getOperand(0);
5069     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5070                                           .getOperand(1))->getSExtValue();
5071     if (ExtractVec == SourceVecs[0]) {
5072       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5073     } else {
5074       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5075     }
5076   }
5077 
5078   // Final check before we try to produce nonsense...
5079   if (isShuffleMaskLegal(Mask, VT))
5080     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5081                                 &Mask[0]);
5082 
5083   return SDValue();
5084 }
5085 
5086 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5087 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5088 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5089 /// are assumed to be legal.
5090 bool
5091 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5092                                       EVT VT) const {
5093   if (VT.getVectorNumElements() == 4 &&
5094       (VT.is128BitVector() || VT.is64BitVector())) {
5095     unsigned PFIndexes[4];
5096     for (unsigned i = 0; i != 4; ++i) {
5097       if (M[i] < 0)
5098         PFIndexes[i] = 8;
5099       else
5100         PFIndexes[i] = M[i];
5101     }
5102 
5103     // Compute the index in the perfect shuffle table.
5104     unsigned PFTableIndex =
5105       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5106     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5107     unsigned Cost = (PFEntry >> 30);
5108 
5109     if (Cost <= 4)
5110       return true;
5111   }
5112 
5113   bool ReverseVEXT;
5114   unsigned Imm, WhichResult;
5115 
5116   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5117   return (EltSize >= 32 ||
5118           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5119           isVREVMask(M, VT, 64) ||
5120           isVREVMask(M, VT, 32) ||
5121           isVREVMask(M, VT, 16) ||
5122           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5123           isVTBLMask(M, VT) ||
5124           isVTRNMask(M, VT, WhichResult) ||
5125           isVUZPMask(M, VT, WhichResult) ||
5126           isVZIPMask(M, VT, WhichResult) ||
5127           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5128           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5129           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5130           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5131 }
5132 
5133 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5134 /// the specified operations to build the shuffle.
5135 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5136                                       SDValue RHS, SelectionDAG &DAG,
5137                                       SDLoc dl) {
5138   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5139   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5140   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5141 
5142   enum {
5143     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5144     OP_VREV,
5145     OP_VDUP0,
5146     OP_VDUP1,
5147     OP_VDUP2,
5148     OP_VDUP3,
5149     OP_VEXT1,
5150     OP_VEXT2,
5151     OP_VEXT3,
5152     OP_VUZPL, // VUZP, left result
5153     OP_VUZPR, // VUZP, right result
5154     OP_VZIPL, // VZIP, left result
5155     OP_VZIPR, // VZIP, right result
5156     OP_VTRNL, // VTRN, left result
5157     OP_VTRNR  // VTRN, right result
5158   };
5159 
5160   if (OpNum == OP_COPY) {
5161     if (LHSID == (1*9+2)*9+3) return LHS;
5162     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5163     return RHS;
5164   }
5165 
5166   SDValue OpLHS, OpRHS;
5167   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5168   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5169   EVT VT = OpLHS.getValueType();
5170 
5171   switch (OpNum) {
5172   default: llvm_unreachable("Unknown shuffle opcode!");
5173   case OP_VREV:
5174     // VREV divides the vector in half and swaps within the half.
5175     if (VT.getVectorElementType() == MVT::i32 ||
5176         VT.getVectorElementType() == MVT::f32)
5177       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5178     // vrev <4 x i16> -> VREV32
5179     if (VT.getVectorElementType() == MVT::i16)
5180       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5181     // vrev <4 x i8> -> VREV16
5182     assert(VT.getVectorElementType() == MVT::i8);
5183     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5184   case OP_VDUP0:
5185   case OP_VDUP1:
5186   case OP_VDUP2:
5187   case OP_VDUP3:
5188     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5189                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5190   case OP_VEXT1:
5191   case OP_VEXT2:
5192   case OP_VEXT3:
5193     return DAG.getNode(ARMISD::VEXT, dl, VT,
5194                        OpLHS, OpRHS,
5195                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5196   case OP_VUZPL:
5197   case OP_VUZPR:
5198     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5199                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5200   case OP_VZIPL:
5201   case OP_VZIPR:
5202     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5203                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5204   case OP_VTRNL:
5205   case OP_VTRNR:
5206     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5207                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5208   }
5209 }
5210 
5211 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5212                                        ArrayRef<int> ShuffleMask,
5213                                        SelectionDAG &DAG) {
5214   // Check to see if we can use the VTBL instruction.
5215   SDValue V1 = Op.getOperand(0);
5216   SDValue V2 = Op.getOperand(1);
5217   SDLoc DL(Op);
5218 
5219   SmallVector<SDValue, 8> VTBLMask;
5220   for (ArrayRef<int>::iterator
5221          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5222     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5223 
5224   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5225     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5226                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5227                                    &VTBLMask[0], 8));
5228 
5229   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5230                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5231                                  &VTBLMask[0], 8));
5232 }
5233 
5234 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5235                                                       SelectionDAG &DAG) {
5236   SDLoc DL(Op);
5237   SDValue OpLHS = Op.getOperand(0);
5238   EVT VT = OpLHS.getValueType();
5239 
5240   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5241          "Expect an v8i16/v16i8 type");
5242   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5243   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5244   // extract the first 8 bytes into the top double word and the last 8 bytes
5245   // into the bottom double word. The v8i16 case is similar.
5246   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5247   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5248                      DAG.getConstant(ExtractNum, MVT::i32));
5249 }
5250 
5251 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5252   SDValue V1 = Op.getOperand(0);
5253   SDValue V2 = Op.getOperand(1);
5254   SDLoc dl(Op);
5255   EVT VT = Op.getValueType();
5256   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5257 
5258   // Convert shuffles that are directly supported on NEON to target-specific
5259   // DAG nodes, instead of keeping them as shuffles and matching them again
5260   // during code selection.  This is more efficient and avoids the possibility
5261   // of inconsistencies between legalization and selection.
5262   // FIXME: floating-point vectors should be canonicalized to integer vectors
5263   // of the same time so that they get CSEd properly.
5264   ArrayRef<int> ShuffleMask = SVN->getMask();
5265 
5266   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5267   if (EltSize <= 32) {
5268     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5269       int Lane = SVN->getSplatIndex();
5270       // If this is undef splat, generate it via "just" vdup, if possible.
5271       if (Lane == -1) Lane = 0;
5272 
5273       // Test if V1 is a SCALAR_TO_VECTOR.
5274       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5275         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5276       }
5277       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5278       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5279       // reaches it).
5280       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5281           !isa<ConstantSDNode>(V1.getOperand(0))) {
5282         bool IsScalarToVector = true;
5283         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5284           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5285             IsScalarToVector = false;
5286             break;
5287           }
5288         if (IsScalarToVector)
5289           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5290       }
5291       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5292                          DAG.getConstant(Lane, MVT::i32));
5293     }
5294 
5295     bool ReverseVEXT;
5296     unsigned Imm;
5297     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5298       if (ReverseVEXT)
5299         std::swap(V1, V2);
5300       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5301                          DAG.getConstant(Imm, MVT::i32));
5302     }
5303 
5304     if (isVREVMask(ShuffleMask, VT, 64))
5305       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5306     if (isVREVMask(ShuffleMask, VT, 32))
5307       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5308     if (isVREVMask(ShuffleMask, VT, 16))
5309       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5310 
5311     if (V2->getOpcode() == ISD::UNDEF &&
5312         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5313       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5314                          DAG.getConstant(Imm, MVT::i32));
5315     }
5316 
5317     // Check for Neon shuffles that modify both input vectors in place.
5318     // If both results are used, i.e., if there are two shuffles with the same
5319     // source operands and with masks corresponding to both results of one of
5320     // these operations, DAG memoization will ensure that a single node is
5321     // used for both shuffles.
5322     unsigned WhichResult;
5323     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5324       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5325                          V1, V2).getValue(WhichResult);
5326     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5327       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5328                          V1, V2).getValue(WhichResult);
5329     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5330       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5331                          V1, V2).getValue(WhichResult);
5332 
5333     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5334       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5335                          V1, V1).getValue(WhichResult);
5336     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5337       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5338                          V1, V1).getValue(WhichResult);
5339     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5340       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5341                          V1, V1).getValue(WhichResult);
5342   }
5343 
5344   // If the shuffle is not directly supported and it has 4 elements, use
5345   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5346   unsigned NumElts = VT.getVectorNumElements();
5347   if (NumElts == 4) {
5348     unsigned PFIndexes[4];
5349     for (unsigned i = 0; i != 4; ++i) {
5350       if (ShuffleMask[i] < 0)
5351         PFIndexes[i] = 8;
5352       else
5353         PFIndexes[i] = ShuffleMask[i];
5354     }
5355 
5356     // Compute the index in the perfect shuffle table.
5357     unsigned PFTableIndex =
5358       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5359     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5360     unsigned Cost = (PFEntry >> 30);
5361 
5362     if (Cost <= 4)
5363       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5364   }
5365 
5366   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5367   if (EltSize >= 32) {
5368     // Do the expansion with floating-point types, since that is what the VFP
5369     // registers are defined to use, and since i64 is not legal.
5370     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5371     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5372     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5373     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5374     SmallVector<SDValue, 8> Ops;
5375     for (unsigned i = 0; i < NumElts; ++i) {
5376       if (ShuffleMask[i] < 0)
5377         Ops.push_back(DAG.getUNDEF(EltVT));
5378       else
5379         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5380                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5381                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5382                                                   MVT::i32)));
5383     }
5384     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5385     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5386   }
5387 
5388   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5389     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5390 
5391   if (VT == MVT::v8i8) {
5392     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5393     if (NewOp.getNode())
5394       return NewOp;
5395   }
5396 
5397   return SDValue();
5398 }
5399 
5400 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5401   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5402   SDValue Lane = Op.getOperand(2);
5403   if (!isa<ConstantSDNode>(Lane))
5404     return SDValue();
5405 
5406   return Op;
5407 }
5408 
5409 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5410   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5411   SDValue Lane = Op.getOperand(1);
5412   if (!isa<ConstantSDNode>(Lane))
5413     return SDValue();
5414 
5415   SDValue Vec = Op.getOperand(0);
5416   if (Op.getValueType() == MVT::i32 &&
5417       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5418     SDLoc dl(Op);
5419     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5420   }
5421 
5422   return Op;
5423 }
5424 
5425 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5426   // The only time a CONCAT_VECTORS operation can have legal types is when
5427   // two 64-bit vectors are concatenated to a 128-bit vector.
5428   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5429          "unexpected CONCAT_VECTORS");
5430   SDLoc dl(Op);
5431   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5432   SDValue Op0 = Op.getOperand(0);
5433   SDValue Op1 = Op.getOperand(1);
5434   if (Op0.getOpcode() != ISD::UNDEF)
5435     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5436                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5437                       DAG.getIntPtrConstant(0));
5438   if (Op1.getOpcode() != ISD::UNDEF)
5439     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5440                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5441                       DAG.getIntPtrConstant(1));
5442   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5443 }
5444 
5445 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5446 /// element has been zero/sign-extended, depending on the isSigned parameter,
5447 /// from an integer type half its size.
5448 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5449                                    bool isSigned) {
5450   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5451   EVT VT = N->getValueType(0);
5452   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5453     SDNode *BVN = N->getOperand(0).getNode();
5454     if (BVN->getValueType(0) != MVT::v4i32 ||
5455         BVN->getOpcode() != ISD::BUILD_VECTOR)
5456       return false;
5457     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5458     unsigned HiElt = 1 - LoElt;
5459     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5460     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5461     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5462     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5463     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5464       return false;
5465     if (isSigned) {
5466       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5467           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5468         return true;
5469     } else {
5470       if (Hi0->isNullValue() && Hi1->isNullValue())
5471         return true;
5472     }
5473     return false;
5474   }
5475 
5476   if (N->getOpcode() != ISD::BUILD_VECTOR)
5477     return false;
5478 
5479   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5480     SDNode *Elt = N->getOperand(i).getNode();
5481     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5482       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5483       unsigned HalfSize = EltSize / 2;
5484       if (isSigned) {
5485         if (!isIntN(HalfSize, C->getSExtValue()))
5486           return false;
5487       } else {
5488         if (!isUIntN(HalfSize, C->getZExtValue()))
5489           return false;
5490       }
5491       continue;
5492     }
5493     return false;
5494   }
5495 
5496   return true;
5497 }
5498 
5499 /// isSignExtended - Check if a node is a vector value that is sign-extended
5500 /// or a constant BUILD_VECTOR with sign-extended elements.
5501 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5502   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5503     return true;
5504   if (isExtendedBUILD_VECTOR(N, DAG, true))
5505     return true;
5506   return false;
5507 }
5508 
5509 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5510 /// or a constant BUILD_VECTOR with zero-extended elements.
5511 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5512   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5513     return true;
5514   if (isExtendedBUILD_VECTOR(N, DAG, false))
5515     return true;
5516   return false;
5517 }
5518 
5519 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5520   if (OrigVT.getSizeInBits() >= 64)
5521     return OrigVT;
5522 
5523   assert(OrigVT.isSimple() && "Expecting a simple value type");
5524 
5525   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5526   switch (OrigSimpleTy) {
5527   default: llvm_unreachable("Unexpected Vector Type");
5528   case MVT::v2i8:
5529   case MVT::v2i16:
5530      return MVT::v2i32;
5531   case MVT::v4i8:
5532     return  MVT::v4i16;
5533   }
5534 }
5535 
5536 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5537 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5538 /// We insert the required extension here to get the vector to fill a D register.
5539 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5540                                             const EVT &OrigTy,
5541                                             const EVT &ExtTy,
5542                                             unsigned ExtOpcode) {
5543   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5544   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5545   // 64-bits we need to insert a new extension so that it will be 64-bits.
5546   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5547   if (OrigTy.getSizeInBits() >= 64)
5548     return N;
5549 
5550   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5551   EVT NewVT = getExtensionTo64Bits(OrigTy);
5552 
5553   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5554 }
5555 
5556 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5557 /// does not do any sign/zero extension. If the original vector is less
5558 /// than 64 bits, an appropriate extension will be added after the load to
5559 /// reach a total size of 64 bits. We have to add the extension separately
5560 /// because ARM does not have a sign/zero extending load for vectors.
5561 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5562   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5563 
5564   // The load already has the right type.
5565   if (ExtendedTy == LD->getMemoryVT())
5566     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5567                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5568                 LD->isNonTemporal(), LD->isInvariant(),
5569                 LD->getAlignment());
5570 
5571   // We need to create a zextload/sextload. We cannot just create a load
5572   // followed by a zext/zext node because LowerMUL is also run during normal
5573   // operation legalization where we can't create illegal types.
5574   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5575                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5576                         LD->getMemoryVT(), LD->isVolatile(),
5577                         LD->isNonTemporal(), LD->getAlignment());
5578 }
5579 
5580 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5581 /// extending load, or BUILD_VECTOR with extended elements, return the
5582 /// unextended value. The unextended vector should be 64 bits so that it can
5583 /// be used as an operand to a VMULL instruction. If the original vector size
5584 /// before extension is less than 64 bits we add a an extension to resize
5585 /// the vector to 64 bits.
5586 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5587   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5588     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5589                                         N->getOperand(0)->getValueType(0),
5590                                         N->getValueType(0),
5591                                         N->getOpcode());
5592 
5593   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5594     return SkipLoadExtensionForVMULL(LD, DAG);
5595 
5596   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5597   // have been legalized as a BITCAST from v4i32.
5598   if (N->getOpcode() == ISD::BITCAST) {
5599     SDNode *BVN = N->getOperand(0).getNode();
5600     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5601            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5602     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5603     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5604                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5605   }
5606   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5607   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5608   EVT VT = N->getValueType(0);
5609   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5610   unsigned NumElts = VT.getVectorNumElements();
5611   MVT TruncVT = MVT::getIntegerVT(EltSize);
5612   SmallVector<SDValue, 8> Ops;
5613   for (unsigned i = 0; i != NumElts; ++i) {
5614     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5615     const APInt &CInt = C->getAPIntValue();
5616     // Element types smaller than 32 bits are not legal, so use i32 elements.
5617     // The values are implicitly truncated so sext vs. zext doesn't matter.
5618     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5619   }
5620   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5621                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5622 }
5623 
5624 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5625   unsigned Opcode = N->getOpcode();
5626   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5627     SDNode *N0 = N->getOperand(0).getNode();
5628     SDNode *N1 = N->getOperand(1).getNode();
5629     return N0->hasOneUse() && N1->hasOneUse() &&
5630       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5631   }
5632   return false;
5633 }
5634 
5635 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5636   unsigned Opcode = N->getOpcode();
5637   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5638     SDNode *N0 = N->getOperand(0).getNode();
5639     SDNode *N1 = N->getOperand(1).getNode();
5640     return N0->hasOneUse() && N1->hasOneUse() &&
5641       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5642   }
5643   return false;
5644 }
5645 
5646 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5647   // Multiplications are only custom-lowered for 128-bit vectors so that
5648   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5649   EVT VT = Op.getValueType();
5650   assert(VT.is128BitVector() && VT.isInteger() &&
5651          "unexpected type for custom-lowering ISD::MUL");
5652   SDNode *N0 = Op.getOperand(0).getNode();
5653   SDNode *N1 = Op.getOperand(1).getNode();
5654   unsigned NewOpc = 0;
5655   bool isMLA = false;
5656   bool isN0SExt = isSignExtended(N0, DAG);
5657   bool isN1SExt = isSignExtended(N1, DAG);
5658   if (isN0SExt && isN1SExt)
5659     NewOpc = ARMISD::VMULLs;
5660   else {
5661     bool isN0ZExt = isZeroExtended(N0, DAG);
5662     bool isN1ZExt = isZeroExtended(N1, DAG);
5663     if (isN0ZExt && isN1ZExt)
5664       NewOpc = ARMISD::VMULLu;
5665     else if (isN1SExt || isN1ZExt) {
5666       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5667       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5668       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5669         NewOpc = ARMISD::VMULLs;
5670         isMLA = true;
5671       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5672         NewOpc = ARMISD::VMULLu;
5673         isMLA = true;
5674       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5675         std::swap(N0, N1);
5676         NewOpc = ARMISD::VMULLu;
5677         isMLA = true;
5678       }
5679     }
5680 
5681     if (!NewOpc) {
5682       if (VT == MVT::v2i64)
5683         // Fall through to expand this.  It is not legal.
5684         return SDValue();
5685       else
5686         // Other vector multiplications are legal.
5687         return Op;
5688     }
5689   }
5690 
5691   // Legalize to a VMULL instruction.
5692   SDLoc DL(Op);
5693   SDValue Op0;
5694   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5695   if (!isMLA) {
5696     Op0 = SkipExtensionForVMULL(N0, DAG);
5697     assert(Op0.getValueType().is64BitVector() &&
5698            Op1.getValueType().is64BitVector() &&
5699            "unexpected types for extended operands to VMULL");
5700     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5701   }
5702 
5703   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5704   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5705   //   vmull q0, d4, d6
5706   //   vmlal q0, d5, d6
5707   // is faster than
5708   //   vaddl q0, d4, d5
5709   //   vmovl q1, d6
5710   //   vmul  q0, q0, q1
5711   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5712   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5713   EVT Op1VT = Op1.getValueType();
5714   return DAG.getNode(N0->getOpcode(), DL, VT,
5715                      DAG.getNode(NewOpc, DL, VT,
5716                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5717                      DAG.getNode(NewOpc, DL, VT,
5718                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5719 }
5720 
5721 static SDValue
5722 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5723   // Convert to float
5724   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5725   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5726   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5727   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5728   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5729   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5730   // Get reciprocal estimate.
5731   // float4 recip = vrecpeq_f32(yf);
5732   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5733                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5734   // Because char has a smaller range than uchar, we can actually get away
5735   // without any newton steps.  This requires that we use a weird bias
5736   // of 0xb000, however (again, this has been exhaustively tested).
5737   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5738   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5739   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5740   Y = DAG.getConstant(0xb000, MVT::i32);
5741   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5742   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5743   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5744   // Convert back to short.
5745   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5746   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5747   return X;
5748 }
5749 
5750 static SDValue
5751 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5752   SDValue N2;
5753   // Convert to float.
5754   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5755   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5756   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5757   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5758   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5759   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5760 
5761   // Use reciprocal estimate and one refinement step.
5762   // float4 recip = vrecpeq_f32(yf);
5763   // recip *= vrecpsq_f32(yf, recip);
5764   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5765                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5766   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5767                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5768                    N1, N2);
5769   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5770   // Because short has a smaller range than ushort, we can actually get away
5771   // with only a single newton step.  This requires that we use a weird bias
5772   // of 89, however (again, this has been exhaustively tested).
5773   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5774   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5775   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5776   N1 = DAG.getConstant(0x89, MVT::i32);
5777   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5778   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5779   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5780   // Convert back to integer and return.
5781   // return vmovn_s32(vcvt_s32_f32(result));
5782   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5783   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5784   return N0;
5785 }
5786 
5787 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5788   EVT VT = Op.getValueType();
5789   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5790          "unexpected type for custom-lowering ISD::SDIV");
5791 
5792   SDLoc dl(Op);
5793   SDValue N0 = Op.getOperand(0);
5794   SDValue N1 = Op.getOperand(1);
5795   SDValue N2, N3;
5796 
5797   if (VT == MVT::v8i8) {
5798     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5799     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5800 
5801     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5802                      DAG.getIntPtrConstant(4));
5803     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5804                      DAG.getIntPtrConstant(4));
5805     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5806                      DAG.getIntPtrConstant(0));
5807     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5808                      DAG.getIntPtrConstant(0));
5809 
5810     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5811     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5812 
5813     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5814     N0 = LowerCONCAT_VECTORS(N0, DAG);
5815 
5816     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5817     return N0;
5818   }
5819   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5820 }
5821 
5822 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5823   EVT VT = Op.getValueType();
5824   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5825          "unexpected type for custom-lowering ISD::UDIV");
5826 
5827   SDLoc dl(Op);
5828   SDValue N0 = Op.getOperand(0);
5829   SDValue N1 = Op.getOperand(1);
5830   SDValue N2, N3;
5831 
5832   if (VT == MVT::v8i8) {
5833     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5834     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5835 
5836     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5837                      DAG.getIntPtrConstant(4));
5838     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5839                      DAG.getIntPtrConstant(4));
5840     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5841                      DAG.getIntPtrConstant(0));
5842     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5843                      DAG.getIntPtrConstant(0));
5844 
5845     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5846     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5847 
5848     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5849     N0 = LowerCONCAT_VECTORS(N0, DAG);
5850 
5851     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5852                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5853                      N0);
5854     return N0;
5855   }
5856 
5857   // v4i16 sdiv ... Convert to float.
5858   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5859   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5860   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5861   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5862   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5863   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5864 
5865   // Use reciprocal estimate and two refinement steps.
5866   // float4 recip = vrecpeq_f32(yf);
5867   // recip *= vrecpsq_f32(yf, recip);
5868   // recip *= vrecpsq_f32(yf, recip);
5869   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5870                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5871   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5872                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5873                    BN1, N2);
5874   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5875   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5876                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5877                    BN1, N2);
5878   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5879   // Simply multiplying by the reciprocal estimate can leave us a few ulps
5880   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5881   // and that it will never cause us to return an answer too large).
5882   // float4 result = as_float4(as_int4(xf*recip) + 2);
5883   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5884   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5885   N1 = DAG.getConstant(2, MVT::i32);
5886   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5887   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5888   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5889   // Convert back to integer and return.
5890   // return vmovn_u32(vcvt_s32_f32(result));
5891   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5892   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5893   return N0;
5894 }
5895 
5896 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5897   EVT VT = Op.getNode()->getValueType(0);
5898   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5899 
5900   unsigned Opc;
5901   bool ExtraOp = false;
5902   switch (Op.getOpcode()) {
5903   default: llvm_unreachable("Invalid code");
5904   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5905   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5906   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5907   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5908   }
5909 
5910   if (!ExtraOp)
5911     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5912                        Op.getOperand(1));
5913   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5914                      Op.getOperand(1), Op.getOperand(2));
5915 }
5916 
5917 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
5918   assert(Subtarget->isTargetDarwin());
5919 
5920   // For iOS, we want to call an alternative entry point: __sincos_stret,
5921   // return values are passed via sret.
5922   SDLoc dl(Op);
5923   SDValue Arg = Op.getOperand(0);
5924   EVT ArgVT = Arg.getValueType();
5925   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
5926 
5927   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
5928   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5929 
5930   // Pair of floats / doubles used to pass the result.
5931   StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
5932 
5933   // Create stack object for sret.
5934   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
5935   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
5936   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
5937   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
5938 
5939   ArgListTy Args;
5940   ArgListEntry Entry;
5941 
5942   Entry.Node = SRet;
5943   Entry.Ty = RetTy->getPointerTo();
5944   Entry.isSExt = false;
5945   Entry.isZExt = false;
5946   Entry.isSRet = true;
5947   Args.push_back(Entry);
5948 
5949   Entry.Node = Arg;
5950   Entry.Ty = ArgTy;
5951   Entry.isSExt = false;
5952   Entry.isZExt = false;
5953   Args.push_back(Entry);
5954 
5955   const char *LibcallName  = (ArgVT == MVT::f64)
5956   ? "__sincos_stret" : "__sincosf_stret";
5957   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
5958 
5959   TargetLowering::
5960   CallLoweringInfo CLI(DAG.getEntryNode(), Type::getVoidTy(*DAG.getContext()),
5961                        false, false, false, false, 0,
5962                        CallingConv::C, /*isTaillCall=*/false,
5963                        /*doesNotRet=*/false, /*isReturnValueUsed*/false,
5964                        Callee, Args, DAG, dl);
5965   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
5966 
5967   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
5968                                 MachinePointerInfo(), false, false, false, 0);
5969 
5970   // Address of cos field.
5971   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
5972                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
5973   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
5974                                 MachinePointerInfo(), false, false, false, 0);
5975 
5976   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
5977   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
5978                      LoadSin.getValue(0), LoadCos.getValue(0));
5979 }
5980 
5981 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5982   // Monotonic load/store is legal for all targets
5983   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5984     return Op;
5985 
5986   // Acquire/Release load/store is not legal for targets without a
5987   // dmb or equivalent available.
5988   return SDValue();
5989 }
5990 
5991 static void
5992 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5993                     SelectionDAG &DAG) {
5994   SDLoc dl(Node);
5995   assert (Node->getValueType(0) == MVT::i64 &&
5996           "Only know how to expand i64 atomics");
5997   AtomicSDNode *AN = cast<AtomicSDNode>(Node);
5998 
5999   SmallVector<SDValue, 6> Ops;
6000   Ops.push_back(Node->getOperand(0)); // Chain
6001   Ops.push_back(Node->getOperand(1)); // Ptr
6002   for(unsigned i=2; i<Node->getNumOperands(); i++) {
6003     // Low part
6004     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6005                               Node->getOperand(i), DAG.getIntPtrConstant(0)));
6006     // High part
6007     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6008                               Node->getOperand(i), DAG.getIntPtrConstant(1)));
6009   }
6010   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6011   SDValue Result =
6012     DAG.getAtomic(Node->getOpcode(), dl, MVT::i64, Tys, Ops.data(), Ops.size(),
6013                   cast<MemSDNode>(Node)->getMemOperand(), AN->getOrdering(),
6014                   AN->getSynchScope());
6015   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
6016   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6017   Results.push_back(Result.getValue(2));
6018 }
6019 
6020 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6021                                     SmallVectorImpl<SDValue> &Results,
6022                                     SelectionDAG &DAG,
6023                                     const ARMSubtarget *Subtarget) {
6024   SDLoc DL(N);
6025   SDValue Cycles32, OutChain;
6026 
6027   if (Subtarget->hasPerfMon()) {
6028     // Under Power Management extensions, the cycle-count is:
6029     //    mrc p15, #0, <Rt>, c9, c13, #0
6030     SDValue Ops[] = { N->getOperand(0), // Chain
6031                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6032                       DAG.getConstant(15, MVT::i32),
6033                       DAG.getConstant(0, MVT::i32),
6034                       DAG.getConstant(9, MVT::i32),
6035                       DAG.getConstant(13, MVT::i32),
6036                       DAG.getConstant(0, MVT::i32)
6037     };
6038 
6039     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6040                            DAG.getVTList(MVT::i32, MVT::Other), &Ops[0],
6041                            array_lengthof(Ops));
6042     OutChain = Cycles32.getValue(1);
6043   } else {
6044     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6045     // there are older ARM CPUs that have implementation-specific ways of
6046     // obtaining this information (FIXME!).
6047     Cycles32 = DAG.getConstant(0, MVT::i32);
6048     OutChain = DAG.getEntryNode();
6049   }
6050 
6051 
6052   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6053                                  Cycles32, DAG.getConstant(0, MVT::i32));
6054   Results.push_back(Cycles64);
6055   Results.push_back(OutChain);
6056 }
6057 
6058 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6059   switch (Op.getOpcode()) {
6060   default: llvm_unreachable("Don't know how to custom lower this!");
6061   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6062   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6063   case ISD::GlobalAddress:
6064     return Subtarget->isTargetMachO() ? LowerGlobalAddressDarwin(Op, DAG) :
6065       LowerGlobalAddressELF(Op, DAG);
6066   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6067   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6068   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6069   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6070   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6071   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6072   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6073   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6074   case ISD::SINT_TO_FP:
6075   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6076   case ISD::FP_TO_SINT:
6077   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6078   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6079   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6080   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6081   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6082   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6083   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6084   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6085                                                                Subtarget);
6086   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6087   case ISD::SHL:
6088   case ISD::SRL:
6089   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6090   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6091   case ISD::SRL_PARTS:
6092   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6093   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6094   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6095   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6096   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6097   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6098   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6099   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6100   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6101   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6102   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6103   case ISD::MUL:           return LowerMUL(Op, DAG);
6104   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6105   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6106   case ISD::ADDC:
6107   case ISD::ADDE:
6108   case ISD::SUBC:
6109   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6110   case ISD::ATOMIC_LOAD:
6111   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6112   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6113   case ISD::SDIVREM:
6114   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6115   }
6116 }
6117 
6118 /// ReplaceNodeResults - Replace the results of node with an illegal result
6119 /// type with new values built out of custom code.
6120 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6121                                            SmallVectorImpl<SDValue>&Results,
6122                                            SelectionDAG &DAG) const {
6123   SDValue Res;
6124   switch (N->getOpcode()) {
6125   default:
6126     llvm_unreachable("Don't know how to custom expand this!");
6127   case ISD::BITCAST:
6128     Res = ExpandBITCAST(N, DAG);
6129     break;
6130   case ISD::SRL:
6131   case ISD::SRA:
6132     Res = Expand64BitShift(N, DAG, Subtarget);
6133     break;
6134   case ISD::READCYCLECOUNTER:
6135     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6136     return;
6137   case ISD::ATOMIC_STORE:
6138   case ISD::ATOMIC_LOAD:
6139   case ISD::ATOMIC_LOAD_ADD:
6140   case ISD::ATOMIC_LOAD_AND:
6141   case ISD::ATOMIC_LOAD_NAND:
6142   case ISD::ATOMIC_LOAD_OR:
6143   case ISD::ATOMIC_LOAD_SUB:
6144   case ISD::ATOMIC_LOAD_XOR:
6145   case ISD::ATOMIC_SWAP:
6146   case ISD::ATOMIC_CMP_SWAP:
6147   case ISD::ATOMIC_LOAD_MIN:
6148   case ISD::ATOMIC_LOAD_UMIN:
6149   case ISD::ATOMIC_LOAD_MAX:
6150   case ISD::ATOMIC_LOAD_UMAX:
6151     ReplaceATOMIC_OP_64(N, Results, DAG);
6152     return;
6153   }
6154   if (Res.getNode())
6155     Results.push_back(Res);
6156 }
6157 
6158 //===----------------------------------------------------------------------===//
6159 //                           ARM Scheduler Hooks
6160 //===----------------------------------------------------------------------===//
6161 
6162 MachineBasicBlock *
6163 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
6164                                      MachineBasicBlock *BB,
6165                                      unsigned Size) const {
6166   unsigned dest    = MI->getOperand(0).getReg();
6167   unsigned ptr     = MI->getOperand(1).getReg();
6168   unsigned oldval  = MI->getOperand(2).getReg();
6169   unsigned newval  = MI->getOperand(3).getReg();
6170   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6171   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(4).getImm());
6172   DebugLoc dl = MI->getDebugLoc();
6173   bool isThumb2 = Subtarget->isThumb2();
6174 
6175   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6176   unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
6177     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6178     (const TargetRegisterClass*)&ARM::GPRRegClass);
6179 
6180   if (isThumb2) {
6181     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6182     MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
6183     MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
6184   }
6185 
6186   unsigned ldrOpc, strOpc;
6187   getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6188 
6189   MachineFunction *MF = BB->getParent();
6190   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6191   MachineFunction::iterator It = BB;
6192   ++It; // insert the new blocks after the current block
6193 
6194   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6195   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6196   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6197   MF->insert(It, loop1MBB);
6198   MF->insert(It, loop2MBB);
6199   MF->insert(It, exitMBB);
6200 
6201   // Transfer the remainder of BB and its successor edges to exitMBB.
6202   exitMBB->splice(exitMBB->begin(), BB,
6203                   llvm::next(MachineBasicBlock::iterator(MI)),
6204                   BB->end());
6205   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6206 
6207   //  thisMBB:
6208   //   ...
6209   //   fallthrough --> loop1MBB
6210   BB->addSuccessor(loop1MBB);
6211 
6212   // loop1MBB:
6213   //   ldrex dest, [ptr]
6214   //   cmp dest, oldval
6215   //   bne exitMBB
6216   BB = loop1MBB;
6217   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6218   if (ldrOpc == ARM::t2LDREX)
6219     MIB.addImm(0);
6220   AddDefaultPred(MIB);
6221   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6222                  .addReg(dest).addReg(oldval));
6223   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6224     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6225   BB->addSuccessor(loop2MBB);
6226   BB->addSuccessor(exitMBB);
6227 
6228   // loop2MBB:
6229   //   strex scratch, newval, [ptr]
6230   //   cmp scratch, #0
6231   //   bne loop1MBB
6232   BB = loop2MBB;
6233   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
6234   if (strOpc == ARM::t2STREX)
6235     MIB.addImm(0);
6236   AddDefaultPred(MIB);
6237   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6238                  .addReg(scratch).addImm(0));
6239   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6240     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6241   BB->addSuccessor(loop1MBB);
6242   BB->addSuccessor(exitMBB);
6243 
6244   //  exitMBB:
6245   //   ...
6246   BB = exitMBB;
6247 
6248   MI->eraseFromParent();   // The instruction is gone now.
6249 
6250   return BB;
6251 }
6252 
6253 MachineBasicBlock *
6254 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6255                                     unsigned Size, unsigned BinOpcode) const {
6256   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6257   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6258 
6259   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6260   MachineFunction *MF = BB->getParent();
6261   MachineFunction::iterator It = BB;
6262   ++It;
6263 
6264   unsigned dest = MI->getOperand(0).getReg();
6265   unsigned ptr = MI->getOperand(1).getReg();
6266   unsigned incr = MI->getOperand(2).getReg();
6267   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6268   DebugLoc dl = MI->getDebugLoc();
6269   bool isThumb2 = Subtarget->isThumb2();
6270 
6271   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6272   if (isThumb2) {
6273     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6274     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6275     MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6276   }
6277 
6278   unsigned ldrOpc, strOpc;
6279   getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6280 
6281   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6282   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6283   MF->insert(It, loopMBB);
6284   MF->insert(It, exitMBB);
6285 
6286   // Transfer the remainder of BB and its successor edges to exitMBB.
6287   exitMBB->splice(exitMBB->begin(), BB,
6288                   llvm::next(MachineBasicBlock::iterator(MI)),
6289                   BB->end());
6290   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6291 
6292   const TargetRegisterClass *TRC = isThumb2 ?
6293     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6294     (const TargetRegisterClass*)&ARM::GPRRegClass;
6295   unsigned scratch = MRI.createVirtualRegister(TRC);
6296   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
6297 
6298   //  thisMBB:
6299   //   ...
6300   //   fallthrough --> loopMBB
6301   BB->addSuccessor(loopMBB);
6302 
6303   //  loopMBB:
6304   //   ldrex dest, ptr
6305   //   <binop> scratch2, dest, incr
6306   //   strex scratch, scratch2, ptr
6307   //   cmp scratch, #0
6308   //   bne- loopMBB
6309   //   fallthrough --> exitMBB
6310   BB = loopMBB;
6311   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6312   if (ldrOpc == ARM::t2LDREX)
6313     MIB.addImm(0);
6314   AddDefaultPred(MIB);
6315   if (BinOpcode) {
6316     // operand order needs to go the other way for NAND
6317     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
6318       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6319                      addReg(incr).addReg(dest)).addReg(0);
6320     else
6321       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6322                      addReg(dest).addReg(incr)).addReg(0);
6323   }
6324 
6325   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6326   if (strOpc == ARM::t2STREX)
6327     MIB.addImm(0);
6328   AddDefaultPred(MIB);
6329   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6330                  .addReg(scratch).addImm(0));
6331   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6332     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6333 
6334   BB->addSuccessor(loopMBB);
6335   BB->addSuccessor(exitMBB);
6336 
6337   //  exitMBB:
6338   //   ...
6339   BB = exitMBB;
6340 
6341   MI->eraseFromParent();   // The instruction is gone now.
6342 
6343   return BB;
6344 }
6345 
6346 MachineBasicBlock *
6347 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
6348                                           MachineBasicBlock *BB,
6349                                           unsigned Size,
6350                                           bool signExtend,
6351                                           ARMCC::CondCodes Cond) const {
6352   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6353 
6354   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6355   MachineFunction *MF = BB->getParent();
6356   MachineFunction::iterator It = BB;
6357   ++It;
6358 
6359   unsigned dest = MI->getOperand(0).getReg();
6360   unsigned ptr = MI->getOperand(1).getReg();
6361   unsigned incr = MI->getOperand(2).getReg();
6362   unsigned oldval = dest;
6363   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6364   DebugLoc dl = MI->getDebugLoc();
6365   bool isThumb2 = Subtarget->isThumb2();
6366 
6367   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6368   if (isThumb2) {
6369     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6370     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6371     MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6372   }
6373 
6374   unsigned ldrOpc, strOpc, extendOpc;
6375   getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6376   switch (Size) {
6377   default: llvm_unreachable("unsupported size for AtomicBinaryMinMax!");
6378   case 1:
6379     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
6380     break;
6381   case 2:
6382     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
6383     break;
6384   case 4:
6385     extendOpc = 0;
6386     break;
6387   }
6388 
6389   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6390   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6391   MF->insert(It, loopMBB);
6392   MF->insert(It, exitMBB);
6393 
6394   // Transfer the remainder of BB and its successor edges to exitMBB.
6395   exitMBB->splice(exitMBB->begin(), BB,
6396                   llvm::next(MachineBasicBlock::iterator(MI)),
6397                   BB->end());
6398   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6399 
6400   const TargetRegisterClass *TRC = isThumb2 ?
6401     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6402     (const TargetRegisterClass*)&ARM::GPRRegClass;
6403   unsigned scratch = MRI.createVirtualRegister(TRC);
6404   unsigned scratch2 = MRI.createVirtualRegister(TRC);
6405 
6406   //  thisMBB:
6407   //   ...
6408   //   fallthrough --> loopMBB
6409   BB->addSuccessor(loopMBB);
6410 
6411   //  loopMBB:
6412   //   ldrex dest, ptr
6413   //   (sign extend dest, if required)
6414   //   cmp dest, incr
6415   //   cmov.cond scratch2, incr, dest
6416   //   strex scratch, scratch2, ptr
6417   //   cmp scratch, #0
6418   //   bne- loopMBB
6419   //   fallthrough --> exitMBB
6420   BB = loopMBB;
6421   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6422   if (ldrOpc == ARM::t2LDREX)
6423     MIB.addImm(0);
6424   AddDefaultPred(MIB);
6425 
6426   // Sign extend the value, if necessary.
6427   if (signExtend && extendOpc) {
6428     oldval = MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass
6429                                                 : &ARM::GPRnopcRegClass);
6430     if (!isThumb2)
6431       MRI.constrainRegClass(dest, &ARM::GPRnopcRegClass);
6432     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
6433                      .addReg(dest)
6434                      .addImm(0));
6435   }
6436 
6437   // Build compare and cmov instructions.
6438   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6439                  .addReg(oldval).addReg(incr));
6440   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
6441          .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
6442 
6443   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6444   if (strOpc == ARM::t2STREX)
6445     MIB.addImm(0);
6446   AddDefaultPred(MIB);
6447   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6448                  .addReg(scratch).addImm(0));
6449   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6450     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6451 
6452   BB->addSuccessor(loopMBB);
6453   BB->addSuccessor(exitMBB);
6454 
6455   //  exitMBB:
6456   //   ...
6457   BB = exitMBB;
6458 
6459   MI->eraseFromParent();   // The instruction is gone now.
6460 
6461   return BB;
6462 }
6463 
6464 MachineBasicBlock *
6465 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
6466                                       unsigned Op1, unsigned Op2,
6467                                       bool NeedsCarry, bool IsCmpxchg,
6468                                       bool IsMinMax, ARMCC::CondCodes CC) const {
6469   // This also handles ATOMIC_SWAP and ATOMIC_STORE, indicated by Op1==0.
6470   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6471 
6472   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6473   MachineFunction *MF = BB->getParent();
6474   MachineFunction::iterator It = BB;
6475   ++It;
6476 
6477   bool isStore = (MI->getOpcode() == ARM::ATOMIC_STORE_I64);
6478   unsigned offset = (isStore ? -2 : 0);
6479   unsigned destlo = MI->getOperand(0).getReg();
6480   unsigned desthi = MI->getOperand(1).getReg();
6481   unsigned ptr = MI->getOperand(offset+2).getReg();
6482   unsigned vallo = MI->getOperand(offset+3).getReg();
6483   unsigned valhi = MI->getOperand(offset+4).getReg();
6484   unsigned OrdIdx = offset + (IsCmpxchg ? 7 : 5);
6485   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(OrdIdx).getImm());
6486   DebugLoc dl = MI->getDebugLoc();
6487   bool isThumb2 = Subtarget->isThumb2();
6488 
6489   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6490   if (isThumb2) {
6491     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6492     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6493     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6494     MRI.constrainRegClass(vallo, &ARM::rGPRRegClass);
6495     MRI.constrainRegClass(valhi, &ARM::rGPRRegClass);
6496   }
6497 
6498   unsigned ldrOpc, strOpc;
6499   getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6500 
6501   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6502   MachineBasicBlock *contBB = 0, *cont2BB = 0;
6503   if (IsCmpxchg || IsMinMax)
6504     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
6505   if (IsCmpxchg)
6506     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
6507   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6508 
6509   MF->insert(It, loopMBB);
6510   if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6511   if (IsCmpxchg) MF->insert(It, cont2BB);
6512   MF->insert(It, exitMBB);
6513 
6514   // Transfer the remainder of BB and its successor edges to exitMBB.
6515   exitMBB->splice(exitMBB->begin(), BB,
6516                   llvm::next(MachineBasicBlock::iterator(MI)),
6517                   BB->end());
6518   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6519 
6520   const TargetRegisterClass *TRC = isThumb2 ?
6521     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6522     (const TargetRegisterClass*)&ARM::GPRRegClass;
6523   unsigned storesuccess = MRI.createVirtualRegister(TRC);
6524 
6525   //  thisMBB:
6526   //   ...
6527   //   fallthrough --> loopMBB
6528   BB->addSuccessor(loopMBB);
6529 
6530   //  loopMBB:
6531   //   ldrexd r2, r3, ptr
6532   //   <binopa> r0, r2, incr
6533   //   <binopb> r1, r3, incr
6534   //   strexd storesuccess, r0, r1, ptr
6535   //   cmp storesuccess, #0
6536   //   bne- loopMBB
6537   //   fallthrough --> exitMBB
6538   BB = loopMBB;
6539 
6540   if (!isStore) {
6541     // Load
6542     if (isThumb2) {
6543       AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6544                      .addReg(destlo, RegState::Define)
6545                      .addReg(desthi, RegState::Define)
6546                      .addReg(ptr));
6547     } else {
6548       unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6549       AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6550                      .addReg(GPRPair0, RegState::Define).addReg(ptr));
6551       // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
6552       BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6553         .addReg(GPRPair0, 0, ARM::gsub_0);
6554       BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6555         .addReg(GPRPair0, 0, ARM::gsub_1);
6556     }
6557   }
6558 
6559   unsigned StoreLo, StoreHi;
6560   if (IsCmpxchg) {
6561     // Add early exit
6562     for (unsigned i = 0; i < 2; i++) {
6563       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6564                                                          ARM::CMPrr))
6565                      .addReg(i == 0 ? destlo : desthi)
6566                      .addReg(i == 0 ? vallo : valhi));
6567       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6568         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6569       BB->addSuccessor(exitMBB);
6570       BB->addSuccessor(i == 0 ? contBB : cont2BB);
6571       BB = (i == 0 ? contBB : cont2BB);
6572     }
6573 
6574     // Copy to physregs for strexd
6575     StoreLo = MI->getOperand(5).getReg();
6576     StoreHi = MI->getOperand(6).getReg();
6577   } else if (Op1) {
6578     // Perform binary operation
6579     unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6580     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6581                    .addReg(destlo).addReg(vallo))
6582         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6583     unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6584     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6585                    .addReg(desthi).addReg(valhi))
6586         .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6587 
6588     StoreLo = tmpRegLo;
6589     StoreHi = tmpRegHi;
6590   } else {
6591     // Copy to physregs for strexd
6592     StoreLo = vallo;
6593     StoreHi = valhi;
6594   }
6595   if (IsMinMax) {
6596     // Compare and branch to exit block.
6597     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6598       .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6599     BB->addSuccessor(exitMBB);
6600     BB->addSuccessor(contBB);
6601     BB = contBB;
6602     StoreLo = vallo;
6603     StoreHi = valhi;
6604   }
6605 
6606   // Store
6607   if (isThumb2) {
6608     MRI.constrainRegClass(StoreLo, &ARM::rGPRRegClass);
6609     MRI.constrainRegClass(StoreHi, &ARM::rGPRRegClass);
6610     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6611                    .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6612   } else {
6613     // Marshal a pair...
6614     unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6615     unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6616     unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6617     BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6618     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6619       .addReg(UndefPair)
6620       .addReg(StoreLo)
6621       .addImm(ARM::gsub_0);
6622     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6623       .addReg(r1)
6624       .addReg(StoreHi)
6625       .addImm(ARM::gsub_1);
6626 
6627     // ...and store it
6628     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6629                    .addReg(StorePair).addReg(ptr));
6630   }
6631   // Cmp+jump
6632   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6633                  .addReg(storesuccess).addImm(0));
6634   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6635     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6636 
6637   BB->addSuccessor(loopMBB);
6638   BB->addSuccessor(exitMBB);
6639 
6640   //  exitMBB:
6641   //   ...
6642   BB = exitMBB;
6643 
6644   MI->eraseFromParent();   // The instruction is gone now.
6645 
6646   return BB;
6647 }
6648 
6649 MachineBasicBlock *
6650 ARMTargetLowering::EmitAtomicLoad64(MachineInstr *MI, MachineBasicBlock *BB) const {
6651 
6652   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6653 
6654   unsigned destlo = MI->getOperand(0).getReg();
6655   unsigned desthi = MI->getOperand(1).getReg();
6656   unsigned ptr = MI->getOperand(2).getReg();
6657   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6658   DebugLoc dl = MI->getDebugLoc();
6659   bool isThumb2 = Subtarget->isThumb2();
6660 
6661   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6662   if (isThumb2) {
6663     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6664     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6665     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6666   }
6667   unsigned ldrOpc, strOpc;
6668   getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6669 
6670   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(ldrOpc));
6671 
6672   if (isThumb2) {
6673     MIB.addReg(destlo, RegState::Define)
6674        .addReg(desthi, RegState::Define)
6675        .addReg(ptr);
6676 
6677   } else {
6678     unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6679     MIB.addReg(GPRPair0, RegState::Define).addReg(ptr);
6680 
6681     // Copy GPRPair0 into dest.  (This copy will normally be coalesced.)
6682     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), destlo)
6683       .addReg(GPRPair0, 0, ARM::gsub_0);
6684     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), desthi)
6685       .addReg(GPRPair0, 0, ARM::gsub_1);
6686   }
6687   AddDefaultPred(MIB);
6688 
6689   MI->eraseFromParent();   // The instruction is gone now.
6690 
6691   return BB;
6692 }
6693 
6694 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6695 /// registers the function context.
6696 void ARMTargetLowering::
6697 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6698                        MachineBasicBlock *DispatchBB, int FI) const {
6699   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6700   DebugLoc dl = MI->getDebugLoc();
6701   MachineFunction *MF = MBB->getParent();
6702   MachineRegisterInfo *MRI = &MF->getRegInfo();
6703   MachineConstantPool *MCP = MF->getConstantPool();
6704   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6705   const Function *F = MF->getFunction();
6706 
6707   bool isThumb = Subtarget->isThumb();
6708   bool isThumb2 = Subtarget->isThumb2();
6709 
6710   unsigned PCLabelId = AFI->createPICLabelUId();
6711   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6712   ARMConstantPoolValue *CPV =
6713     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6714   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6715 
6716   const TargetRegisterClass *TRC = isThumb ?
6717     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6718     (const TargetRegisterClass*)&ARM::GPRRegClass;
6719 
6720   // Grab constant pool and fixed stack memory operands.
6721   MachineMemOperand *CPMMO =
6722     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6723                              MachineMemOperand::MOLoad, 4, 4);
6724 
6725   MachineMemOperand *FIMMOSt =
6726     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6727                              MachineMemOperand::MOStore, 4, 4);
6728 
6729   // Load the address of the dispatch MBB into the jump buffer.
6730   if (isThumb2) {
6731     // Incoming value: jbuf
6732     //   ldr.n  r5, LCPI1_1
6733     //   orr    r5, r5, #1
6734     //   add    r5, pc
6735     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6736     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6737     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6738                    .addConstantPoolIndex(CPI)
6739                    .addMemOperand(CPMMO));
6740     // Set the low bit because of thumb mode.
6741     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6742     AddDefaultCC(
6743       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6744                      .addReg(NewVReg1, RegState::Kill)
6745                      .addImm(0x01)));
6746     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6747     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6748       .addReg(NewVReg2, RegState::Kill)
6749       .addImm(PCLabelId);
6750     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6751                    .addReg(NewVReg3, RegState::Kill)
6752                    .addFrameIndex(FI)
6753                    .addImm(36)  // &jbuf[1] :: pc
6754                    .addMemOperand(FIMMOSt));
6755   } else if (isThumb) {
6756     // Incoming value: jbuf
6757     //   ldr.n  r1, LCPI1_4
6758     //   add    r1, pc
6759     //   mov    r2, #1
6760     //   orrs   r1, r2
6761     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6762     //   str    r1, [r2]
6763     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6764     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6765                    .addConstantPoolIndex(CPI)
6766                    .addMemOperand(CPMMO));
6767     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6768     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6769       .addReg(NewVReg1, RegState::Kill)
6770       .addImm(PCLabelId);
6771     // Set the low bit because of thumb mode.
6772     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6773     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6774                    .addReg(ARM::CPSR, RegState::Define)
6775                    .addImm(1));
6776     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6777     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6778                    .addReg(ARM::CPSR, RegState::Define)
6779                    .addReg(NewVReg2, RegState::Kill)
6780                    .addReg(NewVReg3, RegState::Kill));
6781     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6782     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6783                    .addFrameIndex(FI)
6784                    .addImm(36)); // &jbuf[1] :: pc
6785     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6786                    .addReg(NewVReg4, RegState::Kill)
6787                    .addReg(NewVReg5, RegState::Kill)
6788                    .addImm(0)
6789                    .addMemOperand(FIMMOSt));
6790   } else {
6791     // Incoming value: jbuf
6792     //   ldr  r1, LCPI1_1
6793     //   add  r1, pc, r1
6794     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6795     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6796     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6797                    .addConstantPoolIndex(CPI)
6798                    .addImm(0)
6799                    .addMemOperand(CPMMO));
6800     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6801     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6802                    .addReg(NewVReg1, RegState::Kill)
6803                    .addImm(PCLabelId));
6804     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6805                    .addReg(NewVReg2, RegState::Kill)
6806                    .addFrameIndex(FI)
6807                    .addImm(36)  // &jbuf[1] :: pc
6808                    .addMemOperand(FIMMOSt));
6809   }
6810 }
6811 
6812 MachineBasicBlock *ARMTargetLowering::
6813 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6814   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6815   DebugLoc dl = MI->getDebugLoc();
6816   MachineFunction *MF = MBB->getParent();
6817   MachineRegisterInfo *MRI = &MF->getRegInfo();
6818   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6819   MachineFrameInfo *MFI = MF->getFrameInfo();
6820   int FI = MFI->getFunctionContextIndex();
6821 
6822   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6823     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6824     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6825 
6826   // Get a mapping of the call site numbers to all of the landing pads they're
6827   // associated with.
6828   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6829   unsigned MaxCSNum = 0;
6830   MachineModuleInfo &MMI = MF->getMMI();
6831   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6832        ++BB) {
6833     if (!BB->isLandingPad()) continue;
6834 
6835     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6836     // pad.
6837     for (MachineBasicBlock::iterator
6838            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6839       if (!II->isEHLabel()) continue;
6840 
6841       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6842       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6843 
6844       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6845       for (SmallVectorImpl<unsigned>::iterator
6846              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6847            CSI != CSE; ++CSI) {
6848         CallSiteNumToLPad[*CSI].push_back(BB);
6849         MaxCSNum = std::max(MaxCSNum, *CSI);
6850       }
6851       break;
6852     }
6853   }
6854 
6855   // Get an ordered list of the machine basic blocks for the jump table.
6856   std::vector<MachineBasicBlock*> LPadList;
6857   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6858   LPadList.reserve(CallSiteNumToLPad.size());
6859   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6860     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6861     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6862            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6863       LPadList.push_back(*II);
6864       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6865     }
6866   }
6867 
6868   assert(!LPadList.empty() &&
6869          "No landing pad destinations for the dispatch jump table!");
6870 
6871   // Create the jump table and associated information.
6872   MachineJumpTableInfo *JTI =
6873     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6874   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6875   unsigned UId = AFI->createJumpTableUId();
6876   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6877 
6878   // Create the MBBs for the dispatch code.
6879 
6880   // Shove the dispatch's address into the return slot in the function context.
6881   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6882   DispatchBB->setIsLandingPad();
6883 
6884   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6885   unsigned trap_opcode;
6886   if (Subtarget->isThumb())
6887     trap_opcode = ARM::tTRAP;
6888   else
6889     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6890 
6891   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6892   DispatchBB->addSuccessor(TrapBB);
6893 
6894   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6895   DispatchBB->addSuccessor(DispContBB);
6896 
6897   // Insert and MBBs.
6898   MF->insert(MF->end(), DispatchBB);
6899   MF->insert(MF->end(), DispContBB);
6900   MF->insert(MF->end(), TrapBB);
6901 
6902   // Insert code into the entry block that creates and registers the function
6903   // context.
6904   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6905 
6906   MachineMemOperand *FIMMOLd =
6907     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6908                              MachineMemOperand::MOLoad |
6909                              MachineMemOperand::MOVolatile, 4, 4);
6910 
6911   MachineInstrBuilder MIB;
6912   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6913 
6914   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6915   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6916 
6917   // Add a register mask with no preserved registers.  This results in all
6918   // registers being marked as clobbered.
6919   MIB.addRegMask(RI.getNoPreservedMask());
6920 
6921   unsigned NumLPads = LPadList.size();
6922   if (Subtarget->isThumb2()) {
6923     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6924     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6925                    .addFrameIndex(FI)
6926                    .addImm(4)
6927                    .addMemOperand(FIMMOLd));
6928 
6929     if (NumLPads < 256) {
6930       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6931                      .addReg(NewVReg1)
6932                      .addImm(LPadList.size()));
6933     } else {
6934       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6935       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6936                      .addImm(NumLPads & 0xFFFF));
6937 
6938       unsigned VReg2 = VReg1;
6939       if ((NumLPads & 0xFFFF0000) != 0) {
6940         VReg2 = MRI->createVirtualRegister(TRC);
6941         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6942                        .addReg(VReg1)
6943                        .addImm(NumLPads >> 16));
6944       }
6945 
6946       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6947                      .addReg(NewVReg1)
6948                      .addReg(VReg2));
6949     }
6950 
6951     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6952       .addMBB(TrapBB)
6953       .addImm(ARMCC::HI)
6954       .addReg(ARM::CPSR);
6955 
6956     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6957     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6958                    .addJumpTableIndex(MJTI)
6959                    .addImm(UId));
6960 
6961     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6962     AddDefaultCC(
6963       AddDefaultPred(
6964         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6965         .addReg(NewVReg3, RegState::Kill)
6966         .addReg(NewVReg1)
6967         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6968 
6969     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6970       .addReg(NewVReg4, RegState::Kill)
6971       .addReg(NewVReg1)
6972       .addJumpTableIndex(MJTI)
6973       .addImm(UId);
6974   } else if (Subtarget->isThumb()) {
6975     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6976     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6977                    .addFrameIndex(FI)
6978                    .addImm(1)
6979                    .addMemOperand(FIMMOLd));
6980 
6981     if (NumLPads < 256) {
6982       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6983                      .addReg(NewVReg1)
6984                      .addImm(NumLPads));
6985     } else {
6986       MachineConstantPool *ConstantPool = MF->getConstantPool();
6987       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6988       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6989 
6990       // MachineConstantPool wants an explicit alignment.
6991       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6992       if (Align == 0)
6993         Align = getDataLayout()->getTypeAllocSize(C->getType());
6994       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6995 
6996       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6997       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6998                      .addReg(VReg1, RegState::Define)
6999                      .addConstantPoolIndex(Idx));
7000       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7001                      .addReg(NewVReg1)
7002                      .addReg(VReg1));
7003     }
7004 
7005     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7006       .addMBB(TrapBB)
7007       .addImm(ARMCC::HI)
7008       .addReg(ARM::CPSR);
7009 
7010     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7011     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7012                    .addReg(ARM::CPSR, RegState::Define)
7013                    .addReg(NewVReg1)
7014                    .addImm(2));
7015 
7016     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7017     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7018                    .addJumpTableIndex(MJTI)
7019                    .addImm(UId));
7020 
7021     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7022     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7023                    .addReg(ARM::CPSR, RegState::Define)
7024                    .addReg(NewVReg2, RegState::Kill)
7025                    .addReg(NewVReg3));
7026 
7027     MachineMemOperand *JTMMOLd =
7028       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7029                                MachineMemOperand::MOLoad, 4, 4);
7030 
7031     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7032     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7033                    .addReg(NewVReg4, RegState::Kill)
7034                    .addImm(0)
7035                    .addMemOperand(JTMMOLd));
7036 
7037     unsigned NewVReg6 = NewVReg5;
7038     if (RelocM == Reloc::PIC_) {
7039       NewVReg6 = MRI->createVirtualRegister(TRC);
7040       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7041                      .addReg(ARM::CPSR, RegState::Define)
7042                      .addReg(NewVReg5, RegState::Kill)
7043                      .addReg(NewVReg3));
7044     }
7045 
7046     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7047       .addReg(NewVReg6, RegState::Kill)
7048       .addJumpTableIndex(MJTI)
7049       .addImm(UId);
7050   } else {
7051     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7052     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7053                    .addFrameIndex(FI)
7054                    .addImm(4)
7055                    .addMemOperand(FIMMOLd));
7056 
7057     if (NumLPads < 256) {
7058       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7059                      .addReg(NewVReg1)
7060                      .addImm(NumLPads));
7061     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7062       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7063       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7064                      .addImm(NumLPads & 0xFFFF));
7065 
7066       unsigned VReg2 = VReg1;
7067       if ((NumLPads & 0xFFFF0000) != 0) {
7068         VReg2 = MRI->createVirtualRegister(TRC);
7069         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7070                        .addReg(VReg1)
7071                        .addImm(NumLPads >> 16));
7072       }
7073 
7074       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7075                      .addReg(NewVReg1)
7076                      .addReg(VReg2));
7077     } else {
7078       MachineConstantPool *ConstantPool = MF->getConstantPool();
7079       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7080       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7081 
7082       // MachineConstantPool wants an explicit alignment.
7083       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7084       if (Align == 0)
7085         Align = getDataLayout()->getTypeAllocSize(C->getType());
7086       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7087 
7088       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7089       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7090                      .addReg(VReg1, RegState::Define)
7091                      .addConstantPoolIndex(Idx)
7092                      .addImm(0));
7093       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7094                      .addReg(NewVReg1)
7095                      .addReg(VReg1, RegState::Kill));
7096     }
7097 
7098     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7099       .addMBB(TrapBB)
7100       .addImm(ARMCC::HI)
7101       .addReg(ARM::CPSR);
7102 
7103     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7104     AddDefaultCC(
7105       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7106                      .addReg(NewVReg1)
7107                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7108     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7109     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7110                    .addJumpTableIndex(MJTI)
7111                    .addImm(UId));
7112 
7113     MachineMemOperand *JTMMOLd =
7114       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7115                                MachineMemOperand::MOLoad, 4, 4);
7116     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7117     AddDefaultPred(
7118       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7119       .addReg(NewVReg3, RegState::Kill)
7120       .addReg(NewVReg4)
7121       .addImm(0)
7122       .addMemOperand(JTMMOLd));
7123 
7124     if (RelocM == Reloc::PIC_) {
7125       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7126         .addReg(NewVReg5, RegState::Kill)
7127         .addReg(NewVReg4)
7128         .addJumpTableIndex(MJTI)
7129         .addImm(UId);
7130     } else {
7131       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7132         .addReg(NewVReg5, RegState::Kill)
7133         .addJumpTableIndex(MJTI)
7134         .addImm(UId);
7135     }
7136   }
7137 
7138   // Add the jump table entries as successors to the MBB.
7139   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7140   for (std::vector<MachineBasicBlock*>::iterator
7141          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7142     MachineBasicBlock *CurMBB = *I;
7143     if (SeenMBBs.insert(CurMBB))
7144       DispContBB->addSuccessor(CurMBB);
7145   }
7146 
7147   // N.B. the order the invoke BBs are processed in doesn't matter here.
7148   const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
7149   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7150   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
7151          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
7152     MachineBasicBlock *BB = *I;
7153 
7154     // Remove the landing pad successor from the invoke block and replace it
7155     // with the new dispatch block.
7156     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7157                                                   BB->succ_end());
7158     while (!Successors.empty()) {
7159       MachineBasicBlock *SMBB = Successors.pop_back_val();
7160       if (SMBB->isLandingPad()) {
7161         BB->removeSuccessor(SMBB);
7162         MBBLPads.push_back(SMBB);
7163       }
7164     }
7165 
7166     BB->addSuccessor(DispatchBB);
7167 
7168     // Find the invoke call and mark all of the callee-saved registers as
7169     // 'implicit defined' so that they're spilled. This prevents code from
7170     // moving instructions to before the EH block, where they will never be
7171     // executed.
7172     for (MachineBasicBlock::reverse_iterator
7173            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7174       if (!II->isCall()) continue;
7175 
7176       DenseMap<unsigned, bool> DefRegs;
7177       for (MachineInstr::mop_iterator
7178              OI = II->operands_begin(), OE = II->operands_end();
7179            OI != OE; ++OI) {
7180         if (!OI->isReg()) continue;
7181         DefRegs[OI->getReg()] = true;
7182       }
7183 
7184       MachineInstrBuilder MIB(*MF, &*II);
7185 
7186       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7187         unsigned Reg = SavedRegs[i];
7188         if (Subtarget->isThumb2() &&
7189             !ARM::tGPRRegClass.contains(Reg) &&
7190             !ARM::hGPRRegClass.contains(Reg))
7191           continue;
7192         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7193           continue;
7194         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7195           continue;
7196         if (!DefRegs[Reg])
7197           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7198       }
7199 
7200       break;
7201     }
7202   }
7203 
7204   // Mark all former landing pads as non-landing pads. The dispatch is the only
7205   // landing pad now.
7206   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7207          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7208     (*I)->setIsLandingPad(false);
7209 
7210   // The instruction is gone now.
7211   MI->eraseFromParent();
7212 
7213   return MBB;
7214 }
7215 
7216 static
7217 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7218   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7219        E = MBB->succ_end(); I != E; ++I)
7220     if (*I != Succ)
7221       return *I;
7222   llvm_unreachable("Expecting a BB with two successors!");
7223 }
7224 
7225 /// Return the load opcode for a given load size. If load size >= 8,
7226 /// neon opcode will be returned.
7227 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7228   if (LdSize >= 8)
7229     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7230                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7231   if (IsThumb1)
7232     return LdSize == 4 ? ARM::tLDRi
7233                        : LdSize == 2 ? ARM::tLDRHi
7234                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7235   if (IsThumb2)
7236     return LdSize == 4 ? ARM::t2LDR_POST
7237                        : LdSize == 2 ? ARM::t2LDRH_POST
7238                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7239   return LdSize == 4 ? ARM::LDR_POST_IMM
7240                      : LdSize == 2 ? ARM::LDRH_POST
7241                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7242 }
7243 
7244 /// Return the store opcode for a given store size. If store size >= 8,
7245 /// neon opcode will be returned.
7246 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7247   if (StSize >= 8)
7248     return StSize == 16 ? ARM::VST1q32wb_fixed
7249                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7250   if (IsThumb1)
7251     return StSize == 4 ? ARM::tSTRi
7252                        : StSize == 2 ? ARM::tSTRHi
7253                                      : StSize == 1 ? ARM::tSTRBi : 0;
7254   if (IsThumb2)
7255     return StSize == 4 ? ARM::t2STR_POST
7256                        : StSize == 2 ? ARM::t2STRH_POST
7257                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7258   return StSize == 4 ? ARM::STR_POST_IMM
7259                      : StSize == 2 ? ARM::STRH_POST
7260                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7261 }
7262 
7263 /// Emit a post-increment load operation with given size. The instructions
7264 /// will be added to BB at Pos.
7265 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7266                        const TargetInstrInfo *TII, DebugLoc dl,
7267                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7268                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7269   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7270   assert(LdOpc != 0 && "Should have a load opcode");
7271   if (LdSize >= 8) {
7272     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7273                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7274                        .addImm(0));
7275   } else if (IsThumb1) {
7276     // load + update AddrIn
7277     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7278                        .addReg(AddrIn).addImm(0));
7279     MachineInstrBuilder MIB =
7280         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7281     MIB = AddDefaultT1CC(MIB);
7282     MIB.addReg(AddrIn).addImm(LdSize);
7283     AddDefaultPred(MIB);
7284   } else if (IsThumb2) {
7285     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7286                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7287                        .addImm(LdSize));
7288   } else { // arm
7289     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7290                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7291                        .addReg(0).addImm(LdSize));
7292   }
7293 }
7294 
7295 /// Emit a post-increment store operation with given size. The instructions
7296 /// will be added to BB at Pos.
7297 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7298                        const TargetInstrInfo *TII, DebugLoc dl,
7299                        unsigned StSize, unsigned Data, unsigned AddrIn,
7300                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7301   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7302   assert(StOpc != 0 && "Should have a store opcode");
7303   if (StSize >= 8) {
7304     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7305                        .addReg(AddrIn).addImm(0).addReg(Data));
7306   } else if (IsThumb1) {
7307     // store + update AddrIn
7308     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7309                        .addReg(AddrIn).addImm(0));
7310     MachineInstrBuilder MIB =
7311         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7312     MIB = AddDefaultT1CC(MIB);
7313     MIB.addReg(AddrIn).addImm(StSize);
7314     AddDefaultPred(MIB);
7315   } else if (IsThumb2) {
7316     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7317                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7318   } else { // arm
7319     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7320                        .addReg(Data).addReg(AddrIn).addReg(0)
7321                        .addImm(StSize));
7322   }
7323 }
7324 
7325 MachineBasicBlock *
7326 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7327                                    MachineBasicBlock *BB) const {
7328   // This pseudo instruction has 3 operands: dst, src, size
7329   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7330   // Otherwise, we will generate unrolled scalar copies.
7331   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7332   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7333   MachineFunction::iterator It = BB;
7334   ++It;
7335 
7336   unsigned dest = MI->getOperand(0).getReg();
7337   unsigned src = MI->getOperand(1).getReg();
7338   unsigned SizeVal = MI->getOperand(2).getImm();
7339   unsigned Align = MI->getOperand(3).getImm();
7340   DebugLoc dl = MI->getDebugLoc();
7341 
7342   MachineFunction *MF = BB->getParent();
7343   MachineRegisterInfo &MRI = MF->getRegInfo();
7344   unsigned UnitSize = 0;
7345   const TargetRegisterClass *TRC = 0;
7346   const TargetRegisterClass *VecTRC = 0;
7347 
7348   bool IsThumb1 = Subtarget->isThumb1Only();
7349   bool IsThumb2 = Subtarget->isThumb2();
7350 
7351   if (Align & 1) {
7352     UnitSize = 1;
7353   } else if (Align & 2) {
7354     UnitSize = 2;
7355   } else {
7356     // Check whether we can use NEON instructions.
7357     if (!MF->getFunction()->getAttributes().
7358           hasAttribute(AttributeSet::FunctionIndex,
7359                        Attribute::NoImplicitFloat) &&
7360         Subtarget->hasNEON()) {
7361       if ((Align % 16 == 0) && SizeVal >= 16)
7362         UnitSize = 16;
7363       else if ((Align % 8 == 0) && SizeVal >= 8)
7364         UnitSize = 8;
7365     }
7366     // Can't use NEON instructions.
7367     if (UnitSize == 0)
7368       UnitSize = 4;
7369   }
7370 
7371   // Select the correct opcode and register class for unit size load/store
7372   bool IsNeon = UnitSize >= 8;
7373   TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
7374                                : (const TargetRegisterClass *)&ARM::GPRRegClass;
7375   if (IsNeon)
7376     VecTRC = UnitSize == 16
7377                  ? (const TargetRegisterClass *)&ARM::DPairRegClass
7378                  : UnitSize == 8
7379                        ? (const TargetRegisterClass *)&ARM::DPRRegClass
7380                        : 0;
7381 
7382   unsigned BytesLeft = SizeVal % UnitSize;
7383   unsigned LoopSize = SizeVal - BytesLeft;
7384 
7385   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7386     // Use LDR and STR to copy.
7387     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7388     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7389     unsigned srcIn = src;
7390     unsigned destIn = dest;
7391     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7392       unsigned srcOut = MRI.createVirtualRegister(TRC);
7393       unsigned destOut = MRI.createVirtualRegister(TRC);
7394       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7395       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7396                  IsThumb1, IsThumb2);
7397       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7398                  IsThumb1, IsThumb2);
7399       srcIn = srcOut;
7400       destIn = destOut;
7401     }
7402 
7403     // Handle the leftover bytes with LDRB and STRB.
7404     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7405     // [destOut] = STRB_POST(scratch, destIn, 1)
7406     for (unsigned i = 0; i < BytesLeft; i++) {
7407       unsigned srcOut = MRI.createVirtualRegister(TRC);
7408       unsigned destOut = MRI.createVirtualRegister(TRC);
7409       unsigned scratch = MRI.createVirtualRegister(TRC);
7410       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7411                  IsThumb1, IsThumb2);
7412       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7413                  IsThumb1, IsThumb2);
7414       srcIn = srcOut;
7415       destIn = destOut;
7416     }
7417     MI->eraseFromParent();   // The instruction is gone now.
7418     return BB;
7419   }
7420 
7421   // Expand the pseudo op to a loop.
7422   // thisMBB:
7423   //   ...
7424   //   movw varEnd, # --> with thumb2
7425   //   movt varEnd, #
7426   //   ldrcp varEnd, idx --> without thumb2
7427   //   fallthrough --> loopMBB
7428   // loopMBB:
7429   //   PHI varPhi, varEnd, varLoop
7430   //   PHI srcPhi, src, srcLoop
7431   //   PHI destPhi, dst, destLoop
7432   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7433   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7434   //   subs varLoop, varPhi, #UnitSize
7435   //   bne loopMBB
7436   //   fallthrough --> exitMBB
7437   // exitMBB:
7438   //   epilogue to handle left-over bytes
7439   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7440   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7441   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7442   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7443   MF->insert(It, loopMBB);
7444   MF->insert(It, exitMBB);
7445 
7446   // Transfer the remainder of BB and its successor edges to exitMBB.
7447   exitMBB->splice(exitMBB->begin(), BB,
7448                   llvm::next(MachineBasicBlock::iterator(MI)),
7449                   BB->end());
7450   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7451 
7452   // Load an immediate to varEnd.
7453   unsigned varEnd = MRI.createVirtualRegister(TRC);
7454   if (IsThumb2) {
7455     unsigned Vtmp = varEnd;
7456     if ((LoopSize & 0xFFFF0000) != 0)
7457       Vtmp = MRI.createVirtualRegister(TRC);
7458     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7459                        .addImm(LoopSize & 0xFFFF));
7460 
7461     if ((LoopSize & 0xFFFF0000) != 0)
7462       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7463                          .addReg(Vtmp).addImm(LoopSize >> 16));
7464   } else {
7465     MachineConstantPool *ConstantPool = MF->getConstantPool();
7466     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7467     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7468 
7469     // MachineConstantPool wants an explicit alignment.
7470     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7471     if (Align == 0)
7472       Align = getDataLayout()->getTypeAllocSize(C->getType());
7473     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7474 
7475     if (IsThumb1)
7476       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7477           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7478     else
7479       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7480           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7481   }
7482   BB->addSuccessor(loopMBB);
7483 
7484   // Generate the loop body:
7485   //   varPhi = PHI(varLoop, varEnd)
7486   //   srcPhi = PHI(srcLoop, src)
7487   //   destPhi = PHI(destLoop, dst)
7488   MachineBasicBlock *entryBB = BB;
7489   BB = loopMBB;
7490   unsigned varLoop = MRI.createVirtualRegister(TRC);
7491   unsigned varPhi = MRI.createVirtualRegister(TRC);
7492   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7493   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7494   unsigned destLoop = MRI.createVirtualRegister(TRC);
7495   unsigned destPhi = MRI.createVirtualRegister(TRC);
7496 
7497   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7498     .addReg(varLoop).addMBB(loopMBB)
7499     .addReg(varEnd).addMBB(entryBB);
7500   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7501     .addReg(srcLoop).addMBB(loopMBB)
7502     .addReg(src).addMBB(entryBB);
7503   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7504     .addReg(destLoop).addMBB(loopMBB)
7505     .addReg(dest).addMBB(entryBB);
7506 
7507   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7508   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7509   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7510   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7511              IsThumb1, IsThumb2);
7512   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7513              IsThumb1, IsThumb2);
7514 
7515   // Decrement loop variable by UnitSize.
7516   if (IsThumb1) {
7517     MachineInstrBuilder MIB =
7518         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7519     MIB = AddDefaultT1CC(MIB);
7520     MIB.addReg(varPhi).addImm(UnitSize);
7521     AddDefaultPred(MIB);
7522   } else {
7523     MachineInstrBuilder MIB =
7524         BuildMI(*BB, BB->end(), dl,
7525                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7526     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7527     MIB->getOperand(5).setReg(ARM::CPSR);
7528     MIB->getOperand(5).setIsDef(true);
7529   }
7530   BuildMI(*BB, BB->end(), dl,
7531           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7532       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7533 
7534   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7535   BB->addSuccessor(loopMBB);
7536   BB->addSuccessor(exitMBB);
7537 
7538   // Add epilogue to handle BytesLeft.
7539   BB = exitMBB;
7540   MachineInstr *StartOfExit = exitMBB->begin();
7541 
7542   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7543   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7544   unsigned srcIn = srcLoop;
7545   unsigned destIn = destLoop;
7546   for (unsigned i = 0; i < BytesLeft; i++) {
7547     unsigned srcOut = MRI.createVirtualRegister(TRC);
7548     unsigned destOut = MRI.createVirtualRegister(TRC);
7549     unsigned scratch = MRI.createVirtualRegister(TRC);
7550     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7551                IsThumb1, IsThumb2);
7552     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7553                IsThumb1, IsThumb2);
7554     srcIn = srcOut;
7555     destIn = destOut;
7556   }
7557 
7558   MI->eraseFromParent();   // The instruction is gone now.
7559   return BB;
7560 }
7561 
7562 MachineBasicBlock *
7563 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7564                                                MachineBasicBlock *BB) const {
7565   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7566   DebugLoc dl = MI->getDebugLoc();
7567   bool isThumb2 = Subtarget->isThumb2();
7568   switch (MI->getOpcode()) {
7569   default: {
7570     MI->dump();
7571     llvm_unreachable("Unexpected instr type to insert");
7572   }
7573   // The Thumb2 pre-indexed stores have the same MI operands, they just
7574   // define them differently in the .td files from the isel patterns, so
7575   // they need pseudos.
7576   case ARM::t2STR_preidx:
7577     MI->setDesc(TII->get(ARM::t2STR_PRE));
7578     return BB;
7579   case ARM::t2STRB_preidx:
7580     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7581     return BB;
7582   case ARM::t2STRH_preidx:
7583     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7584     return BB;
7585 
7586   case ARM::STRi_preidx:
7587   case ARM::STRBi_preidx: {
7588     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7589       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7590     // Decode the offset.
7591     unsigned Offset = MI->getOperand(4).getImm();
7592     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7593     Offset = ARM_AM::getAM2Offset(Offset);
7594     if (isSub)
7595       Offset = -Offset;
7596 
7597     MachineMemOperand *MMO = *MI->memoperands_begin();
7598     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7599       .addOperand(MI->getOperand(0))  // Rn_wb
7600       .addOperand(MI->getOperand(1))  // Rt
7601       .addOperand(MI->getOperand(2))  // Rn
7602       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7603       .addOperand(MI->getOperand(5))  // pred
7604       .addOperand(MI->getOperand(6))
7605       .addMemOperand(MMO);
7606     MI->eraseFromParent();
7607     return BB;
7608   }
7609   case ARM::STRr_preidx:
7610   case ARM::STRBr_preidx:
7611   case ARM::STRH_preidx: {
7612     unsigned NewOpc;
7613     switch (MI->getOpcode()) {
7614     default: llvm_unreachable("unexpected opcode!");
7615     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7616     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7617     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7618     }
7619     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7620     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7621       MIB.addOperand(MI->getOperand(i));
7622     MI->eraseFromParent();
7623     return BB;
7624   }
7625   case ARM::ATOMIC_LOAD_ADD_I8:
7626      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7627   case ARM::ATOMIC_LOAD_ADD_I16:
7628      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7629   case ARM::ATOMIC_LOAD_ADD_I32:
7630      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7631 
7632   case ARM::ATOMIC_LOAD_AND_I8:
7633      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7634   case ARM::ATOMIC_LOAD_AND_I16:
7635      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7636   case ARM::ATOMIC_LOAD_AND_I32:
7637      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7638 
7639   case ARM::ATOMIC_LOAD_OR_I8:
7640      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7641   case ARM::ATOMIC_LOAD_OR_I16:
7642      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7643   case ARM::ATOMIC_LOAD_OR_I32:
7644      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7645 
7646   case ARM::ATOMIC_LOAD_XOR_I8:
7647      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7648   case ARM::ATOMIC_LOAD_XOR_I16:
7649      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7650   case ARM::ATOMIC_LOAD_XOR_I32:
7651      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7652 
7653   case ARM::ATOMIC_LOAD_NAND_I8:
7654      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7655   case ARM::ATOMIC_LOAD_NAND_I16:
7656      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7657   case ARM::ATOMIC_LOAD_NAND_I32:
7658      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7659 
7660   case ARM::ATOMIC_LOAD_SUB_I8:
7661      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7662   case ARM::ATOMIC_LOAD_SUB_I16:
7663      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7664   case ARM::ATOMIC_LOAD_SUB_I32:
7665      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7666 
7667   case ARM::ATOMIC_LOAD_MIN_I8:
7668      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7669   case ARM::ATOMIC_LOAD_MIN_I16:
7670      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7671   case ARM::ATOMIC_LOAD_MIN_I32:
7672      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7673 
7674   case ARM::ATOMIC_LOAD_MAX_I8:
7675      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7676   case ARM::ATOMIC_LOAD_MAX_I16:
7677      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7678   case ARM::ATOMIC_LOAD_MAX_I32:
7679      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7680 
7681   case ARM::ATOMIC_LOAD_UMIN_I8:
7682      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7683   case ARM::ATOMIC_LOAD_UMIN_I16:
7684      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7685   case ARM::ATOMIC_LOAD_UMIN_I32:
7686      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7687 
7688   case ARM::ATOMIC_LOAD_UMAX_I8:
7689      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7690   case ARM::ATOMIC_LOAD_UMAX_I16:
7691      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7692   case ARM::ATOMIC_LOAD_UMAX_I32:
7693      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7694 
7695   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
7696   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7697   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7698 
7699   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
7700   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7701   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7702 
7703   case ARM::ATOMIC_LOAD_I64:
7704     return EmitAtomicLoad64(MI, BB);
7705 
7706   case ARM::ATOMIC_LOAD_ADD_I64:
7707     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7708                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7709                               /*NeedsCarry*/ true);
7710   case ARM::ATOMIC_LOAD_SUB_I64:
7711     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7712                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7713                               /*NeedsCarry*/ true);
7714   case ARM::ATOMIC_LOAD_OR_I64:
7715     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7716                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7717   case ARM::ATOMIC_LOAD_XOR_I64:
7718     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7719                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7720   case ARM::ATOMIC_LOAD_AND_I64:
7721     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7722                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7723   case ARM::ATOMIC_STORE_I64:
7724   case ARM::ATOMIC_SWAP_I64:
7725     return EmitAtomicBinary64(MI, BB, 0, 0, false);
7726   case ARM::ATOMIC_CMP_SWAP_I64:
7727     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7728                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7729                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7730   case ARM::ATOMIC_LOAD_MIN_I64:
7731     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7732                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7733                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7734                               /*IsMinMax*/ true, ARMCC::LT);
7735   case ARM::ATOMIC_LOAD_MAX_I64:
7736     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7737                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7738                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7739                               /*IsMinMax*/ true, ARMCC::GE);
7740   case ARM::ATOMIC_LOAD_UMIN_I64:
7741     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7742                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7743                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7744                               /*IsMinMax*/ true, ARMCC::LO);
7745   case ARM::ATOMIC_LOAD_UMAX_I64:
7746     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7747                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7748                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7749                               /*IsMinMax*/ true, ARMCC::HS);
7750 
7751   case ARM::tMOVCCr_pseudo: {
7752     // To "insert" a SELECT_CC instruction, we actually have to insert the
7753     // diamond control-flow pattern.  The incoming instruction knows the
7754     // destination vreg to set, the condition code register to branch on, the
7755     // true/false values to select between, and a branch opcode to use.
7756     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7757     MachineFunction::iterator It = BB;
7758     ++It;
7759 
7760     //  thisMBB:
7761     //  ...
7762     //   TrueVal = ...
7763     //   cmpTY ccX, r1, r2
7764     //   bCC copy1MBB
7765     //   fallthrough --> copy0MBB
7766     MachineBasicBlock *thisMBB  = BB;
7767     MachineFunction *F = BB->getParent();
7768     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7769     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7770     F->insert(It, copy0MBB);
7771     F->insert(It, sinkMBB);
7772 
7773     // Transfer the remainder of BB and its successor edges to sinkMBB.
7774     sinkMBB->splice(sinkMBB->begin(), BB,
7775                     llvm::next(MachineBasicBlock::iterator(MI)),
7776                     BB->end());
7777     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7778 
7779     BB->addSuccessor(copy0MBB);
7780     BB->addSuccessor(sinkMBB);
7781 
7782     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7783       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7784 
7785     //  copy0MBB:
7786     //   %FalseValue = ...
7787     //   # fallthrough to sinkMBB
7788     BB = copy0MBB;
7789 
7790     // Update machine-CFG edges
7791     BB->addSuccessor(sinkMBB);
7792 
7793     //  sinkMBB:
7794     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7795     //  ...
7796     BB = sinkMBB;
7797     BuildMI(*BB, BB->begin(), dl,
7798             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7799       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7800       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7801 
7802     MI->eraseFromParent();   // The pseudo instruction is gone now.
7803     return BB;
7804   }
7805 
7806   case ARM::BCCi64:
7807   case ARM::BCCZi64: {
7808     // If there is an unconditional branch to the other successor, remove it.
7809     BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
7810 
7811     // Compare both parts that make up the double comparison separately for
7812     // equality.
7813     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7814 
7815     unsigned LHS1 = MI->getOperand(1).getReg();
7816     unsigned LHS2 = MI->getOperand(2).getReg();
7817     if (RHSisZero) {
7818       AddDefaultPred(BuildMI(BB, dl,
7819                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7820                      .addReg(LHS1).addImm(0));
7821       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7822         .addReg(LHS2).addImm(0)
7823         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7824     } else {
7825       unsigned RHS1 = MI->getOperand(3).getReg();
7826       unsigned RHS2 = MI->getOperand(4).getReg();
7827       AddDefaultPred(BuildMI(BB, dl,
7828                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7829                      .addReg(LHS1).addReg(RHS1));
7830       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7831         .addReg(LHS2).addReg(RHS2)
7832         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7833     }
7834 
7835     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7836     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7837     if (MI->getOperand(0).getImm() == ARMCC::NE)
7838       std::swap(destMBB, exitMBB);
7839 
7840     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7841       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7842     if (isThumb2)
7843       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7844     else
7845       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7846 
7847     MI->eraseFromParent();   // The pseudo instruction is gone now.
7848     return BB;
7849   }
7850 
7851   case ARM::Int_eh_sjlj_setjmp:
7852   case ARM::Int_eh_sjlj_setjmp_nofp:
7853   case ARM::tInt_eh_sjlj_setjmp:
7854   case ARM::t2Int_eh_sjlj_setjmp:
7855   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7856     EmitSjLjDispatchBlock(MI, BB);
7857     return BB;
7858 
7859   case ARM::ABS:
7860   case ARM::t2ABS: {
7861     // To insert an ABS instruction, we have to insert the
7862     // diamond control-flow pattern.  The incoming instruction knows the
7863     // source vreg to test against 0, the destination vreg to set,
7864     // the condition code register to branch on, the
7865     // true/false values to select between, and a branch opcode to use.
7866     // It transforms
7867     //     V1 = ABS V0
7868     // into
7869     //     V2 = MOVS V0
7870     //     BCC                      (branch to SinkBB if V0 >= 0)
7871     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7872     //     SinkBB: V1 = PHI(V2, V3)
7873     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7874     MachineFunction::iterator BBI = BB;
7875     ++BBI;
7876     MachineFunction *Fn = BB->getParent();
7877     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7878     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7879     Fn->insert(BBI, RSBBB);
7880     Fn->insert(BBI, SinkBB);
7881 
7882     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7883     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7884     bool isThumb2 = Subtarget->isThumb2();
7885     MachineRegisterInfo &MRI = Fn->getRegInfo();
7886     // In Thumb mode S must not be specified if source register is the SP or
7887     // PC and if destination register is the SP, so restrict register class
7888     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7889       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7890       (const TargetRegisterClass*)&ARM::GPRRegClass);
7891 
7892     // Transfer the remainder of BB and its successor edges to sinkMBB.
7893     SinkBB->splice(SinkBB->begin(), BB,
7894       llvm::next(MachineBasicBlock::iterator(MI)),
7895       BB->end());
7896     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7897 
7898     BB->addSuccessor(RSBBB);
7899     BB->addSuccessor(SinkBB);
7900 
7901     // fall through to SinkMBB
7902     RSBBB->addSuccessor(SinkBB);
7903 
7904     // insert a cmp at the end of BB
7905     AddDefaultPred(BuildMI(BB, dl,
7906                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7907                    .addReg(ABSSrcReg).addImm(0));
7908 
7909     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7910     BuildMI(BB, dl,
7911       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7912       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7913 
7914     // insert rsbri in RSBBB
7915     // Note: BCC and rsbri will be converted into predicated rsbmi
7916     // by if-conversion pass
7917     BuildMI(*RSBBB, RSBBB->begin(), dl,
7918       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7919       .addReg(ABSSrcReg, RegState::Kill)
7920       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7921 
7922     // insert PHI in SinkBB,
7923     // reuse ABSDstReg to not change uses of ABS instruction
7924     BuildMI(*SinkBB, SinkBB->begin(), dl,
7925       TII->get(ARM::PHI), ABSDstReg)
7926       .addReg(NewRsbDstReg).addMBB(RSBBB)
7927       .addReg(ABSSrcReg).addMBB(BB);
7928 
7929     // remove ABS instruction
7930     MI->eraseFromParent();
7931 
7932     // return last added BB
7933     return SinkBB;
7934   }
7935   case ARM::COPY_STRUCT_BYVAL_I32:
7936     ++NumLoopByVals;
7937     return EmitStructByval(MI, BB);
7938   }
7939 }
7940 
7941 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7942                                                       SDNode *Node) const {
7943   if (!MI->hasPostISelHook()) {
7944     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7945            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7946     return;
7947   }
7948 
7949   const MCInstrDesc *MCID = &MI->getDesc();
7950   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7951   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7952   // operand is still set to noreg. If needed, set the optional operand's
7953   // register to CPSR, and remove the redundant implicit def.
7954   //
7955   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7956 
7957   // Rename pseudo opcodes.
7958   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7959   if (NewOpc) {
7960     const ARMBaseInstrInfo *TII =
7961       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7962     MCID = &TII->get(NewOpc);
7963 
7964     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7965            "converted opcode should be the same except for cc_out");
7966 
7967     MI->setDesc(*MCID);
7968 
7969     // Add the optional cc_out operand
7970     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7971   }
7972   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7973 
7974   // Any ARM instruction that sets the 's' bit should specify an optional
7975   // "cc_out" operand in the last operand position.
7976   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7977     assert(!NewOpc && "Optional cc_out operand required");
7978     return;
7979   }
7980   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7981   // since we already have an optional CPSR def.
7982   bool definesCPSR = false;
7983   bool deadCPSR = false;
7984   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7985        i != e; ++i) {
7986     const MachineOperand &MO = MI->getOperand(i);
7987     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7988       definesCPSR = true;
7989       if (MO.isDead())
7990         deadCPSR = true;
7991       MI->RemoveOperand(i);
7992       break;
7993     }
7994   }
7995   if (!definesCPSR) {
7996     assert(!NewOpc && "Optional cc_out operand required");
7997     return;
7998   }
7999   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8000   if (deadCPSR) {
8001     assert(!MI->getOperand(ccOutIdx).getReg() &&
8002            "expect uninitialized optional cc_out operand");
8003     return;
8004   }
8005 
8006   // If this instruction was defined with an optional CPSR def and its dag node
8007   // had a live implicit CPSR def, then activate the optional CPSR def.
8008   MachineOperand &MO = MI->getOperand(ccOutIdx);
8009   MO.setReg(ARM::CPSR);
8010   MO.setIsDef(true);
8011 }
8012 
8013 //===----------------------------------------------------------------------===//
8014 //                           ARM Optimization Hooks
8015 //===----------------------------------------------------------------------===//
8016 
8017 // Helper function that checks if N is a null or all ones constant.
8018 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8019   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8020   if (!C)
8021     return false;
8022   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8023 }
8024 
8025 // Return true if N is conditionally 0 or all ones.
8026 // Detects these expressions where cc is an i1 value:
8027 //
8028 //   (select cc 0, y)   [AllOnes=0]
8029 //   (select cc y, 0)   [AllOnes=0]
8030 //   (zext cc)          [AllOnes=0]
8031 //   (sext cc)          [AllOnes=0/1]
8032 //   (select cc -1, y)  [AllOnes=1]
8033 //   (select cc y, -1)  [AllOnes=1]
8034 //
8035 // Invert is set when N is the null/all ones constant when CC is false.
8036 // OtherOp is set to the alternative value of N.
8037 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8038                                        SDValue &CC, bool &Invert,
8039                                        SDValue &OtherOp,
8040                                        SelectionDAG &DAG) {
8041   switch (N->getOpcode()) {
8042   default: return false;
8043   case ISD::SELECT: {
8044     CC = N->getOperand(0);
8045     SDValue N1 = N->getOperand(1);
8046     SDValue N2 = N->getOperand(2);
8047     if (isZeroOrAllOnes(N1, AllOnes)) {
8048       Invert = false;
8049       OtherOp = N2;
8050       return true;
8051     }
8052     if (isZeroOrAllOnes(N2, AllOnes)) {
8053       Invert = true;
8054       OtherOp = N1;
8055       return true;
8056     }
8057     return false;
8058   }
8059   case ISD::ZERO_EXTEND:
8060     // (zext cc) can never be the all ones value.
8061     if (AllOnes)
8062       return false;
8063     // Fall through.
8064   case ISD::SIGN_EXTEND: {
8065     EVT VT = N->getValueType(0);
8066     CC = N->getOperand(0);
8067     if (CC.getValueType() != MVT::i1)
8068       return false;
8069     Invert = !AllOnes;
8070     if (AllOnes)
8071       // When looking for an AllOnes constant, N is an sext, and the 'other'
8072       // value is 0.
8073       OtherOp = DAG.getConstant(0, VT);
8074     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8075       // When looking for a 0 constant, N can be zext or sext.
8076       OtherOp = DAG.getConstant(1, VT);
8077     else
8078       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
8079     return true;
8080   }
8081   }
8082 }
8083 
8084 // Combine a constant select operand into its use:
8085 //
8086 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
8087 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
8088 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
8089 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
8090 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
8091 //
8092 // The transform is rejected if the select doesn't have a constant operand that
8093 // is null, or all ones when AllOnes is set.
8094 //
8095 // Also recognize sext/zext from i1:
8096 //
8097 //   (add (zext cc), x) -> (select cc (add x, 1), x)
8098 //   (add (sext cc), x) -> (select cc (add x, -1), x)
8099 //
8100 // These transformations eventually create predicated instructions.
8101 //
8102 // @param N       The node to transform.
8103 // @param Slct    The N operand that is a select.
8104 // @param OtherOp The other N operand (x above).
8105 // @param DCI     Context.
8106 // @param AllOnes Require the select constant to be all ones instead of null.
8107 // @returns The new node, or SDValue() on failure.
8108 static
8109 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8110                             TargetLowering::DAGCombinerInfo &DCI,
8111                             bool AllOnes = false) {
8112   SelectionDAG &DAG = DCI.DAG;
8113   EVT VT = N->getValueType(0);
8114   SDValue NonConstantVal;
8115   SDValue CCOp;
8116   bool SwapSelectOps;
8117   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8118                                   NonConstantVal, DAG))
8119     return SDValue();
8120 
8121   // Slct is now know to be the desired identity constant when CC is true.
8122   SDValue TrueVal = OtherOp;
8123   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8124                                  OtherOp, NonConstantVal);
8125   // Unless SwapSelectOps says CC should be false.
8126   if (SwapSelectOps)
8127     std::swap(TrueVal, FalseVal);
8128 
8129   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8130                      CCOp, TrueVal, FalseVal);
8131 }
8132 
8133 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8134 static
8135 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8136                                        TargetLowering::DAGCombinerInfo &DCI) {
8137   SDValue N0 = N->getOperand(0);
8138   SDValue N1 = N->getOperand(1);
8139   if (N0.getNode()->hasOneUse()) {
8140     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8141     if (Result.getNode())
8142       return Result;
8143   }
8144   if (N1.getNode()->hasOneUse()) {
8145     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8146     if (Result.getNode())
8147       return Result;
8148   }
8149   return SDValue();
8150 }
8151 
8152 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8153 // (only after legalization).
8154 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8155                                  TargetLowering::DAGCombinerInfo &DCI,
8156                                  const ARMSubtarget *Subtarget) {
8157 
8158   // Only perform optimization if after legalize, and if NEON is available. We
8159   // also expected both operands to be BUILD_VECTORs.
8160   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8161       || N0.getOpcode() != ISD::BUILD_VECTOR
8162       || N1.getOpcode() != ISD::BUILD_VECTOR)
8163     return SDValue();
8164 
8165   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8166   EVT VT = N->getValueType(0);
8167   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8168     return SDValue();
8169 
8170   // Check that the vector operands are of the right form.
8171   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8172   // operands, where N is the size of the formed vector.
8173   // Each EXTRACT_VECTOR should have the same input vector and odd or even
8174   // index such that we have a pair wise add pattern.
8175 
8176   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8177   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8178     return SDValue();
8179   SDValue Vec = N0->getOperand(0)->getOperand(0);
8180   SDNode *V = Vec.getNode();
8181   unsigned nextIndex = 0;
8182 
8183   // For each operands to the ADD which are BUILD_VECTORs,
8184   // check to see if each of their operands are an EXTRACT_VECTOR with
8185   // the same vector and appropriate index.
8186   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8187     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8188         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8189 
8190       SDValue ExtVec0 = N0->getOperand(i);
8191       SDValue ExtVec1 = N1->getOperand(i);
8192 
8193       // First operand is the vector, verify its the same.
8194       if (V != ExtVec0->getOperand(0).getNode() ||
8195           V != ExtVec1->getOperand(0).getNode())
8196         return SDValue();
8197 
8198       // Second is the constant, verify its correct.
8199       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8200       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8201 
8202       // For the constant, we want to see all the even or all the odd.
8203       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8204           || C1->getZExtValue() != nextIndex+1)
8205         return SDValue();
8206 
8207       // Increment index.
8208       nextIndex+=2;
8209     } else
8210       return SDValue();
8211   }
8212 
8213   // Create VPADDL node.
8214   SelectionDAG &DAG = DCI.DAG;
8215   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8216 
8217   // Build operand list.
8218   SmallVector<SDValue, 8> Ops;
8219   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
8220                                 TLI.getPointerTy()));
8221 
8222   // Input is the vector.
8223   Ops.push_back(Vec);
8224 
8225   // Get widened type and narrowed type.
8226   MVT widenType;
8227   unsigned numElem = VT.getVectorNumElements();
8228   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8229     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8230     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8231     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8232     default:
8233       llvm_unreachable("Invalid vector element type for padd optimization.");
8234   }
8235 
8236   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
8237                             widenType, &Ops[0], Ops.size());
8238   return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, tmp);
8239 }
8240 
8241 static SDValue findMUL_LOHI(SDValue V) {
8242   if (V->getOpcode() == ISD::UMUL_LOHI ||
8243       V->getOpcode() == ISD::SMUL_LOHI)
8244     return V;
8245   return SDValue();
8246 }
8247 
8248 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8249                                      TargetLowering::DAGCombinerInfo &DCI,
8250                                      const ARMSubtarget *Subtarget) {
8251 
8252   if (Subtarget->isThumb1Only()) return SDValue();
8253 
8254   // Only perform the checks after legalize when the pattern is available.
8255   if (DCI.isBeforeLegalize()) return SDValue();
8256 
8257   // Look for multiply add opportunities.
8258   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8259   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8260   // a glue link from the first add to the second add.
8261   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8262   // a S/UMLAL instruction.
8263   //          loAdd   UMUL_LOHI
8264   //            \    / :lo    \ :hi
8265   //             \  /          \          [no multiline comment]
8266   //              ADDC         |  hiAdd
8267   //                 \ :glue  /  /
8268   //                  \      /  /
8269   //                    ADDE
8270   //
8271   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8272   SDValue AddcOp0 = AddcNode->getOperand(0);
8273   SDValue AddcOp1 = AddcNode->getOperand(1);
8274 
8275   // Check if the two operands are from the same mul_lohi node.
8276   if (AddcOp0.getNode() == AddcOp1.getNode())
8277     return SDValue();
8278 
8279   assert(AddcNode->getNumValues() == 2 &&
8280          AddcNode->getValueType(0) == MVT::i32 &&
8281          "Expect ADDC with two result values. First: i32");
8282 
8283   // Check that we have a glued ADDC node.
8284   if (AddcNode->getValueType(1) != MVT::Glue)
8285     return SDValue();
8286 
8287   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8288   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8289       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8290       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8291       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8292     return SDValue();
8293 
8294   // Look for the glued ADDE.
8295   SDNode* AddeNode = AddcNode->getGluedUser();
8296   if (AddeNode == NULL)
8297     return SDValue();
8298 
8299   // Make sure it is really an ADDE.
8300   if (AddeNode->getOpcode() != ISD::ADDE)
8301     return SDValue();
8302 
8303   assert(AddeNode->getNumOperands() == 3 &&
8304          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8305          "ADDE node has the wrong inputs");
8306 
8307   // Check for the triangle shape.
8308   SDValue AddeOp0 = AddeNode->getOperand(0);
8309   SDValue AddeOp1 = AddeNode->getOperand(1);
8310 
8311   // Make sure that the ADDE operands are not coming from the same node.
8312   if (AddeOp0.getNode() == AddeOp1.getNode())
8313     return SDValue();
8314 
8315   // Find the MUL_LOHI node walking up ADDE's operands.
8316   bool IsLeftOperandMUL = false;
8317   SDValue MULOp = findMUL_LOHI(AddeOp0);
8318   if (MULOp == SDValue())
8319    MULOp = findMUL_LOHI(AddeOp1);
8320   else
8321     IsLeftOperandMUL = true;
8322   if (MULOp == SDValue())
8323      return SDValue();
8324 
8325   // Figure out the right opcode.
8326   unsigned Opc = MULOp->getOpcode();
8327   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8328 
8329   // Figure out the high and low input values to the MLAL node.
8330   SDValue* HiMul = &MULOp;
8331   SDValue* HiAdd = NULL;
8332   SDValue* LoMul = NULL;
8333   SDValue* LowAdd = NULL;
8334 
8335   if (IsLeftOperandMUL)
8336     HiAdd = &AddeOp1;
8337   else
8338     HiAdd = &AddeOp0;
8339 
8340 
8341   if (AddcOp0->getOpcode() == Opc) {
8342     LoMul = &AddcOp0;
8343     LowAdd = &AddcOp1;
8344   }
8345   if (AddcOp1->getOpcode() == Opc) {
8346     LoMul = &AddcOp1;
8347     LowAdd = &AddcOp0;
8348   }
8349 
8350   if (LoMul == NULL)
8351     return SDValue();
8352 
8353   if (LoMul->getNode() != HiMul->getNode())
8354     return SDValue();
8355 
8356   // Create the merged node.
8357   SelectionDAG &DAG = DCI.DAG;
8358 
8359   // Build operand list.
8360   SmallVector<SDValue, 8> Ops;
8361   Ops.push_back(LoMul->getOperand(0));
8362   Ops.push_back(LoMul->getOperand(1));
8363   Ops.push_back(*LowAdd);
8364   Ops.push_back(*HiAdd);
8365 
8366   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8367                                  DAG.getVTList(MVT::i32, MVT::i32),
8368                                  &Ops[0], Ops.size());
8369 
8370   // Replace the ADDs' nodes uses by the MLA node's values.
8371   SDValue HiMLALResult(MLALNode.getNode(), 1);
8372   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8373 
8374   SDValue LoMLALResult(MLALNode.getNode(), 0);
8375   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8376 
8377   // Return original node to notify the driver to stop replacing.
8378   SDValue resNode(AddcNode, 0);
8379   return resNode;
8380 }
8381 
8382 /// PerformADDCCombine - Target-specific dag combine transform from
8383 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8384 static SDValue PerformADDCCombine(SDNode *N,
8385                                  TargetLowering::DAGCombinerInfo &DCI,
8386                                  const ARMSubtarget *Subtarget) {
8387 
8388   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8389 
8390 }
8391 
8392 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8393 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8394 /// called with the default operands, and if that fails, with commuted
8395 /// operands.
8396 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8397                                           TargetLowering::DAGCombinerInfo &DCI,
8398                                           const ARMSubtarget *Subtarget){
8399 
8400   // Attempt to create vpaddl for this add.
8401   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8402   if (Result.getNode())
8403     return Result;
8404 
8405   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8406   if (N0.getNode()->hasOneUse()) {
8407     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8408     if (Result.getNode()) return Result;
8409   }
8410   return SDValue();
8411 }
8412 
8413 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8414 ///
8415 static SDValue PerformADDCombine(SDNode *N,
8416                                  TargetLowering::DAGCombinerInfo &DCI,
8417                                  const ARMSubtarget *Subtarget) {
8418   SDValue N0 = N->getOperand(0);
8419   SDValue N1 = N->getOperand(1);
8420 
8421   // First try with the default operand order.
8422   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8423   if (Result.getNode())
8424     return Result;
8425 
8426   // If that didn't work, try again with the operands commuted.
8427   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8428 }
8429 
8430 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8431 ///
8432 static SDValue PerformSUBCombine(SDNode *N,
8433                                  TargetLowering::DAGCombinerInfo &DCI) {
8434   SDValue N0 = N->getOperand(0);
8435   SDValue N1 = N->getOperand(1);
8436 
8437   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8438   if (N1.getNode()->hasOneUse()) {
8439     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8440     if (Result.getNode()) return Result;
8441   }
8442 
8443   return SDValue();
8444 }
8445 
8446 /// PerformVMULCombine
8447 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8448 /// special multiplier accumulator forwarding.
8449 ///   vmul d3, d0, d2
8450 ///   vmla d3, d1, d2
8451 /// is faster than
8452 ///   vadd d3, d0, d1
8453 ///   vmul d3, d3, d2
8454 //  However, for (A + B) * (A + B),
8455 //    vadd d2, d0, d1
8456 //    vmul d3, d0, d2
8457 //    vmla d3, d1, d2
8458 //  is slower than
8459 //    vadd d2, d0, d1
8460 //    vmul d3, d2, d2
8461 static SDValue PerformVMULCombine(SDNode *N,
8462                                   TargetLowering::DAGCombinerInfo &DCI,
8463                                   const ARMSubtarget *Subtarget) {
8464   if (!Subtarget->hasVMLxForwarding())
8465     return SDValue();
8466 
8467   SelectionDAG &DAG = DCI.DAG;
8468   SDValue N0 = N->getOperand(0);
8469   SDValue N1 = N->getOperand(1);
8470   unsigned Opcode = N0.getOpcode();
8471   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8472       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8473     Opcode = N1.getOpcode();
8474     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8475         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8476       return SDValue();
8477     std::swap(N0, N1);
8478   }
8479 
8480   if (N0 == N1)
8481     return SDValue();
8482 
8483   EVT VT = N->getValueType(0);
8484   SDLoc DL(N);
8485   SDValue N00 = N0->getOperand(0);
8486   SDValue N01 = N0->getOperand(1);
8487   return DAG.getNode(Opcode, DL, VT,
8488                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8489                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8490 }
8491 
8492 static SDValue PerformMULCombine(SDNode *N,
8493                                  TargetLowering::DAGCombinerInfo &DCI,
8494                                  const ARMSubtarget *Subtarget) {
8495   SelectionDAG &DAG = DCI.DAG;
8496 
8497   if (Subtarget->isThumb1Only())
8498     return SDValue();
8499 
8500   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8501     return SDValue();
8502 
8503   EVT VT = N->getValueType(0);
8504   if (VT.is64BitVector() || VT.is128BitVector())
8505     return PerformVMULCombine(N, DCI, Subtarget);
8506   if (VT != MVT::i32)
8507     return SDValue();
8508 
8509   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8510   if (!C)
8511     return SDValue();
8512 
8513   int64_t MulAmt = C->getSExtValue();
8514   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8515 
8516   ShiftAmt = ShiftAmt & (32 - 1);
8517   SDValue V = N->getOperand(0);
8518   SDLoc DL(N);
8519 
8520   SDValue Res;
8521   MulAmt >>= ShiftAmt;
8522 
8523   if (MulAmt >= 0) {
8524     if (isPowerOf2_32(MulAmt - 1)) {
8525       // (mul x, 2^N + 1) => (add (shl x, N), x)
8526       Res = DAG.getNode(ISD::ADD, DL, VT,
8527                         V,
8528                         DAG.getNode(ISD::SHL, DL, VT,
8529                                     V,
8530                                     DAG.getConstant(Log2_32(MulAmt - 1),
8531                                                     MVT::i32)));
8532     } else if (isPowerOf2_32(MulAmt + 1)) {
8533       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8534       Res = DAG.getNode(ISD::SUB, DL, VT,
8535                         DAG.getNode(ISD::SHL, DL, VT,
8536                                     V,
8537                                     DAG.getConstant(Log2_32(MulAmt + 1),
8538                                                     MVT::i32)),
8539                         V);
8540     } else
8541       return SDValue();
8542   } else {
8543     uint64_t MulAmtAbs = -MulAmt;
8544     if (isPowerOf2_32(MulAmtAbs + 1)) {
8545       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8546       Res = DAG.getNode(ISD::SUB, DL, VT,
8547                         V,
8548                         DAG.getNode(ISD::SHL, DL, VT,
8549                                     V,
8550                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8551                                                     MVT::i32)));
8552     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8553       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8554       Res = DAG.getNode(ISD::ADD, DL, VT,
8555                         V,
8556                         DAG.getNode(ISD::SHL, DL, VT,
8557                                     V,
8558                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8559                                                     MVT::i32)));
8560       Res = DAG.getNode(ISD::SUB, DL, VT,
8561                         DAG.getConstant(0, MVT::i32),Res);
8562 
8563     } else
8564       return SDValue();
8565   }
8566 
8567   if (ShiftAmt != 0)
8568     Res = DAG.getNode(ISD::SHL, DL, VT,
8569                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8570 
8571   // Do not add new nodes to DAG combiner worklist.
8572   DCI.CombineTo(N, Res, false);
8573   return SDValue();
8574 }
8575 
8576 static SDValue PerformANDCombine(SDNode *N,
8577                                  TargetLowering::DAGCombinerInfo &DCI,
8578                                  const ARMSubtarget *Subtarget) {
8579 
8580   // Attempt to use immediate-form VBIC
8581   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8582   SDLoc dl(N);
8583   EVT VT = N->getValueType(0);
8584   SelectionDAG &DAG = DCI.DAG;
8585 
8586   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8587     return SDValue();
8588 
8589   APInt SplatBits, SplatUndef;
8590   unsigned SplatBitSize;
8591   bool HasAnyUndefs;
8592   if (BVN &&
8593       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8594     if (SplatBitSize <= 64) {
8595       EVT VbicVT;
8596       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8597                                       SplatUndef.getZExtValue(), SplatBitSize,
8598                                       DAG, VbicVT, VT.is128BitVector(),
8599                                       OtherModImm);
8600       if (Val.getNode()) {
8601         SDValue Input =
8602           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8603         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8604         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8605       }
8606     }
8607   }
8608 
8609   if (!Subtarget->isThumb1Only()) {
8610     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8611     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8612     if (Result.getNode())
8613       return Result;
8614   }
8615 
8616   return SDValue();
8617 }
8618 
8619 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8620 static SDValue PerformORCombine(SDNode *N,
8621                                 TargetLowering::DAGCombinerInfo &DCI,
8622                                 const ARMSubtarget *Subtarget) {
8623   // Attempt to use immediate-form VORR
8624   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8625   SDLoc dl(N);
8626   EVT VT = N->getValueType(0);
8627   SelectionDAG &DAG = DCI.DAG;
8628 
8629   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8630     return SDValue();
8631 
8632   APInt SplatBits, SplatUndef;
8633   unsigned SplatBitSize;
8634   bool HasAnyUndefs;
8635   if (BVN && Subtarget->hasNEON() &&
8636       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8637     if (SplatBitSize <= 64) {
8638       EVT VorrVT;
8639       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8640                                       SplatUndef.getZExtValue(), SplatBitSize,
8641                                       DAG, VorrVT, VT.is128BitVector(),
8642                                       OtherModImm);
8643       if (Val.getNode()) {
8644         SDValue Input =
8645           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8646         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8647         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8648       }
8649     }
8650   }
8651 
8652   if (!Subtarget->isThumb1Only()) {
8653     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8654     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8655     if (Result.getNode())
8656       return Result;
8657   }
8658 
8659   // The code below optimizes (or (and X, Y), Z).
8660   // The AND operand needs to have a single user to make these optimizations
8661   // profitable.
8662   SDValue N0 = N->getOperand(0);
8663   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8664     return SDValue();
8665   SDValue N1 = N->getOperand(1);
8666 
8667   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8668   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8669       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8670     APInt SplatUndef;
8671     unsigned SplatBitSize;
8672     bool HasAnyUndefs;
8673 
8674     APInt SplatBits0, SplatBits1;
8675     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8676     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8677     // Ensure that the second operand of both ands are constants
8678     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8679                                       HasAnyUndefs) && !HasAnyUndefs) {
8680         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8681                                           HasAnyUndefs) && !HasAnyUndefs) {
8682             // Ensure that the bit width of the constants are the same and that
8683             // the splat arguments are logical inverses as per the pattern we
8684             // are trying to simplify.
8685             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8686                 SplatBits0 == ~SplatBits1) {
8687                 // Canonicalize the vector type to make instruction selection
8688                 // simpler.
8689                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8690                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8691                                              N0->getOperand(1),
8692                                              N0->getOperand(0),
8693                                              N1->getOperand(0));
8694                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8695             }
8696         }
8697     }
8698   }
8699 
8700   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8701   // reasonable.
8702 
8703   // BFI is only available on V6T2+
8704   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8705     return SDValue();
8706 
8707   SDLoc DL(N);
8708   // 1) or (and A, mask), val => ARMbfi A, val, mask
8709   //      iff (val & mask) == val
8710   //
8711   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8712   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8713   //          && mask == ~mask2
8714   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8715   //          && ~mask == mask2
8716   //  (i.e., copy a bitfield value into another bitfield of the same width)
8717 
8718   if (VT != MVT::i32)
8719     return SDValue();
8720 
8721   SDValue N00 = N0.getOperand(0);
8722 
8723   // The value and the mask need to be constants so we can verify this is
8724   // actually a bitfield set. If the mask is 0xffff, we can do better
8725   // via a movt instruction, so don't use BFI in that case.
8726   SDValue MaskOp = N0.getOperand(1);
8727   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8728   if (!MaskC)
8729     return SDValue();
8730   unsigned Mask = MaskC->getZExtValue();
8731   if (Mask == 0xffff)
8732     return SDValue();
8733   SDValue Res;
8734   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8735   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8736   if (N1C) {
8737     unsigned Val = N1C->getZExtValue();
8738     if ((Val & ~Mask) != Val)
8739       return SDValue();
8740 
8741     if (ARM::isBitFieldInvertedMask(Mask)) {
8742       Val >>= countTrailingZeros(~Mask);
8743 
8744       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8745                         DAG.getConstant(Val, MVT::i32),
8746                         DAG.getConstant(Mask, MVT::i32));
8747 
8748       // Do not add new nodes to DAG combiner worklist.
8749       DCI.CombineTo(N, Res, false);
8750       return SDValue();
8751     }
8752   } else if (N1.getOpcode() == ISD::AND) {
8753     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8754     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8755     if (!N11C)
8756       return SDValue();
8757     unsigned Mask2 = N11C->getZExtValue();
8758 
8759     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8760     // as is to match.
8761     if (ARM::isBitFieldInvertedMask(Mask) &&
8762         (Mask == ~Mask2)) {
8763       // The pack halfword instruction works better for masks that fit it,
8764       // so use that when it's available.
8765       if (Subtarget->hasT2ExtractPack() &&
8766           (Mask == 0xffff || Mask == 0xffff0000))
8767         return SDValue();
8768       // 2a
8769       unsigned amt = countTrailingZeros(Mask2);
8770       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8771                         DAG.getConstant(amt, MVT::i32));
8772       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8773                         DAG.getConstant(Mask, MVT::i32));
8774       // Do not add new nodes to DAG combiner worklist.
8775       DCI.CombineTo(N, Res, false);
8776       return SDValue();
8777     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8778                (~Mask == Mask2)) {
8779       // The pack halfword instruction works better for masks that fit it,
8780       // so use that when it's available.
8781       if (Subtarget->hasT2ExtractPack() &&
8782           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8783         return SDValue();
8784       // 2b
8785       unsigned lsb = countTrailingZeros(Mask);
8786       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8787                         DAG.getConstant(lsb, MVT::i32));
8788       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8789                         DAG.getConstant(Mask2, MVT::i32));
8790       // Do not add new nodes to DAG combiner worklist.
8791       DCI.CombineTo(N, Res, false);
8792       return SDValue();
8793     }
8794   }
8795 
8796   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8797       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8798       ARM::isBitFieldInvertedMask(~Mask)) {
8799     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8800     // where lsb(mask) == #shamt and masked bits of B are known zero.
8801     SDValue ShAmt = N00.getOperand(1);
8802     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8803     unsigned LSB = countTrailingZeros(Mask);
8804     if (ShAmtC != LSB)
8805       return SDValue();
8806 
8807     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8808                       DAG.getConstant(~Mask, MVT::i32));
8809 
8810     // Do not add new nodes to DAG combiner worklist.
8811     DCI.CombineTo(N, Res, false);
8812   }
8813 
8814   return SDValue();
8815 }
8816 
8817 static SDValue PerformXORCombine(SDNode *N,
8818                                  TargetLowering::DAGCombinerInfo &DCI,
8819                                  const ARMSubtarget *Subtarget) {
8820   EVT VT = N->getValueType(0);
8821   SelectionDAG &DAG = DCI.DAG;
8822 
8823   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8824     return SDValue();
8825 
8826   if (!Subtarget->isThumb1Only()) {
8827     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8828     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8829     if (Result.getNode())
8830       return Result;
8831   }
8832 
8833   return SDValue();
8834 }
8835 
8836 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8837 /// the bits being cleared by the AND are not demanded by the BFI.
8838 static SDValue PerformBFICombine(SDNode *N,
8839                                  TargetLowering::DAGCombinerInfo &DCI) {
8840   SDValue N1 = N->getOperand(1);
8841   if (N1.getOpcode() == ISD::AND) {
8842     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8843     if (!N11C)
8844       return SDValue();
8845     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8846     unsigned LSB = countTrailingZeros(~InvMask);
8847     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8848     unsigned Mask = (1 << Width)-1;
8849     unsigned Mask2 = N11C->getZExtValue();
8850     if ((Mask & (~Mask2)) == 0)
8851       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8852                              N->getOperand(0), N1.getOperand(0),
8853                              N->getOperand(2));
8854   }
8855   return SDValue();
8856 }
8857 
8858 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8859 /// ARMISD::VMOVRRD.
8860 static SDValue PerformVMOVRRDCombine(SDNode *N,
8861                                      TargetLowering::DAGCombinerInfo &DCI) {
8862   // vmovrrd(vmovdrr x, y) -> x,y
8863   SDValue InDouble = N->getOperand(0);
8864   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8865     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8866 
8867   // vmovrrd(load f64) -> (load i32), (load i32)
8868   SDNode *InNode = InDouble.getNode();
8869   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8870       InNode->getValueType(0) == MVT::f64 &&
8871       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8872       !cast<LoadSDNode>(InNode)->isVolatile()) {
8873     // TODO: Should this be done for non-FrameIndex operands?
8874     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8875 
8876     SelectionDAG &DAG = DCI.DAG;
8877     SDLoc DL(LD);
8878     SDValue BasePtr = LD->getBasePtr();
8879     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8880                                  LD->getPointerInfo(), LD->isVolatile(),
8881                                  LD->isNonTemporal(), LD->isInvariant(),
8882                                  LD->getAlignment());
8883 
8884     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8885                                     DAG.getConstant(4, MVT::i32));
8886     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8887                                  LD->getPointerInfo(), LD->isVolatile(),
8888                                  LD->isNonTemporal(), LD->isInvariant(),
8889                                  std::min(4U, LD->getAlignment() / 2));
8890 
8891     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8892     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8893     DCI.RemoveFromWorklist(LD);
8894     DAG.DeleteNode(LD);
8895     return Result;
8896   }
8897 
8898   return SDValue();
8899 }
8900 
8901 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8902 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8903 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8904   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8905   SDValue Op0 = N->getOperand(0);
8906   SDValue Op1 = N->getOperand(1);
8907   if (Op0.getOpcode() == ISD::BITCAST)
8908     Op0 = Op0.getOperand(0);
8909   if (Op1.getOpcode() == ISD::BITCAST)
8910     Op1 = Op1.getOperand(0);
8911   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8912       Op0.getNode() == Op1.getNode() &&
8913       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8914     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8915                        N->getValueType(0), Op0.getOperand(0));
8916   return SDValue();
8917 }
8918 
8919 /// PerformSTORECombine - Target-specific dag combine xforms for
8920 /// ISD::STORE.
8921 static SDValue PerformSTORECombine(SDNode *N,
8922                                    TargetLowering::DAGCombinerInfo &DCI) {
8923   StoreSDNode *St = cast<StoreSDNode>(N);
8924   if (St->isVolatile())
8925     return SDValue();
8926 
8927   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8928   // pack all of the elements in one place.  Next, store to memory in fewer
8929   // chunks.
8930   SDValue StVal = St->getValue();
8931   EVT VT = StVal.getValueType();
8932   if (St->isTruncatingStore() && VT.isVector()) {
8933     SelectionDAG &DAG = DCI.DAG;
8934     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8935     EVT StVT = St->getMemoryVT();
8936     unsigned NumElems = VT.getVectorNumElements();
8937     assert(StVT != VT && "Cannot truncate to the same type");
8938     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8939     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8940 
8941     // From, To sizes and ElemCount must be pow of two
8942     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8943 
8944     // We are going to use the original vector elt for storing.
8945     // Accumulated smaller vector elements must be a multiple of the store size.
8946     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8947 
8948     unsigned SizeRatio  = FromEltSz / ToEltSz;
8949     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8950 
8951     // Create a type on which we perform the shuffle.
8952     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8953                                      NumElems*SizeRatio);
8954     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8955 
8956     SDLoc DL(St);
8957     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8958     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8959     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8960 
8961     // Can't shuffle using an illegal type.
8962     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8963 
8964     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8965                                 DAG.getUNDEF(WideVec.getValueType()),
8966                                 ShuffleVec.data());
8967     // At this point all of the data is stored at the bottom of the
8968     // register. We now need to save it to mem.
8969 
8970     // Find the largest store unit
8971     MVT StoreType = MVT::i8;
8972     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8973          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8974       MVT Tp = (MVT::SimpleValueType)tp;
8975       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8976         StoreType = Tp;
8977     }
8978     // Didn't find a legal store type.
8979     if (!TLI.isTypeLegal(StoreType))
8980       return SDValue();
8981 
8982     // Bitcast the original vector into a vector of store-size units
8983     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8984             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8985     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8986     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8987     SmallVector<SDValue, 8> Chains;
8988     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8989                                         TLI.getPointerTy());
8990     SDValue BasePtr = St->getBasePtr();
8991 
8992     // Perform one or more big stores into memory.
8993     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8994     for (unsigned I = 0; I < E; I++) {
8995       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8996                                    StoreType, ShuffWide,
8997                                    DAG.getIntPtrConstant(I));
8998       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8999                                 St->getPointerInfo(), St->isVolatile(),
9000                                 St->isNonTemporal(), St->getAlignment());
9001       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9002                             Increment);
9003       Chains.push_back(Ch);
9004     }
9005     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
9006                        Chains.size());
9007   }
9008 
9009   if (!ISD::isNormalStore(St))
9010     return SDValue();
9011 
9012   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9013   // ARM stores of arguments in the same cache line.
9014   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9015       StVal.getNode()->hasOneUse()) {
9016     SelectionDAG  &DAG = DCI.DAG;
9017     SDLoc DL(St);
9018     SDValue BasePtr = St->getBasePtr();
9019     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9020                                   StVal.getNode()->getOperand(0), BasePtr,
9021                                   St->getPointerInfo(), St->isVolatile(),
9022                                   St->isNonTemporal(), St->getAlignment());
9023 
9024     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9025                                     DAG.getConstant(4, MVT::i32));
9026     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
9027                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9028                         St->isNonTemporal(),
9029                         std::min(4U, St->getAlignment() / 2));
9030   }
9031 
9032   if (StVal.getValueType() != MVT::i64 ||
9033       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9034     return SDValue();
9035 
9036   // Bitcast an i64 store extracted from a vector to f64.
9037   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9038   SelectionDAG &DAG = DCI.DAG;
9039   SDLoc dl(StVal);
9040   SDValue IntVec = StVal.getOperand(0);
9041   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9042                                  IntVec.getValueType().getVectorNumElements());
9043   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9044   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9045                                Vec, StVal.getOperand(1));
9046   dl = SDLoc(N);
9047   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9048   // Make the DAGCombiner fold the bitcasts.
9049   DCI.AddToWorklist(Vec.getNode());
9050   DCI.AddToWorklist(ExtElt.getNode());
9051   DCI.AddToWorklist(V.getNode());
9052   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9053                       St->getPointerInfo(), St->isVolatile(),
9054                       St->isNonTemporal(), St->getAlignment(),
9055                       St->getTBAAInfo());
9056 }
9057 
9058 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9059 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
9060 /// i64 vector to have f64 elements, since the value can then be loaded
9061 /// directly into a VFP register.
9062 static bool hasNormalLoadOperand(SDNode *N) {
9063   unsigned NumElts = N->getValueType(0).getVectorNumElements();
9064   for (unsigned i = 0; i < NumElts; ++i) {
9065     SDNode *Elt = N->getOperand(i).getNode();
9066     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9067       return true;
9068   }
9069   return false;
9070 }
9071 
9072 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9073 /// ISD::BUILD_VECTOR.
9074 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9075                                           TargetLowering::DAGCombinerInfo &DCI){
9076   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9077   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
9078   // into a pair of GPRs, which is fine when the value is used as a scalar,
9079   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9080   SelectionDAG &DAG = DCI.DAG;
9081   if (N->getNumOperands() == 2) {
9082     SDValue RV = PerformVMOVDRRCombine(N, DAG);
9083     if (RV.getNode())
9084       return RV;
9085   }
9086 
9087   // Load i64 elements as f64 values so that type legalization does not split
9088   // them up into i32 values.
9089   EVT VT = N->getValueType(0);
9090   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9091     return SDValue();
9092   SDLoc dl(N);
9093   SmallVector<SDValue, 8> Ops;
9094   unsigned NumElts = VT.getVectorNumElements();
9095   for (unsigned i = 0; i < NumElts; ++i) {
9096     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9097     Ops.push_back(V);
9098     // Make the DAGCombiner fold the bitcast.
9099     DCI.AddToWorklist(V.getNode());
9100   }
9101   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9102   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
9103   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9104 }
9105 
9106 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9107 static SDValue
9108 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9109   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9110   // At that time, we may have inserted bitcasts from integer to float.
9111   // If these bitcasts have survived DAGCombine, change the lowering of this
9112   // BUILD_VECTOR in something more vector friendly, i.e., that does not
9113   // force to use floating point types.
9114 
9115   // Make sure we can change the type of the vector.
9116   // This is possible iff:
9117   // 1. The vector is only used in a bitcast to a integer type. I.e.,
9118   //    1.1. Vector is used only once.
9119   //    1.2. Use is a bit convert to an integer type.
9120   // 2. The size of its operands are 32-bits (64-bits are not legal).
9121   EVT VT = N->getValueType(0);
9122   EVT EltVT = VT.getVectorElementType();
9123 
9124   // Check 1.1. and 2.
9125   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9126     return SDValue();
9127 
9128   // By construction, the input type must be float.
9129   assert(EltVT == MVT::f32 && "Unexpected type!");
9130 
9131   // Check 1.2.
9132   SDNode *Use = *N->use_begin();
9133   if (Use->getOpcode() != ISD::BITCAST ||
9134       Use->getValueType(0).isFloatingPoint())
9135     return SDValue();
9136 
9137   // Check profitability.
9138   // Model is, if more than half of the relevant operands are bitcast from
9139   // i32, turn the build_vector into a sequence of insert_vector_elt.
9140   // Relevant operands are everything that is not statically
9141   // (i.e., at compile time) bitcasted.
9142   unsigned NumOfBitCastedElts = 0;
9143   unsigned NumElts = VT.getVectorNumElements();
9144   unsigned NumOfRelevantElts = NumElts;
9145   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9146     SDValue Elt = N->getOperand(Idx);
9147     if (Elt->getOpcode() == ISD::BITCAST) {
9148       // Assume only bit cast to i32 will go away.
9149       if (Elt->getOperand(0).getValueType() == MVT::i32)
9150         ++NumOfBitCastedElts;
9151     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9152       // Constants are statically casted, thus do not count them as
9153       // relevant operands.
9154       --NumOfRelevantElts;
9155   }
9156 
9157   // Check if more than half of the elements require a non-free bitcast.
9158   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9159     return SDValue();
9160 
9161   SelectionDAG &DAG = DCI.DAG;
9162   // Create the new vector type.
9163   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9164   // Check if the type is legal.
9165   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9166   if (!TLI.isTypeLegal(VecVT))
9167     return SDValue();
9168 
9169   // Combine:
9170   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9171   // => BITCAST INSERT_VECTOR_ELT
9172   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9173   //                      (BITCAST EN), N.
9174   SDValue Vec = DAG.getUNDEF(VecVT);
9175   SDLoc dl(N);
9176   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9177     SDValue V = N->getOperand(Idx);
9178     if (V.getOpcode() == ISD::UNDEF)
9179       continue;
9180     if (V.getOpcode() == ISD::BITCAST &&
9181         V->getOperand(0).getValueType() == MVT::i32)
9182       // Fold obvious case.
9183       V = V.getOperand(0);
9184     else {
9185       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9186       // Make the DAGCombiner fold the bitcasts.
9187       DCI.AddToWorklist(V.getNode());
9188     }
9189     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
9190     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9191   }
9192   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9193   // Make the DAGCombiner fold the bitcasts.
9194   DCI.AddToWorklist(Vec.getNode());
9195   return Vec;
9196 }
9197 
9198 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9199 /// ISD::INSERT_VECTOR_ELT.
9200 static SDValue PerformInsertEltCombine(SDNode *N,
9201                                        TargetLowering::DAGCombinerInfo &DCI) {
9202   // Bitcast an i64 load inserted into a vector to f64.
9203   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9204   EVT VT = N->getValueType(0);
9205   SDNode *Elt = N->getOperand(1).getNode();
9206   if (VT.getVectorElementType() != MVT::i64 ||
9207       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9208     return SDValue();
9209 
9210   SelectionDAG &DAG = DCI.DAG;
9211   SDLoc dl(N);
9212   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9213                                  VT.getVectorNumElements());
9214   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9215   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9216   // Make the DAGCombiner fold the bitcasts.
9217   DCI.AddToWorklist(Vec.getNode());
9218   DCI.AddToWorklist(V.getNode());
9219   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9220                                Vec, V, N->getOperand(2));
9221   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9222 }
9223 
9224 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9225 /// ISD::VECTOR_SHUFFLE.
9226 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9227   // The LLVM shufflevector instruction does not require the shuffle mask
9228   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9229   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
9230   // operands do not match the mask length, they are extended by concatenating
9231   // them with undef vectors.  That is probably the right thing for other
9232   // targets, but for NEON it is better to concatenate two double-register
9233   // size vector operands into a single quad-register size vector.  Do that
9234   // transformation here:
9235   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
9236   //   shuffle(concat(v1, v2), undef)
9237   SDValue Op0 = N->getOperand(0);
9238   SDValue Op1 = N->getOperand(1);
9239   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9240       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9241       Op0.getNumOperands() != 2 ||
9242       Op1.getNumOperands() != 2)
9243     return SDValue();
9244   SDValue Concat0Op1 = Op0.getOperand(1);
9245   SDValue Concat1Op1 = Op1.getOperand(1);
9246   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9247       Concat1Op1.getOpcode() != ISD::UNDEF)
9248     return SDValue();
9249   // Skip the transformation if any of the types are illegal.
9250   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9251   EVT VT = N->getValueType(0);
9252   if (!TLI.isTypeLegal(VT) ||
9253       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9254       !TLI.isTypeLegal(Concat1Op1.getValueType()))
9255     return SDValue();
9256 
9257   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9258                                   Op0.getOperand(0), Op1.getOperand(0));
9259   // Translate the shuffle mask.
9260   SmallVector<int, 16> NewMask;
9261   unsigned NumElts = VT.getVectorNumElements();
9262   unsigned HalfElts = NumElts/2;
9263   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9264   for (unsigned n = 0; n < NumElts; ++n) {
9265     int MaskElt = SVN->getMaskElt(n);
9266     int NewElt = -1;
9267     if (MaskElt < (int)HalfElts)
9268       NewElt = MaskElt;
9269     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9270       NewElt = HalfElts + MaskElt - NumElts;
9271     NewMask.push_back(NewElt);
9272   }
9273   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9274                               DAG.getUNDEF(VT), NewMask.data());
9275 }
9276 
9277 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
9278 /// NEON load/store intrinsics to merge base address updates.
9279 static SDValue CombineBaseUpdate(SDNode *N,
9280                                  TargetLowering::DAGCombinerInfo &DCI) {
9281   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9282     return SDValue();
9283 
9284   SelectionDAG &DAG = DCI.DAG;
9285   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9286                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9287   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
9288   SDValue Addr = N->getOperand(AddrOpIdx);
9289 
9290   // Search for a use of the address operand that is an increment.
9291   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9292          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9293     SDNode *User = *UI;
9294     if (User->getOpcode() != ISD::ADD ||
9295         UI.getUse().getResNo() != Addr.getResNo())
9296       continue;
9297 
9298     // Check that the add is independent of the load/store.  Otherwise, folding
9299     // it would create a cycle.
9300     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9301       continue;
9302 
9303     // Find the new opcode for the updating load/store.
9304     bool isLoad = true;
9305     bool isLaneOp = false;
9306     unsigned NewOpc = 0;
9307     unsigned NumVecs = 0;
9308     if (isIntrinsic) {
9309       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9310       switch (IntNo) {
9311       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9312       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9313         NumVecs = 1; break;
9314       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9315         NumVecs = 2; break;
9316       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9317         NumVecs = 3; break;
9318       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9319         NumVecs = 4; break;
9320       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9321         NumVecs = 2; isLaneOp = true; break;
9322       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9323         NumVecs = 3; isLaneOp = true; break;
9324       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9325         NumVecs = 4; isLaneOp = true; break;
9326       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9327         NumVecs = 1; isLoad = false; break;
9328       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9329         NumVecs = 2; isLoad = false; break;
9330       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9331         NumVecs = 3; isLoad = false; break;
9332       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9333         NumVecs = 4; isLoad = false; break;
9334       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9335         NumVecs = 2; isLoad = false; isLaneOp = true; break;
9336       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9337         NumVecs = 3; isLoad = false; isLaneOp = true; break;
9338       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9339         NumVecs = 4; isLoad = false; isLaneOp = true; break;
9340       }
9341     } else {
9342       isLaneOp = true;
9343       switch (N->getOpcode()) {
9344       default: llvm_unreachable("unexpected opcode for Neon base update");
9345       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9346       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9347       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9348       }
9349     }
9350 
9351     // Find the size of memory referenced by the load/store.
9352     EVT VecTy;
9353     if (isLoad)
9354       VecTy = N->getValueType(0);
9355     else
9356       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9357     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9358     if (isLaneOp)
9359       NumBytes /= VecTy.getVectorNumElements();
9360 
9361     // If the increment is a constant, it must match the memory ref size.
9362     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9363     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9364       uint64_t IncVal = CInc->getZExtValue();
9365       if (IncVal != NumBytes)
9366         continue;
9367     } else if (NumBytes >= 3 * 16) {
9368       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9369       // separate instructions that make it harder to use a non-constant update.
9370       continue;
9371     }
9372 
9373     // Create the new updating load/store node.
9374     EVT Tys[6];
9375     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
9376     unsigned n;
9377     for (n = 0; n < NumResultVecs; ++n)
9378       Tys[n] = VecTy;
9379     Tys[n++] = MVT::i32;
9380     Tys[n] = MVT::Other;
9381     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
9382     SmallVector<SDValue, 8> Ops;
9383     Ops.push_back(N->getOperand(0)); // incoming chain
9384     Ops.push_back(N->getOperand(AddrOpIdx));
9385     Ops.push_back(Inc);
9386     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
9387       Ops.push_back(N->getOperand(i));
9388     }
9389     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9390     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9391                                            Ops.data(), Ops.size(),
9392                                            MemInt->getMemoryVT(),
9393                                            MemInt->getMemOperand());
9394 
9395     // Update the uses.
9396     std::vector<SDValue> NewResults;
9397     for (unsigned i = 0; i < NumResultVecs; ++i) {
9398       NewResults.push_back(SDValue(UpdN.getNode(), i));
9399     }
9400     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9401     DCI.CombineTo(N, NewResults);
9402     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9403 
9404     break;
9405   }
9406   return SDValue();
9407 }
9408 
9409 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9410 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9411 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9412 /// return true.
9413 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9414   SelectionDAG &DAG = DCI.DAG;
9415   EVT VT = N->getValueType(0);
9416   // vldN-dup instructions only support 64-bit vectors for N > 1.
9417   if (!VT.is64BitVector())
9418     return false;
9419 
9420   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9421   SDNode *VLD = N->getOperand(0).getNode();
9422   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9423     return false;
9424   unsigned NumVecs = 0;
9425   unsigned NewOpc = 0;
9426   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9427   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9428     NumVecs = 2;
9429     NewOpc = ARMISD::VLD2DUP;
9430   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9431     NumVecs = 3;
9432     NewOpc = ARMISD::VLD3DUP;
9433   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9434     NumVecs = 4;
9435     NewOpc = ARMISD::VLD4DUP;
9436   } else {
9437     return false;
9438   }
9439 
9440   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9441   // numbers match the load.
9442   unsigned VLDLaneNo =
9443     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9444   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9445        UI != UE; ++UI) {
9446     // Ignore uses of the chain result.
9447     if (UI.getUse().getResNo() == NumVecs)
9448       continue;
9449     SDNode *User = *UI;
9450     if (User->getOpcode() != ARMISD::VDUPLANE ||
9451         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9452       return false;
9453   }
9454 
9455   // Create the vldN-dup node.
9456   EVT Tys[5];
9457   unsigned n;
9458   for (n = 0; n < NumVecs; ++n)
9459     Tys[n] = VT;
9460   Tys[n] = MVT::Other;
9461   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
9462   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9463   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9464   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9465                                            Ops, 2, VLDMemInt->getMemoryVT(),
9466                                            VLDMemInt->getMemOperand());
9467 
9468   // Update the uses.
9469   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9470        UI != UE; ++UI) {
9471     unsigned ResNo = UI.getUse().getResNo();
9472     // Ignore uses of the chain result.
9473     if (ResNo == NumVecs)
9474       continue;
9475     SDNode *User = *UI;
9476     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9477   }
9478 
9479   // Now the vldN-lane intrinsic is dead except for its chain result.
9480   // Update uses of the chain.
9481   std::vector<SDValue> VLDDupResults;
9482   for (unsigned n = 0; n < NumVecs; ++n)
9483     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9484   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9485   DCI.CombineTo(VLD, VLDDupResults);
9486 
9487   return true;
9488 }
9489 
9490 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9491 /// ARMISD::VDUPLANE.
9492 static SDValue PerformVDUPLANECombine(SDNode *N,
9493                                       TargetLowering::DAGCombinerInfo &DCI) {
9494   SDValue Op = N->getOperand(0);
9495 
9496   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9497   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9498   if (CombineVLDDUP(N, DCI))
9499     return SDValue(N, 0);
9500 
9501   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9502   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9503   while (Op.getOpcode() == ISD::BITCAST)
9504     Op = Op.getOperand(0);
9505   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9506     return SDValue();
9507 
9508   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9509   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9510   // The canonical VMOV for a zero vector uses a 32-bit element size.
9511   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9512   unsigned EltBits;
9513   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9514     EltSize = 8;
9515   EVT VT = N->getValueType(0);
9516   if (EltSize > VT.getVectorElementType().getSizeInBits())
9517     return SDValue();
9518 
9519   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9520 }
9521 
9522 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9523 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9524 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9525 {
9526   integerPart cN;
9527   integerPart c0 = 0;
9528   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9529        I != E; I++) {
9530     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9531     if (!C)
9532       return false;
9533 
9534     bool isExact;
9535     APFloat APF = C->getValueAPF();
9536     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9537         != APFloat::opOK || !isExact)
9538       return false;
9539 
9540     c0 = (I == 0) ? cN : c0;
9541     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9542       return false;
9543   }
9544   C = c0;
9545   return true;
9546 }
9547 
9548 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9549 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9550 /// when the VMUL has a constant operand that is a power of 2.
9551 ///
9552 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9553 ///  vmul.f32        d16, d17, d16
9554 ///  vcvt.s32.f32    d16, d16
9555 /// becomes:
9556 ///  vcvt.s32.f32    d16, d16, #3
9557 static SDValue PerformVCVTCombine(SDNode *N,
9558                                   TargetLowering::DAGCombinerInfo &DCI,
9559                                   const ARMSubtarget *Subtarget) {
9560   SelectionDAG &DAG = DCI.DAG;
9561   SDValue Op = N->getOperand(0);
9562 
9563   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9564       Op.getOpcode() != ISD::FMUL)
9565     return SDValue();
9566 
9567   uint64_t C;
9568   SDValue N0 = Op->getOperand(0);
9569   SDValue ConstVec = Op->getOperand(1);
9570   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9571 
9572   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9573       !isConstVecPow2(ConstVec, isSigned, C))
9574     return SDValue();
9575 
9576   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9577   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9578   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9579     // These instructions only exist converting from f32 to i32. We can handle
9580     // smaller integers by generating an extra truncate, but larger ones would
9581     // be lossy.
9582     return SDValue();
9583   }
9584 
9585   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9586     Intrinsic::arm_neon_vcvtfp2fxu;
9587   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9588   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9589                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9590                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9591                                  DAG.getConstant(Log2_64(C), MVT::i32));
9592 
9593   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9594     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9595 
9596   return FixConv;
9597 }
9598 
9599 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9600 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9601 /// when the VDIV has a constant operand that is a power of 2.
9602 ///
9603 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9604 ///  vcvt.f32.s32    d16, d16
9605 ///  vdiv.f32        d16, d17, d16
9606 /// becomes:
9607 ///  vcvt.f32.s32    d16, d16, #3
9608 static SDValue PerformVDIVCombine(SDNode *N,
9609                                   TargetLowering::DAGCombinerInfo &DCI,
9610                                   const ARMSubtarget *Subtarget) {
9611   SelectionDAG &DAG = DCI.DAG;
9612   SDValue Op = N->getOperand(0);
9613   unsigned OpOpcode = Op.getNode()->getOpcode();
9614 
9615   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9616       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9617     return SDValue();
9618 
9619   uint64_t C;
9620   SDValue ConstVec = N->getOperand(1);
9621   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9622 
9623   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9624       !isConstVecPow2(ConstVec, isSigned, C))
9625     return SDValue();
9626 
9627   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9628   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9629   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9630     // These instructions only exist converting from i32 to f32. We can handle
9631     // smaller integers by generating an extra extend, but larger ones would
9632     // be lossy.
9633     return SDValue();
9634   }
9635 
9636   SDValue ConvInput = Op.getOperand(0);
9637   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9638   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9639     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9640                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9641                             ConvInput);
9642 
9643   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9644     Intrinsic::arm_neon_vcvtfxu2fp;
9645   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9646                      Op.getValueType(),
9647                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9648                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9649 }
9650 
9651 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9652 /// operand of a vector shift operation, where all the elements of the
9653 /// build_vector must have the same constant integer value.
9654 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9655   // Ignore bit_converts.
9656   while (Op.getOpcode() == ISD::BITCAST)
9657     Op = Op.getOperand(0);
9658   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9659   APInt SplatBits, SplatUndef;
9660   unsigned SplatBitSize;
9661   bool HasAnyUndefs;
9662   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9663                                       HasAnyUndefs, ElementBits) ||
9664       SplatBitSize > ElementBits)
9665     return false;
9666   Cnt = SplatBits.getSExtValue();
9667   return true;
9668 }
9669 
9670 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9671 /// operand of a vector shift left operation.  That value must be in the range:
9672 ///   0 <= Value < ElementBits for a left shift; or
9673 ///   0 <= Value <= ElementBits for a long left shift.
9674 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9675   assert(VT.isVector() && "vector shift count is not a vector type");
9676   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9677   if (! getVShiftImm(Op, ElementBits, Cnt))
9678     return false;
9679   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9680 }
9681 
9682 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9683 /// operand of a vector shift right operation.  For a shift opcode, the value
9684 /// is positive, but for an intrinsic the value count must be negative. The
9685 /// absolute value must be in the range:
9686 ///   1 <= |Value| <= ElementBits for a right shift; or
9687 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9688 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9689                          int64_t &Cnt) {
9690   assert(VT.isVector() && "vector shift count is not a vector type");
9691   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9692   if (! getVShiftImm(Op, ElementBits, Cnt))
9693     return false;
9694   if (isIntrinsic)
9695     Cnt = -Cnt;
9696   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9697 }
9698 
9699 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9700 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9701   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9702   switch (IntNo) {
9703   default:
9704     // Don't do anything for most intrinsics.
9705     break;
9706 
9707   // Vector shifts: check for immediate versions and lower them.
9708   // Note: This is done during DAG combining instead of DAG legalizing because
9709   // the build_vectors for 64-bit vector element shift counts are generally
9710   // not legal, and it is hard to see their values after they get legalized to
9711   // loads from a constant pool.
9712   case Intrinsic::arm_neon_vshifts:
9713   case Intrinsic::arm_neon_vshiftu:
9714   case Intrinsic::arm_neon_vrshifts:
9715   case Intrinsic::arm_neon_vrshiftu:
9716   case Intrinsic::arm_neon_vrshiftn:
9717   case Intrinsic::arm_neon_vqshifts:
9718   case Intrinsic::arm_neon_vqshiftu:
9719   case Intrinsic::arm_neon_vqshiftsu:
9720   case Intrinsic::arm_neon_vqshiftns:
9721   case Intrinsic::arm_neon_vqshiftnu:
9722   case Intrinsic::arm_neon_vqshiftnsu:
9723   case Intrinsic::arm_neon_vqrshiftns:
9724   case Intrinsic::arm_neon_vqrshiftnu:
9725   case Intrinsic::arm_neon_vqrshiftnsu: {
9726     EVT VT = N->getOperand(1).getValueType();
9727     int64_t Cnt;
9728     unsigned VShiftOpc = 0;
9729 
9730     switch (IntNo) {
9731     case Intrinsic::arm_neon_vshifts:
9732     case Intrinsic::arm_neon_vshiftu:
9733       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9734         VShiftOpc = ARMISD::VSHL;
9735         break;
9736       }
9737       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9738         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9739                      ARMISD::VSHRs : ARMISD::VSHRu);
9740         break;
9741       }
9742       return SDValue();
9743 
9744     case Intrinsic::arm_neon_vrshifts:
9745     case Intrinsic::arm_neon_vrshiftu:
9746       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9747         break;
9748       return SDValue();
9749 
9750     case Intrinsic::arm_neon_vqshifts:
9751     case Intrinsic::arm_neon_vqshiftu:
9752       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9753         break;
9754       return SDValue();
9755 
9756     case Intrinsic::arm_neon_vqshiftsu:
9757       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9758         break;
9759       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9760 
9761     case Intrinsic::arm_neon_vrshiftn:
9762     case Intrinsic::arm_neon_vqshiftns:
9763     case Intrinsic::arm_neon_vqshiftnu:
9764     case Intrinsic::arm_neon_vqshiftnsu:
9765     case Intrinsic::arm_neon_vqrshiftns:
9766     case Intrinsic::arm_neon_vqrshiftnu:
9767     case Intrinsic::arm_neon_vqrshiftnsu:
9768       // Narrowing shifts require an immediate right shift.
9769       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9770         break;
9771       llvm_unreachable("invalid shift count for narrowing vector shift "
9772                        "intrinsic");
9773 
9774     default:
9775       llvm_unreachable("unhandled vector shift");
9776     }
9777 
9778     switch (IntNo) {
9779     case Intrinsic::arm_neon_vshifts:
9780     case Intrinsic::arm_neon_vshiftu:
9781       // Opcode already set above.
9782       break;
9783     case Intrinsic::arm_neon_vrshifts:
9784       VShiftOpc = ARMISD::VRSHRs; break;
9785     case Intrinsic::arm_neon_vrshiftu:
9786       VShiftOpc = ARMISD::VRSHRu; break;
9787     case Intrinsic::arm_neon_vrshiftn:
9788       VShiftOpc = ARMISD::VRSHRN; break;
9789     case Intrinsic::arm_neon_vqshifts:
9790       VShiftOpc = ARMISD::VQSHLs; break;
9791     case Intrinsic::arm_neon_vqshiftu:
9792       VShiftOpc = ARMISD::VQSHLu; break;
9793     case Intrinsic::arm_neon_vqshiftsu:
9794       VShiftOpc = ARMISD::VQSHLsu; break;
9795     case Intrinsic::arm_neon_vqshiftns:
9796       VShiftOpc = ARMISD::VQSHRNs; break;
9797     case Intrinsic::arm_neon_vqshiftnu:
9798       VShiftOpc = ARMISD::VQSHRNu; break;
9799     case Intrinsic::arm_neon_vqshiftnsu:
9800       VShiftOpc = ARMISD::VQSHRNsu; break;
9801     case Intrinsic::arm_neon_vqrshiftns:
9802       VShiftOpc = ARMISD::VQRSHRNs; break;
9803     case Intrinsic::arm_neon_vqrshiftnu:
9804       VShiftOpc = ARMISD::VQRSHRNu; break;
9805     case Intrinsic::arm_neon_vqrshiftnsu:
9806       VShiftOpc = ARMISD::VQRSHRNsu; break;
9807     }
9808 
9809     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9810                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9811   }
9812 
9813   case Intrinsic::arm_neon_vshiftins: {
9814     EVT VT = N->getOperand(1).getValueType();
9815     int64_t Cnt;
9816     unsigned VShiftOpc = 0;
9817 
9818     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9819       VShiftOpc = ARMISD::VSLI;
9820     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9821       VShiftOpc = ARMISD::VSRI;
9822     else {
9823       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9824     }
9825 
9826     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9827                        N->getOperand(1), N->getOperand(2),
9828                        DAG.getConstant(Cnt, MVT::i32));
9829   }
9830 
9831   case Intrinsic::arm_neon_vqrshifts:
9832   case Intrinsic::arm_neon_vqrshiftu:
9833     // No immediate versions of these to check for.
9834     break;
9835   }
9836 
9837   return SDValue();
9838 }
9839 
9840 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9841 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9842 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9843 /// vector element shift counts are generally not legal, and it is hard to see
9844 /// their values after they get legalized to loads from a constant pool.
9845 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9846                                    const ARMSubtarget *ST) {
9847   EVT VT = N->getValueType(0);
9848   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9849     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9850     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9851     SDValue N1 = N->getOperand(1);
9852     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9853       SDValue N0 = N->getOperand(0);
9854       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9855           DAG.MaskedValueIsZero(N0.getOperand(0),
9856                                 APInt::getHighBitsSet(32, 16)))
9857         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9858     }
9859   }
9860 
9861   // Nothing to be done for scalar shifts.
9862   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9863   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9864     return SDValue();
9865 
9866   assert(ST->hasNEON() && "unexpected vector shift");
9867   int64_t Cnt;
9868 
9869   switch (N->getOpcode()) {
9870   default: llvm_unreachable("unexpected shift opcode");
9871 
9872   case ISD::SHL:
9873     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9874       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9875                          DAG.getConstant(Cnt, MVT::i32));
9876     break;
9877 
9878   case ISD::SRA:
9879   case ISD::SRL:
9880     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9881       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9882                             ARMISD::VSHRs : ARMISD::VSHRu);
9883       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9884                          DAG.getConstant(Cnt, MVT::i32));
9885     }
9886   }
9887   return SDValue();
9888 }
9889 
9890 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9891 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9892 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9893                                     const ARMSubtarget *ST) {
9894   SDValue N0 = N->getOperand(0);
9895 
9896   // Check for sign- and zero-extensions of vector extract operations of 8-
9897   // and 16-bit vector elements.  NEON supports these directly.  They are
9898   // handled during DAG combining because type legalization will promote them
9899   // to 32-bit types and it is messy to recognize the operations after that.
9900   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9901     SDValue Vec = N0.getOperand(0);
9902     SDValue Lane = N0.getOperand(1);
9903     EVT VT = N->getValueType(0);
9904     EVT EltVT = N0.getValueType();
9905     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9906 
9907     if (VT == MVT::i32 &&
9908         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9909         TLI.isTypeLegal(Vec.getValueType()) &&
9910         isa<ConstantSDNode>(Lane)) {
9911 
9912       unsigned Opc = 0;
9913       switch (N->getOpcode()) {
9914       default: llvm_unreachable("unexpected opcode");
9915       case ISD::SIGN_EXTEND:
9916         Opc = ARMISD::VGETLANEs;
9917         break;
9918       case ISD::ZERO_EXTEND:
9919       case ISD::ANY_EXTEND:
9920         Opc = ARMISD::VGETLANEu;
9921         break;
9922       }
9923       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9924     }
9925   }
9926 
9927   return SDValue();
9928 }
9929 
9930 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9931 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9932 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9933                                        const ARMSubtarget *ST) {
9934   // If the target supports NEON, try to use vmax/vmin instructions for f32
9935   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9936   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9937   // a NaN; only do the transformation when it matches that behavior.
9938 
9939   // For now only do this when using NEON for FP operations; if using VFP, it
9940   // is not obvious that the benefit outweighs the cost of switching to the
9941   // NEON pipeline.
9942   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9943       N->getValueType(0) != MVT::f32)
9944     return SDValue();
9945 
9946   SDValue CondLHS = N->getOperand(0);
9947   SDValue CondRHS = N->getOperand(1);
9948   SDValue LHS = N->getOperand(2);
9949   SDValue RHS = N->getOperand(3);
9950   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9951 
9952   unsigned Opcode = 0;
9953   bool IsReversed;
9954   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9955     IsReversed = false; // x CC y ? x : y
9956   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9957     IsReversed = true ; // x CC y ? y : x
9958   } else {
9959     return SDValue();
9960   }
9961 
9962   bool IsUnordered;
9963   switch (CC) {
9964   default: break;
9965   case ISD::SETOLT:
9966   case ISD::SETOLE:
9967   case ISD::SETLT:
9968   case ISD::SETLE:
9969   case ISD::SETULT:
9970   case ISD::SETULE:
9971     // If LHS is NaN, an ordered comparison will be false and the result will
9972     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9973     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9974     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9975     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9976       break;
9977     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9978     // will return -0, so vmin can only be used for unsafe math or if one of
9979     // the operands is known to be nonzero.
9980     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9981         !DAG.getTarget().Options.UnsafeFPMath &&
9982         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9983       break;
9984     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9985     break;
9986 
9987   case ISD::SETOGT:
9988   case ISD::SETOGE:
9989   case ISD::SETGT:
9990   case ISD::SETGE:
9991   case ISD::SETUGT:
9992   case ISD::SETUGE:
9993     // If LHS is NaN, an ordered comparison will be false and the result will
9994     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9995     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9996     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9997     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9998       break;
9999     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
10000     // will return +0, so vmax can only be used for unsafe math or if one of
10001     // the operands is known to be nonzero.
10002     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
10003         !DAG.getTarget().Options.UnsafeFPMath &&
10004         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10005       break;
10006     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
10007     break;
10008   }
10009 
10010   if (!Opcode)
10011     return SDValue();
10012   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
10013 }
10014 
10015 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10016 SDValue
10017 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10018   SDValue Cmp = N->getOperand(4);
10019   if (Cmp.getOpcode() != ARMISD::CMPZ)
10020     // Only looking at EQ and NE cases.
10021     return SDValue();
10022 
10023   EVT VT = N->getValueType(0);
10024   SDLoc dl(N);
10025   SDValue LHS = Cmp.getOperand(0);
10026   SDValue RHS = Cmp.getOperand(1);
10027   SDValue FalseVal = N->getOperand(0);
10028   SDValue TrueVal = N->getOperand(1);
10029   SDValue ARMcc = N->getOperand(2);
10030   ARMCC::CondCodes CC =
10031     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10032 
10033   // Simplify
10034   //   mov     r1, r0
10035   //   cmp     r1, x
10036   //   mov     r0, y
10037   //   moveq   r0, x
10038   // to
10039   //   cmp     r0, x
10040   //   movne   r0, y
10041   //
10042   //   mov     r1, r0
10043   //   cmp     r1, x
10044   //   mov     r0, x
10045   //   movne   r0, y
10046   // to
10047   //   cmp     r0, x
10048   //   movne   r0, y
10049   /// FIXME: Turn this into a target neutral optimization?
10050   SDValue Res;
10051   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10052     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10053                       N->getOperand(3), Cmp);
10054   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10055     SDValue ARMcc;
10056     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10057     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10058                       N->getOperand(3), NewCmp);
10059   }
10060 
10061   if (Res.getNode()) {
10062     APInt KnownZero, KnownOne;
10063     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
10064     // Capture demanded bits information that would be otherwise lost.
10065     if (KnownZero == 0xfffffffe)
10066       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10067                         DAG.getValueType(MVT::i1));
10068     else if (KnownZero == 0xffffff00)
10069       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10070                         DAG.getValueType(MVT::i8));
10071     else if (KnownZero == 0xffff0000)
10072       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10073                         DAG.getValueType(MVT::i16));
10074   }
10075 
10076   return Res;
10077 }
10078 
10079 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10080                                              DAGCombinerInfo &DCI) const {
10081   switch (N->getOpcode()) {
10082   default: break;
10083   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
10084   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
10085   case ISD::SUB:        return PerformSUBCombine(N, DCI);
10086   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
10087   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
10088   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
10089   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
10090   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
10091   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
10092   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10093   case ISD::STORE:      return PerformSTORECombine(N, DCI);
10094   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
10095   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10096   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10097   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10098   case ISD::FP_TO_SINT:
10099   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10100   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
10101   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10102   case ISD::SHL:
10103   case ISD::SRA:
10104   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10105   case ISD::SIGN_EXTEND:
10106   case ISD::ZERO_EXTEND:
10107   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10108   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
10109   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10110   case ARMISD::VLD2DUP:
10111   case ARMISD::VLD3DUP:
10112   case ARMISD::VLD4DUP:
10113     return CombineBaseUpdate(N, DCI);
10114   case ARMISD::BUILD_VECTOR:
10115     return PerformARMBUILD_VECTORCombine(N, DCI);
10116   case ISD::INTRINSIC_VOID:
10117   case ISD::INTRINSIC_W_CHAIN:
10118     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10119     case Intrinsic::arm_neon_vld1:
10120     case Intrinsic::arm_neon_vld2:
10121     case Intrinsic::arm_neon_vld3:
10122     case Intrinsic::arm_neon_vld4:
10123     case Intrinsic::arm_neon_vld2lane:
10124     case Intrinsic::arm_neon_vld3lane:
10125     case Intrinsic::arm_neon_vld4lane:
10126     case Intrinsic::arm_neon_vst1:
10127     case Intrinsic::arm_neon_vst2:
10128     case Intrinsic::arm_neon_vst3:
10129     case Intrinsic::arm_neon_vst4:
10130     case Intrinsic::arm_neon_vst2lane:
10131     case Intrinsic::arm_neon_vst3lane:
10132     case Intrinsic::arm_neon_vst4lane:
10133       return CombineBaseUpdate(N, DCI);
10134     default: break;
10135     }
10136     break;
10137   }
10138   return SDValue();
10139 }
10140 
10141 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10142                                                           EVT VT) const {
10143   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10144 }
10145 
10146 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, unsigned,
10147                                                       bool *Fast) const {
10148   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10149   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10150 
10151   switch (VT.getSimpleVT().SimpleTy) {
10152   default:
10153     return false;
10154   case MVT::i8:
10155   case MVT::i16:
10156   case MVT::i32: {
10157     // Unaligned access can use (for example) LRDB, LRDH, LDR
10158     if (AllowsUnaligned) {
10159       if (Fast)
10160         *Fast = Subtarget->hasV7Ops();
10161       return true;
10162     }
10163     return false;
10164   }
10165   case MVT::f64:
10166   case MVT::v2f64: {
10167     // For any little-endian targets with neon, we can support unaligned ld/st
10168     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10169     // A big-endian target may also explicitly support unaligned accesses
10170     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
10171       if (Fast)
10172         *Fast = true;
10173       return true;
10174     }
10175     return false;
10176   }
10177   }
10178 }
10179 
10180 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10181                        unsigned AlignCheck) {
10182   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10183           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10184 }
10185 
10186 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10187                                            unsigned DstAlign, unsigned SrcAlign,
10188                                            bool IsMemset, bool ZeroMemset,
10189                                            bool MemcpyStrSrc,
10190                                            MachineFunction &MF) const {
10191   const Function *F = MF.getFunction();
10192 
10193   // See if we can use NEON instructions for this...
10194   if ((!IsMemset || ZeroMemset) &&
10195       Subtarget->hasNEON() &&
10196       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
10197                                        Attribute::NoImplicitFloat)) {
10198     bool Fast;
10199     if (Size >= 16 &&
10200         (memOpAlign(SrcAlign, DstAlign, 16) ||
10201          (allowsUnalignedMemoryAccesses(MVT::v2f64, 0, &Fast) && Fast))) {
10202       return MVT::v2f64;
10203     } else if (Size >= 8 &&
10204                (memOpAlign(SrcAlign, DstAlign, 8) ||
10205                 (allowsUnalignedMemoryAccesses(MVT::f64, 0, &Fast) && Fast))) {
10206       return MVT::f64;
10207     }
10208   }
10209 
10210   // Lowering to i32/i16 if the size permits.
10211   if (Size >= 4)
10212     return MVT::i32;
10213   else if (Size >= 2)
10214     return MVT::i16;
10215 
10216   // Let the target-independent logic figure it out.
10217   return MVT::Other;
10218 }
10219 
10220 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10221   if (Val.getOpcode() != ISD::LOAD)
10222     return false;
10223 
10224   EVT VT1 = Val.getValueType();
10225   if (!VT1.isSimple() || !VT1.isInteger() ||
10226       !VT2.isSimple() || !VT2.isInteger())
10227     return false;
10228 
10229   switch (VT1.getSimpleVT().SimpleTy) {
10230   default: break;
10231   case MVT::i1:
10232   case MVT::i8:
10233   case MVT::i16:
10234     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10235     return true;
10236   }
10237 
10238   return false;
10239 }
10240 
10241 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10242   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10243     return false;
10244 
10245   if (!isTypeLegal(EVT::getEVT(Ty1)))
10246     return false;
10247 
10248   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10249 
10250   // Assuming the caller doesn't have a zeroext or signext return parameter,
10251   // truncation all the way down to i1 is valid.
10252   return true;
10253 }
10254 
10255 
10256 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10257   if (V < 0)
10258     return false;
10259 
10260   unsigned Scale = 1;
10261   switch (VT.getSimpleVT().SimpleTy) {
10262   default: return false;
10263   case MVT::i1:
10264   case MVT::i8:
10265     // Scale == 1;
10266     break;
10267   case MVT::i16:
10268     // Scale == 2;
10269     Scale = 2;
10270     break;
10271   case MVT::i32:
10272     // Scale == 4;
10273     Scale = 4;
10274     break;
10275   }
10276 
10277   if ((V & (Scale - 1)) != 0)
10278     return false;
10279   V /= Scale;
10280   return V == (V & ((1LL << 5) - 1));
10281 }
10282 
10283 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10284                                       const ARMSubtarget *Subtarget) {
10285   bool isNeg = false;
10286   if (V < 0) {
10287     isNeg = true;
10288     V = - V;
10289   }
10290 
10291   switch (VT.getSimpleVT().SimpleTy) {
10292   default: return false;
10293   case MVT::i1:
10294   case MVT::i8:
10295   case MVT::i16:
10296   case MVT::i32:
10297     // + imm12 or - imm8
10298     if (isNeg)
10299       return V == (V & ((1LL << 8) - 1));
10300     return V == (V & ((1LL << 12) - 1));
10301   case MVT::f32:
10302   case MVT::f64:
10303     // Same as ARM mode. FIXME: NEON?
10304     if (!Subtarget->hasVFP2())
10305       return false;
10306     if ((V & 3) != 0)
10307       return false;
10308     V >>= 2;
10309     return V == (V & ((1LL << 8) - 1));
10310   }
10311 }
10312 
10313 /// isLegalAddressImmediate - Return true if the integer value can be used
10314 /// as the offset of the target addressing mode for load / store of the
10315 /// given type.
10316 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10317                                     const ARMSubtarget *Subtarget) {
10318   if (V == 0)
10319     return true;
10320 
10321   if (!VT.isSimple())
10322     return false;
10323 
10324   if (Subtarget->isThumb1Only())
10325     return isLegalT1AddressImmediate(V, VT);
10326   else if (Subtarget->isThumb2())
10327     return isLegalT2AddressImmediate(V, VT, Subtarget);
10328 
10329   // ARM mode.
10330   if (V < 0)
10331     V = - V;
10332   switch (VT.getSimpleVT().SimpleTy) {
10333   default: return false;
10334   case MVT::i1:
10335   case MVT::i8:
10336   case MVT::i32:
10337     // +- imm12
10338     return V == (V & ((1LL << 12) - 1));
10339   case MVT::i16:
10340     // +- imm8
10341     return V == (V & ((1LL << 8) - 1));
10342   case MVT::f32:
10343   case MVT::f64:
10344     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10345       return false;
10346     if ((V & 3) != 0)
10347       return false;
10348     V >>= 2;
10349     return V == (V & ((1LL << 8) - 1));
10350   }
10351 }
10352 
10353 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10354                                                       EVT VT) const {
10355   int Scale = AM.Scale;
10356   if (Scale < 0)
10357     return false;
10358 
10359   switch (VT.getSimpleVT().SimpleTy) {
10360   default: return false;
10361   case MVT::i1:
10362   case MVT::i8:
10363   case MVT::i16:
10364   case MVT::i32:
10365     if (Scale == 1)
10366       return true;
10367     // r + r << imm
10368     Scale = Scale & ~1;
10369     return Scale == 2 || Scale == 4 || Scale == 8;
10370   case MVT::i64:
10371     // r + r
10372     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10373       return true;
10374     return false;
10375   case MVT::isVoid:
10376     // Note, we allow "void" uses (basically, uses that aren't loads or
10377     // stores), because arm allows folding a scale into many arithmetic
10378     // operations.  This should be made more precise and revisited later.
10379 
10380     // Allow r << imm, but the imm has to be a multiple of two.
10381     if (Scale & 1) return false;
10382     return isPowerOf2_32(Scale);
10383   }
10384 }
10385 
10386 /// isLegalAddressingMode - Return true if the addressing mode represented
10387 /// by AM is legal for this target, for a load/store of the specified type.
10388 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10389                                               Type *Ty) const {
10390   EVT VT = getValueType(Ty, true);
10391   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10392     return false;
10393 
10394   // Can never fold addr of global into load/store.
10395   if (AM.BaseGV)
10396     return false;
10397 
10398   switch (AM.Scale) {
10399   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10400     break;
10401   case 1:
10402     if (Subtarget->isThumb1Only())
10403       return false;
10404     // FALL THROUGH.
10405   default:
10406     // ARM doesn't support any R+R*scale+imm addr modes.
10407     if (AM.BaseOffs)
10408       return false;
10409 
10410     if (!VT.isSimple())
10411       return false;
10412 
10413     if (Subtarget->isThumb2())
10414       return isLegalT2ScaledAddressingMode(AM, VT);
10415 
10416     int Scale = AM.Scale;
10417     switch (VT.getSimpleVT().SimpleTy) {
10418     default: return false;
10419     case MVT::i1:
10420     case MVT::i8:
10421     case MVT::i32:
10422       if (Scale < 0) Scale = -Scale;
10423       if (Scale == 1)
10424         return true;
10425       // r + r << imm
10426       return isPowerOf2_32(Scale & ~1);
10427     case MVT::i16:
10428     case MVT::i64:
10429       // r + r
10430       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10431         return true;
10432       return false;
10433 
10434     case MVT::isVoid:
10435       // Note, we allow "void" uses (basically, uses that aren't loads or
10436       // stores), because arm allows folding a scale into many arithmetic
10437       // operations.  This should be made more precise and revisited later.
10438 
10439       // Allow r << imm, but the imm has to be a multiple of two.
10440       if (Scale & 1) return false;
10441       return isPowerOf2_32(Scale);
10442     }
10443   }
10444   return true;
10445 }
10446 
10447 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10448 /// icmp immediate, that is the target has icmp instructions which can compare
10449 /// a register against the immediate without having to materialize the
10450 /// immediate into a register.
10451 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10452   // Thumb2 and ARM modes can use cmn for negative immediates.
10453   if (!Subtarget->isThumb())
10454     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10455   if (Subtarget->isThumb2())
10456     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10457   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10458   return Imm >= 0 && Imm <= 255;
10459 }
10460 
10461 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10462 /// *or sub* immediate, that is the target has add or sub instructions which can
10463 /// add a register with the immediate without having to materialize the
10464 /// immediate into a register.
10465 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10466   // Same encoding for add/sub, just flip the sign.
10467   int64_t AbsImm = llvm::abs64(Imm);
10468   if (!Subtarget->isThumb())
10469     return ARM_AM::getSOImmVal(AbsImm) != -1;
10470   if (Subtarget->isThumb2())
10471     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10472   // Thumb1 only has 8-bit unsigned immediate.
10473   return AbsImm >= 0 && AbsImm <= 255;
10474 }
10475 
10476 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10477                                       bool isSEXTLoad, SDValue &Base,
10478                                       SDValue &Offset, bool &isInc,
10479                                       SelectionDAG &DAG) {
10480   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10481     return false;
10482 
10483   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10484     // AddressingMode 3
10485     Base = Ptr->getOperand(0);
10486     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10487       int RHSC = (int)RHS->getZExtValue();
10488       if (RHSC < 0 && RHSC > -256) {
10489         assert(Ptr->getOpcode() == ISD::ADD);
10490         isInc = false;
10491         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10492         return true;
10493       }
10494     }
10495     isInc = (Ptr->getOpcode() == ISD::ADD);
10496     Offset = Ptr->getOperand(1);
10497     return true;
10498   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10499     // AddressingMode 2
10500     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10501       int RHSC = (int)RHS->getZExtValue();
10502       if (RHSC < 0 && RHSC > -0x1000) {
10503         assert(Ptr->getOpcode() == ISD::ADD);
10504         isInc = false;
10505         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10506         Base = Ptr->getOperand(0);
10507         return true;
10508       }
10509     }
10510 
10511     if (Ptr->getOpcode() == ISD::ADD) {
10512       isInc = true;
10513       ARM_AM::ShiftOpc ShOpcVal=
10514         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10515       if (ShOpcVal != ARM_AM::no_shift) {
10516         Base = Ptr->getOperand(1);
10517         Offset = Ptr->getOperand(0);
10518       } else {
10519         Base = Ptr->getOperand(0);
10520         Offset = Ptr->getOperand(1);
10521       }
10522       return true;
10523     }
10524 
10525     isInc = (Ptr->getOpcode() == ISD::ADD);
10526     Base = Ptr->getOperand(0);
10527     Offset = Ptr->getOperand(1);
10528     return true;
10529   }
10530 
10531   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10532   return false;
10533 }
10534 
10535 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10536                                      bool isSEXTLoad, SDValue &Base,
10537                                      SDValue &Offset, bool &isInc,
10538                                      SelectionDAG &DAG) {
10539   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10540     return false;
10541 
10542   Base = Ptr->getOperand(0);
10543   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10544     int RHSC = (int)RHS->getZExtValue();
10545     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10546       assert(Ptr->getOpcode() == ISD::ADD);
10547       isInc = false;
10548       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10549       return true;
10550     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10551       isInc = Ptr->getOpcode() == ISD::ADD;
10552       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10553       return true;
10554     }
10555   }
10556 
10557   return false;
10558 }
10559 
10560 /// getPreIndexedAddressParts - returns true by value, base pointer and
10561 /// offset pointer and addressing mode by reference if the node's address
10562 /// can be legally represented as pre-indexed load / store address.
10563 bool
10564 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10565                                              SDValue &Offset,
10566                                              ISD::MemIndexedMode &AM,
10567                                              SelectionDAG &DAG) const {
10568   if (Subtarget->isThumb1Only())
10569     return false;
10570 
10571   EVT VT;
10572   SDValue Ptr;
10573   bool isSEXTLoad = false;
10574   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10575     Ptr = LD->getBasePtr();
10576     VT  = LD->getMemoryVT();
10577     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10578   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10579     Ptr = ST->getBasePtr();
10580     VT  = ST->getMemoryVT();
10581   } else
10582     return false;
10583 
10584   bool isInc;
10585   bool isLegal = false;
10586   if (Subtarget->isThumb2())
10587     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10588                                        Offset, isInc, DAG);
10589   else
10590     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10591                                         Offset, isInc, DAG);
10592   if (!isLegal)
10593     return false;
10594 
10595   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10596   return true;
10597 }
10598 
10599 /// getPostIndexedAddressParts - returns true by value, base pointer and
10600 /// offset pointer and addressing mode by reference if this node can be
10601 /// combined with a load / store to form a post-indexed load / store.
10602 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10603                                                    SDValue &Base,
10604                                                    SDValue &Offset,
10605                                                    ISD::MemIndexedMode &AM,
10606                                                    SelectionDAG &DAG) const {
10607   if (Subtarget->isThumb1Only())
10608     return false;
10609 
10610   EVT VT;
10611   SDValue Ptr;
10612   bool isSEXTLoad = false;
10613   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10614     VT  = LD->getMemoryVT();
10615     Ptr = LD->getBasePtr();
10616     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10617   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10618     VT  = ST->getMemoryVT();
10619     Ptr = ST->getBasePtr();
10620   } else
10621     return false;
10622 
10623   bool isInc;
10624   bool isLegal = false;
10625   if (Subtarget->isThumb2())
10626     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10627                                        isInc, DAG);
10628   else
10629     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10630                                         isInc, DAG);
10631   if (!isLegal)
10632     return false;
10633 
10634   if (Ptr != Base) {
10635     // Swap base ptr and offset to catch more post-index load / store when
10636     // it's legal. In Thumb2 mode, offset must be an immediate.
10637     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10638         !Subtarget->isThumb2())
10639       std::swap(Base, Offset);
10640 
10641     // Post-indexed load / store update the base pointer.
10642     if (Ptr != Base)
10643       return false;
10644   }
10645 
10646   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10647   return true;
10648 }
10649 
10650 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10651                                                        APInt &KnownZero,
10652                                                        APInt &KnownOne,
10653                                                        const SelectionDAG &DAG,
10654                                                        unsigned Depth) const {
10655   unsigned BitWidth = KnownOne.getBitWidth();
10656   KnownZero = KnownOne = APInt(BitWidth, 0);
10657   switch (Op.getOpcode()) {
10658   default: break;
10659   case ARMISD::ADDC:
10660   case ARMISD::ADDE:
10661   case ARMISD::SUBC:
10662   case ARMISD::SUBE:
10663     // These nodes' second result is a boolean
10664     if (Op.getResNo() == 0)
10665       break;
10666     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10667     break;
10668   case ARMISD::CMOV: {
10669     // Bits are known zero/one if known on the LHS and RHS.
10670     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10671     if (KnownZero == 0 && KnownOne == 0) return;
10672 
10673     APInt KnownZeroRHS, KnownOneRHS;
10674     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10675     KnownZero &= KnownZeroRHS;
10676     KnownOne  &= KnownOneRHS;
10677     return;
10678   }
10679   }
10680 }
10681 
10682 //===----------------------------------------------------------------------===//
10683 //                           ARM Inline Assembly Support
10684 //===----------------------------------------------------------------------===//
10685 
10686 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10687   // Looking for "rev" which is V6+.
10688   if (!Subtarget->hasV6Ops())
10689     return false;
10690 
10691   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10692   std::string AsmStr = IA->getAsmString();
10693   SmallVector<StringRef, 4> AsmPieces;
10694   SplitString(AsmStr, AsmPieces, ";\n");
10695 
10696   switch (AsmPieces.size()) {
10697   default: return false;
10698   case 1:
10699     AsmStr = AsmPieces[0];
10700     AsmPieces.clear();
10701     SplitString(AsmStr, AsmPieces, " \t,");
10702 
10703     // rev $0, $1
10704     if (AsmPieces.size() == 3 &&
10705         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10706         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10707       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10708       if (Ty && Ty->getBitWidth() == 32)
10709         return IntrinsicLowering::LowerToByteSwap(CI);
10710     }
10711     break;
10712   }
10713 
10714   return false;
10715 }
10716 
10717 /// getConstraintType - Given a constraint letter, return the type of
10718 /// constraint it is for this target.
10719 ARMTargetLowering::ConstraintType
10720 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10721   if (Constraint.size() == 1) {
10722     switch (Constraint[0]) {
10723     default:  break;
10724     case 'l': return C_RegisterClass;
10725     case 'w': return C_RegisterClass;
10726     case 'h': return C_RegisterClass;
10727     case 'x': return C_RegisterClass;
10728     case 't': return C_RegisterClass;
10729     case 'j': return C_Other; // Constant for movw.
10730       // An address with a single base register. Due to the way we
10731       // currently handle addresses it is the same as an 'r' memory constraint.
10732     case 'Q': return C_Memory;
10733     }
10734   } else if (Constraint.size() == 2) {
10735     switch (Constraint[0]) {
10736     default: break;
10737     // All 'U+' constraints are addresses.
10738     case 'U': return C_Memory;
10739     }
10740   }
10741   return TargetLowering::getConstraintType(Constraint);
10742 }
10743 
10744 /// Examine constraint type and operand type and determine a weight value.
10745 /// This object must already have been set up with the operand type
10746 /// and the current alternative constraint selected.
10747 TargetLowering::ConstraintWeight
10748 ARMTargetLowering::getSingleConstraintMatchWeight(
10749     AsmOperandInfo &info, const char *constraint) const {
10750   ConstraintWeight weight = CW_Invalid;
10751   Value *CallOperandVal = info.CallOperandVal;
10752     // If we don't have a value, we can't do a match,
10753     // but allow it at the lowest weight.
10754   if (CallOperandVal == NULL)
10755     return CW_Default;
10756   Type *type = CallOperandVal->getType();
10757   // Look at the constraint type.
10758   switch (*constraint) {
10759   default:
10760     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10761     break;
10762   case 'l':
10763     if (type->isIntegerTy()) {
10764       if (Subtarget->isThumb())
10765         weight = CW_SpecificReg;
10766       else
10767         weight = CW_Register;
10768     }
10769     break;
10770   case 'w':
10771     if (type->isFloatingPointTy())
10772       weight = CW_Register;
10773     break;
10774   }
10775   return weight;
10776 }
10777 
10778 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10779 RCPair
10780 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10781                                                 MVT VT) const {
10782   if (Constraint.size() == 1) {
10783     // GCC ARM Constraint Letters
10784     switch (Constraint[0]) {
10785     case 'l': // Low regs or general regs.
10786       if (Subtarget->isThumb())
10787         return RCPair(0U, &ARM::tGPRRegClass);
10788       return RCPair(0U, &ARM::GPRRegClass);
10789     case 'h': // High regs or no regs.
10790       if (Subtarget->isThumb())
10791         return RCPair(0U, &ARM::hGPRRegClass);
10792       break;
10793     case 'r':
10794       return RCPair(0U, &ARM::GPRRegClass);
10795     case 'w':
10796       if (VT == MVT::Other)
10797         break;
10798       if (VT == MVT::f32)
10799         return RCPair(0U, &ARM::SPRRegClass);
10800       if (VT.getSizeInBits() == 64)
10801         return RCPair(0U, &ARM::DPRRegClass);
10802       if (VT.getSizeInBits() == 128)
10803         return RCPair(0U, &ARM::QPRRegClass);
10804       break;
10805     case 'x':
10806       if (VT == MVT::Other)
10807         break;
10808       if (VT == MVT::f32)
10809         return RCPair(0U, &ARM::SPR_8RegClass);
10810       if (VT.getSizeInBits() == 64)
10811         return RCPair(0U, &ARM::DPR_8RegClass);
10812       if (VT.getSizeInBits() == 128)
10813         return RCPair(0U, &ARM::QPR_8RegClass);
10814       break;
10815     case 't':
10816       if (VT == MVT::f32)
10817         return RCPair(0U, &ARM::SPRRegClass);
10818       break;
10819     }
10820   }
10821   if (StringRef("{cc}").equals_lower(Constraint))
10822     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10823 
10824   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10825 }
10826 
10827 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10828 /// vector.  If it is invalid, don't add anything to Ops.
10829 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10830                                                      std::string &Constraint,
10831                                                      std::vector<SDValue>&Ops,
10832                                                      SelectionDAG &DAG) const {
10833   SDValue Result(0, 0);
10834 
10835   // Currently only support length 1 constraints.
10836   if (Constraint.length() != 1) return;
10837 
10838   char ConstraintLetter = Constraint[0];
10839   switch (ConstraintLetter) {
10840   default: break;
10841   case 'j':
10842   case 'I': case 'J': case 'K': case 'L':
10843   case 'M': case 'N': case 'O':
10844     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10845     if (!C)
10846       return;
10847 
10848     int64_t CVal64 = C->getSExtValue();
10849     int CVal = (int) CVal64;
10850     // None of these constraints allow values larger than 32 bits.  Check
10851     // that the value fits in an int.
10852     if (CVal != CVal64)
10853       return;
10854 
10855     switch (ConstraintLetter) {
10856       case 'j':
10857         // Constant suitable for movw, must be between 0 and
10858         // 65535.
10859         if (Subtarget->hasV6T2Ops())
10860           if (CVal >= 0 && CVal <= 65535)
10861             break;
10862         return;
10863       case 'I':
10864         if (Subtarget->isThumb1Only()) {
10865           // This must be a constant between 0 and 255, for ADD
10866           // immediates.
10867           if (CVal >= 0 && CVal <= 255)
10868             break;
10869         } else if (Subtarget->isThumb2()) {
10870           // A constant that can be used as an immediate value in a
10871           // data-processing instruction.
10872           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10873             break;
10874         } else {
10875           // A constant that can be used as an immediate value in a
10876           // data-processing instruction.
10877           if (ARM_AM::getSOImmVal(CVal) != -1)
10878             break;
10879         }
10880         return;
10881 
10882       case 'J':
10883         if (Subtarget->isThumb()) {  // FIXME thumb2
10884           // This must be a constant between -255 and -1, for negated ADD
10885           // immediates. This can be used in GCC with an "n" modifier that
10886           // prints the negated value, for use with SUB instructions. It is
10887           // not useful otherwise but is implemented for compatibility.
10888           if (CVal >= -255 && CVal <= -1)
10889             break;
10890         } else {
10891           // This must be a constant between -4095 and 4095. It is not clear
10892           // what this constraint is intended for. Implemented for
10893           // compatibility with GCC.
10894           if (CVal >= -4095 && CVal <= 4095)
10895             break;
10896         }
10897         return;
10898 
10899       case 'K':
10900         if (Subtarget->isThumb1Only()) {
10901           // A 32-bit value where only one byte has a nonzero value. Exclude
10902           // zero to match GCC. This constraint is used by GCC internally for
10903           // constants that can be loaded with a move/shift combination.
10904           // It is not useful otherwise but is implemented for compatibility.
10905           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10906             break;
10907         } else if (Subtarget->isThumb2()) {
10908           // A constant whose bitwise inverse can be used as an immediate
10909           // value in a data-processing instruction. This can be used in GCC
10910           // with a "B" modifier that prints the inverted value, for use with
10911           // BIC and MVN instructions. It is not useful otherwise but is
10912           // implemented for compatibility.
10913           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10914             break;
10915         } else {
10916           // A constant whose bitwise inverse can be used as an immediate
10917           // value in a data-processing instruction. This can be used in GCC
10918           // with a "B" modifier that prints the inverted value, for use with
10919           // BIC and MVN instructions. It is not useful otherwise but is
10920           // implemented for compatibility.
10921           if (ARM_AM::getSOImmVal(~CVal) != -1)
10922             break;
10923         }
10924         return;
10925 
10926       case 'L':
10927         if (Subtarget->isThumb1Only()) {
10928           // This must be a constant between -7 and 7,
10929           // for 3-operand ADD/SUB immediate instructions.
10930           if (CVal >= -7 && CVal < 7)
10931             break;
10932         } else if (Subtarget->isThumb2()) {
10933           // A constant whose negation can be used as an immediate value in a
10934           // data-processing instruction. This can be used in GCC with an "n"
10935           // modifier that prints the negated value, for use with SUB
10936           // instructions. It is not useful otherwise but is implemented for
10937           // compatibility.
10938           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10939             break;
10940         } else {
10941           // A constant whose negation can be used as an immediate value in a
10942           // data-processing instruction. This can be used in GCC with an "n"
10943           // modifier that prints the negated value, for use with SUB
10944           // instructions. It is not useful otherwise but is implemented for
10945           // compatibility.
10946           if (ARM_AM::getSOImmVal(-CVal) != -1)
10947             break;
10948         }
10949         return;
10950 
10951       case 'M':
10952         if (Subtarget->isThumb()) { // FIXME thumb2
10953           // This must be a multiple of 4 between 0 and 1020, for
10954           // ADD sp + immediate.
10955           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10956             break;
10957         } else {
10958           // A power of two or a constant between 0 and 32.  This is used in
10959           // GCC for the shift amount on shifted register operands, but it is
10960           // useful in general for any shift amounts.
10961           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10962             break;
10963         }
10964         return;
10965 
10966       case 'N':
10967         if (Subtarget->isThumb()) {  // FIXME thumb2
10968           // This must be a constant between 0 and 31, for shift amounts.
10969           if (CVal >= 0 && CVal <= 31)
10970             break;
10971         }
10972         return;
10973 
10974       case 'O':
10975         if (Subtarget->isThumb()) {  // FIXME thumb2
10976           // This must be a multiple of 4 between -508 and 508, for
10977           // ADD/SUB sp = sp + immediate.
10978           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10979             break;
10980         }
10981         return;
10982     }
10983     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10984     break;
10985   }
10986 
10987   if (Result.getNode()) {
10988     Ops.push_back(Result);
10989     return;
10990   }
10991   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10992 }
10993 
10994 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10995   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10996   unsigned Opcode = Op->getOpcode();
10997   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10998       "Invalid opcode for Div/Rem lowering");
10999   bool isSigned = (Opcode == ISD::SDIVREM);
11000   EVT VT = Op->getValueType(0);
11001   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11002 
11003   RTLIB::Libcall LC;
11004   switch (VT.getSimpleVT().SimpleTy) {
11005   default: llvm_unreachable("Unexpected request for libcall!");
11006   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
11007   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11008   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11009   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11010   }
11011 
11012   SDValue InChain = DAG.getEntryNode();
11013 
11014   TargetLowering::ArgListTy Args;
11015   TargetLowering::ArgListEntry Entry;
11016   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
11017     EVT ArgVT = Op->getOperand(i).getValueType();
11018     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11019     Entry.Node = Op->getOperand(i);
11020     Entry.Ty = ArgTy;
11021     Entry.isSExt = isSigned;
11022     Entry.isZExt = !isSigned;
11023     Args.push_back(Entry);
11024   }
11025 
11026   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11027                                          getPointerTy());
11028 
11029   Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
11030 
11031   SDLoc dl(Op);
11032   TargetLowering::
11033   CallLoweringInfo CLI(InChain, RetTy, isSigned, !isSigned, false, true,
11034                     0, getLibcallCallingConv(LC), /*isTailCall=*/false,
11035                     /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
11036                     Callee, Args, DAG, dl);
11037   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11038 
11039   return CallInfo.first;
11040 }
11041 
11042 bool
11043 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11044   // The ARM target isn't yet aware of offsets.
11045   return false;
11046 }
11047 
11048 bool ARM::isBitFieldInvertedMask(unsigned v) {
11049   if (v == 0xffffffff)
11050     return false;
11051 
11052   // there can be 1's on either or both "outsides", all the "inside"
11053   // bits must be 0's
11054   unsigned TO = CountTrailingOnes_32(v);
11055   unsigned LO = CountLeadingOnes_32(v);
11056   v = (v >> TO) << TO;
11057   v = (v << LO) >> LO;
11058   return v == 0;
11059 }
11060 
11061 /// isFPImmLegal - Returns true if the target can instruction select the
11062 /// specified FP immediate natively. If false, the legalizer will
11063 /// materialize the FP immediate as a load from a constant pool.
11064 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11065   if (!Subtarget->hasVFP3())
11066     return false;
11067   if (VT == MVT::f32)
11068     return ARM_AM::getFP32Imm(Imm) != -1;
11069   if (VT == MVT::f64)
11070     return ARM_AM::getFP64Imm(Imm) != -1;
11071   return false;
11072 }
11073 
11074 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11075 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11076 /// specified in the intrinsic calls.
11077 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11078                                            const CallInst &I,
11079                                            unsigned Intrinsic) const {
11080   switch (Intrinsic) {
11081   case Intrinsic::arm_neon_vld1:
11082   case Intrinsic::arm_neon_vld2:
11083   case Intrinsic::arm_neon_vld3:
11084   case Intrinsic::arm_neon_vld4:
11085   case Intrinsic::arm_neon_vld2lane:
11086   case Intrinsic::arm_neon_vld3lane:
11087   case Intrinsic::arm_neon_vld4lane: {
11088     Info.opc = ISD::INTRINSIC_W_CHAIN;
11089     // Conservatively set memVT to the entire set of vectors loaded.
11090     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
11091     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11092     Info.ptrVal = I.getArgOperand(0);
11093     Info.offset = 0;
11094     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11095     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11096     Info.vol = false; // volatile loads with NEON intrinsics not supported
11097     Info.readMem = true;
11098     Info.writeMem = false;
11099     return true;
11100   }
11101   case Intrinsic::arm_neon_vst1:
11102   case Intrinsic::arm_neon_vst2:
11103   case Intrinsic::arm_neon_vst3:
11104   case Intrinsic::arm_neon_vst4:
11105   case Intrinsic::arm_neon_vst2lane:
11106   case Intrinsic::arm_neon_vst3lane:
11107   case Intrinsic::arm_neon_vst4lane: {
11108     Info.opc = ISD::INTRINSIC_VOID;
11109     // Conservatively set memVT to the entire set of vectors stored.
11110     unsigned NumElts = 0;
11111     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11112       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11113       if (!ArgTy->isVectorTy())
11114         break;
11115       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
11116     }
11117     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11118     Info.ptrVal = I.getArgOperand(0);
11119     Info.offset = 0;
11120     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11121     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11122     Info.vol = false; // volatile stores with NEON intrinsics not supported
11123     Info.readMem = false;
11124     Info.writeMem = true;
11125     return true;
11126   }
11127   case Intrinsic::arm_ldrex: {
11128     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11129     Info.opc = ISD::INTRINSIC_W_CHAIN;
11130     Info.memVT = MVT::getVT(PtrTy->getElementType());
11131     Info.ptrVal = I.getArgOperand(0);
11132     Info.offset = 0;
11133     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11134     Info.vol = true;
11135     Info.readMem = true;
11136     Info.writeMem = false;
11137     return true;
11138   }
11139   case Intrinsic::arm_strex: {
11140     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11141     Info.opc = ISD::INTRINSIC_W_CHAIN;
11142     Info.memVT = MVT::getVT(PtrTy->getElementType());
11143     Info.ptrVal = I.getArgOperand(1);
11144     Info.offset = 0;
11145     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11146     Info.vol = true;
11147     Info.readMem = false;
11148     Info.writeMem = true;
11149     return true;
11150   }
11151   case Intrinsic::arm_strexd: {
11152     Info.opc = ISD::INTRINSIC_W_CHAIN;
11153     Info.memVT = MVT::i64;
11154     Info.ptrVal = I.getArgOperand(2);
11155     Info.offset = 0;
11156     Info.align = 8;
11157     Info.vol = true;
11158     Info.readMem = false;
11159     Info.writeMem = true;
11160     return true;
11161   }
11162   case Intrinsic::arm_ldrexd: {
11163     Info.opc = ISD::INTRINSIC_W_CHAIN;
11164     Info.memVT = MVT::i64;
11165     Info.ptrVal = I.getArgOperand(0);
11166     Info.offset = 0;
11167     Info.align = 8;
11168     Info.vol = true;
11169     Info.readMem = true;
11170     Info.writeMem = false;
11171     return true;
11172   }
11173   default:
11174     break;
11175   }
11176 
11177   return false;
11178 }
11179 
11180 /// \brief Returns true if it is beneficial to convert a load of a constant
11181 /// to just the constant itself.
11182 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11183                                                           Type *Ty) const {
11184   assert(Ty->isIntegerTy());
11185 
11186   unsigned Bits = Ty->getPrimitiveSizeInBits();
11187   if (Bits == 0 || Bits > 32)
11188     return false;
11189   return true;
11190 }
11191