1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #define DEBUG_TYPE "arm-isel"
16 #include "ARM.h"
17 #include "ARMCallingConv.h"
18 #include "ARMConstantPoolValue.h"
19 #include "ARMISelLowering.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "ARMPerfectShuffle.h"
22 #include "ARMRegisterInfo.h"
23 #include "ARMSubtarget.h"
24 #include "ARMTargetMachine.h"
25 #include "ARMTargetObjectFile.h"
26 #include "MCTargetDesc/ARMAddressingModes.h"
27 #include "llvm/CallingConv.h"
28 #include "llvm/Constants.h"
29 #include "llvm/Function.h"
30 #include "llvm/GlobalValue.h"
31 #include "llvm/Instruction.h"
32 #include "llvm/Instructions.h"
33 #include "llvm/Intrinsics.h"
34 #include "llvm/Type.h"
35 #include "llvm/CodeGen/CallingConvLower.h"
36 #include "llvm/CodeGen/IntrinsicLowering.h"
37 #include "llvm/CodeGen/MachineBasicBlock.h"
38 #include "llvm/CodeGen/MachineFrameInfo.h"
39 #include "llvm/CodeGen/MachineFunction.h"
40 #include "llvm/CodeGen/MachineInstrBuilder.h"
41 #include "llvm/CodeGen/MachineModuleInfo.h"
42 #include "llvm/CodeGen/MachineRegisterInfo.h"
43 #include "llvm/CodeGen/SelectionDAG.h"
44 #include "llvm/MC/MCSectionMachO.h"
45 #include "llvm/Target/TargetOptions.h"
46 #include "llvm/ADT/StringExtras.h"
47 #include "llvm/ADT/Statistic.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Support/raw_ostream.h"
52 #include <sstream>
53 using namespace llvm;
54 
55 STATISTIC(NumTailCalls, "Number of tail calls");
56 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
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, SmallVector<CCValAssign, 16> &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 unsigned GPRArgRegs[] = {
91   ARM::R0, ARM::R1, ARM::R2, ARM::R3
92 };
93 
94 void ARMTargetLowering::addTypeForNEON(EVT VT, EVT PromotedLdStVT,
95                                        EVT PromotedBitwiseVT) {
96   if (VT != PromotedLdStVT) {
97     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
98     AddPromotedToType (ISD::LOAD, VT.getSimpleVT(),
99                        PromotedLdStVT.getSimpleVT());
100 
101     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
102     AddPromotedToType (ISD::STORE, VT.getSimpleVT(),
103                        PromotedLdStVT.getSimpleVT());
104   }
105 
106   EVT ElemTy = VT.getVectorElementType();
107   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
108     setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
109   setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
110   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
111   if (ElemTy == MVT::i32) {
112     setOperationAction(ISD::SINT_TO_FP, VT.getSimpleVT(), Custom);
113     setOperationAction(ISD::UINT_TO_FP, VT.getSimpleVT(), Custom);
114     setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
115     setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
116   } else {
117     setOperationAction(ISD::SINT_TO_FP, VT.getSimpleVT(), Expand);
118     setOperationAction(ISD::UINT_TO_FP, VT.getSimpleVT(), Expand);
119     setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Expand);
120     setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Expand);
121   }
122   setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
123   setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
124   setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
125   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Legal);
126   setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
127   setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
128   setOperationAction(ISD::SIGN_EXTEND_INREG, VT.getSimpleVT(), Expand);
129   if (VT.isInteger()) {
130     setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
131     setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
132     setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
133   }
134 
135   // Promote all bit-wise operations.
136   if (VT.isInteger() && VT != PromotedBitwiseVT) {
137     setOperationAction(ISD::AND, VT.getSimpleVT(), Promote);
138     AddPromotedToType (ISD::AND, VT.getSimpleVT(),
139                        PromotedBitwiseVT.getSimpleVT());
140     setOperationAction(ISD::OR,  VT.getSimpleVT(), Promote);
141     AddPromotedToType (ISD::OR,  VT.getSimpleVT(),
142                        PromotedBitwiseVT.getSimpleVT());
143     setOperationAction(ISD::XOR, VT.getSimpleVT(), Promote);
144     AddPromotedToType (ISD::XOR, VT.getSimpleVT(),
145                        PromotedBitwiseVT.getSimpleVT());
146   }
147 
148   // Neon does not support vector divide/remainder operations.
149   setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
150   setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
151   setOperationAction(ISD::FDIV, VT.getSimpleVT(), Expand);
152   setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
153   setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
154   setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
155 }
156 
157 void ARMTargetLowering::addDRTypeForNEON(EVT VT) {
158   addRegisterClass(VT, ARM::DPRRegisterClass);
159   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
160 }
161 
162 void ARMTargetLowering::addQRTypeForNEON(EVT VT) {
163   addRegisterClass(VT, ARM::QPRRegisterClass);
164   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
165 }
166 
167 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
168   if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
169     return new TargetLoweringObjectFileMachO();
170 
171   return new ARMElfTargetObjectFile();
172 }
173 
174 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
175     : TargetLowering(TM, createTLOF(TM)) {
176   Subtarget = &TM.getSubtarget<ARMSubtarget>();
177   RegInfo = TM.getRegisterInfo();
178   Itins = TM.getInstrItineraryData();
179 
180   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
181 
182   if (Subtarget->isTargetDarwin()) {
183     // Uses VFP for Thumb libfuncs if available.
184     if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
185       // Single-precision floating-point arithmetic.
186       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
187       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
188       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
189       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
190 
191       // Double-precision floating-point arithmetic.
192       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
193       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
194       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
195       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
196 
197       // Single-precision comparisons.
198       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
199       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
200       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
201       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
202       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
203       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
204       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
205       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
206 
207       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
208       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
209       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
210       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
211       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
212       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
213       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
214       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
215 
216       // Double-precision comparisons.
217       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
218       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
219       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
220       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
221       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
222       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
223       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
224       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
225 
226       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
227       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
228       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
229       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
230       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
231       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
232       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
233       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
234 
235       // Floating-point to integer conversions.
236       // i64 conversions are done via library routines even when generating VFP
237       // instructions, so use the same ones.
238       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
239       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
240       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
241       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
242 
243       // Conversions between floating types.
244       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
245       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
246 
247       // Integer to floating-point conversions.
248       // i64 conversions are done via library routines even when generating VFP
249       // instructions, so use the same ones.
250       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
251       // e.g., __floatunsidf vs. __floatunssidfvfp.
252       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
253       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
254       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
255       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
256     }
257   }
258 
259   // These libcalls are not available in 32-bit.
260   setLibcallName(RTLIB::SHL_I128, 0);
261   setLibcallName(RTLIB::SRL_I128, 0);
262   setLibcallName(RTLIB::SRA_I128, 0);
263 
264   if (Subtarget->isAAPCS_ABI()) {
265     // Double-precision floating-point arithmetic helper functions
266     // RTABI chapter 4.1.2, Table 2
267     setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
268     setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
269     setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
270     setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
271     setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
272     setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
273     setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
274     setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
275 
276     // Double-precision floating-point comparison helper functions
277     // RTABI chapter 4.1.2, Table 3
278     setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
279     setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
280     setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
281     setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
282     setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
283     setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
284     setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
285     setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
286     setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
287     setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
288     setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
289     setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
290     setLibcallName(RTLIB::UO_F64,  "__aeabi_dcmpun");
291     setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
292     setLibcallName(RTLIB::O_F64,   "__aeabi_dcmpun");
293     setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
294     setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
295     setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
296     setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
297     setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
298     setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
299     setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
300     setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
301     setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
302 
303     // Single-precision floating-point arithmetic helper functions
304     // RTABI chapter 4.1.2, Table 4
305     setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
306     setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
307     setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
308     setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
309     setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
310     setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
311     setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
312     setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
313 
314     // Single-precision floating-point comparison helper functions
315     // RTABI chapter 4.1.2, Table 5
316     setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
317     setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
318     setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
319     setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
320     setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
321     setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
322     setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
323     setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
324     setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
325     setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
326     setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
327     setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
328     setLibcallName(RTLIB::UO_F32,  "__aeabi_fcmpun");
329     setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
330     setLibcallName(RTLIB::O_F32,   "__aeabi_fcmpun");
331     setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
332     setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
333     setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
334     setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
335     setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
336     setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
337     setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
338     setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
339     setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
340 
341     // Floating-point to integer conversions.
342     // RTABI chapter 4.1.2, Table 6
343     setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
344     setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
345     setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
346     setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
347     setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
348     setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
349     setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
350     setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
351     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
352     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
353     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
354     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
355     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
356     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
357     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
358     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
359 
360     // Conversions between floating types.
361     // RTABI chapter 4.1.2, Table 7
362     setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
363     setLibcallName(RTLIB::FPEXT_F32_F64,   "__aeabi_f2d");
364     setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
365     setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
366 
367     // Integer to floating-point conversions.
368     // RTABI chapter 4.1.2, Table 8
369     setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
370     setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
371     setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
372     setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
373     setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
374     setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
375     setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
376     setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
377     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
378     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
379     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
380     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
381     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
382     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
383     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
384     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
385 
386     // Long long helper functions
387     // RTABI chapter 4.2, Table 9
388     setLibcallName(RTLIB::MUL_I64,  "__aeabi_lmul");
389     setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
390     setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
391     setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
392     setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
393     setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
394     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
395     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
396     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
397     setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
398     setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
399     setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
400 
401     // Integer division functions
402     // RTABI chapter 4.3.1
403     setLibcallName(RTLIB::SDIV_I8,  "__aeabi_idiv");
404     setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
405     setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
406     setLibcallName(RTLIB::UDIV_I8,  "__aeabi_uidiv");
407     setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
408     setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
409     setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
410     setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
411     setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
412     setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
413     setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
414     setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
415 
416     // Memory operations
417     // RTABI chapter 4.3.4
418     setLibcallName(RTLIB::MEMCPY,  "__aeabi_memcpy");
419     setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
420     setLibcallName(RTLIB::MEMSET,  "__aeabi_memset");
421   }
422 
423   // Use divmod compiler-rt calls for iOS 5.0 and later.
424   if (Subtarget->getTargetTriple().getOS() == Triple::IOS &&
425       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
426     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
427     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
428   }
429 
430   if (Subtarget->isThumb1Only())
431     addRegisterClass(MVT::i32, ARM::tGPRRegisterClass);
432   else
433     addRegisterClass(MVT::i32, ARM::GPRRegisterClass);
434   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
435       !Subtarget->isThumb1Only()) {
436     addRegisterClass(MVT::f32, ARM::SPRRegisterClass);
437     if (!Subtarget->isFPOnlySP())
438       addRegisterClass(MVT::f64, ARM::DPRRegisterClass);
439 
440     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
441   }
442 
443   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
444        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
445     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
446          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
447       setTruncStoreAction((MVT::SimpleValueType)VT,
448                           (MVT::SimpleValueType)InnerVT, Expand);
449     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
450     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
451     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
452   }
453 
454   if (Subtarget->hasNEON()) {
455     addDRTypeForNEON(MVT::v2f32);
456     addDRTypeForNEON(MVT::v8i8);
457     addDRTypeForNEON(MVT::v4i16);
458     addDRTypeForNEON(MVT::v2i32);
459     addDRTypeForNEON(MVT::v1i64);
460 
461     addQRTypeForNEON(MVT::v4f32);
462     addQRTypeForNEON(MVT::v2f64);
463     addQRTypeForNEON(MVT::v16i8);
464     addQRTypeForNEON(MVT::v8i16);
465     addQRTypeForNEON(MVT::v4i32);
466     addQRTypeForNEON(MVT::v2i64);
467 
468     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
469     // neither Neon nor VFP support any arithmetic operations on it.
470     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
471     // supported for v4f32.
472     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
473     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
474     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
475     // FIXME: Code duplication: FDIV and FREM are expanded always, see
476     // ARMTargetLowering::addTypeForNEON method for details.
477     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
478     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
479     // FIXME: Create unittest.
480     // In another words, find a way when "copysign" appears in DAG with vector
481     // operands.
482     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
483     // FIXME: Code duplication: SETCC has custom operation action, see
484     // ARMTargetLowering::addTypeForNEON method for details.
485     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
486     // FIXME: Create unittest for FNEG and for FABS.
487     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
488     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
489     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
490     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
491     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
492     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
493     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
494     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
495     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
496     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
497     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
498     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
499     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
500     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
501     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
502     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
503     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
504     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
505 
506     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
507     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
508     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
509     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
510     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
511     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
512     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
513     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
514     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
515     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
516 
517     // Neon does not support some operations on v1i64 and v2i64 types.
518     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
519     // Custom handling for some quad-vector types to detect VMULL.
520     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
521     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
522     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
523     // Custom handling for some vector types to avoid expensive expansions
524     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
525     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
526     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
527     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
528     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
529     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
530     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
531     // a destination type that is wider than the source.
532     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
533     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
534 
535     setTargetDAGCombine(ISD::INTRINSIC_VOID);
536     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
537     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
538     setTargetDAGCombine(ISD::SHL);
539     setTargetDAGCombine(ISD::SRL);
540     setTargetDAGCombine(ISD::SRA);
541     setTargetDAGCombine(ISD::SIGN_EXTEND);
542     setTargetDAGCombine(ISD::ZERO_EXTEND);
543     setTargetDAGCombine(ISD::ANY_EXTEND);
544     setTargetDAGCombine(ISD::SELECT_CC);
545     setTargetDAGCombine(ISD::BUILD_VECTOR);
546     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
547     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
548     setTargetDAGCombine(ISD::STORE);
549     setTargetDAGCombine(ISD::FP_TO_SINT);
550     setTargetDAGCombine(ISD::FP_TO_UINT);
551     setTargetDAGCombine(ISD::FDIV);
552 
553     setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Expand);
554   }
555 
556   computeRegisterProperties();
557 
558   // ARM does not have f32 extending load.
559   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
560 
561   // ARM does not have i1 sign extending load.
562   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
563 
564   // ARM supports all 4 flavors of integer indexed load / store.
565   if (!Subtarget->isThumb1Only()) {
566     for (unsigned im = (unsigned)ISD::PRE_INC;
567          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
568       setIndexedLoadAction(im,  MVT::i1,  Legal);
569       setIndexedLoadAction(im,  MVT::i8,  Legal);
570       setIndexedLoadAction(im,  MVT::i16, Legal);
571       setIndexedLoadAction(im,  MVT::i32, Legal);
572       setIndexedStoreAction(im, MVT::i1,  Legal);
573       setIndexedStoreAction(im, MVT::i8,  Legal);
574       setIndexedStoreAction(im, MVT::i16, Legal);
575       setIndexedStoreAction(im, MVT::i32, Legal);
576     }
577   }
578 
579   // i64 operation support.
580   setOperationAction(ISD::MUL,     MVT::i64, Expand);
581   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
582   if (Subtarget->isThumb1Only()) {
583     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
584     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
585   }
586   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
587       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
588     setOperationAction(ISD::MULHS, MVT::i32, Expand);
589 
590   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
591   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
592   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
593   setOperationAction(ISD::SRL,       MVT::i64, Custom);
594   setOperationAction(ISD::SRA,       MVT::i64, Custom);
595 
596   if (!Subtarget->isThumb1Only()) {
597     // FIXME: We should do this for Thumb1 as well.
598     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
599     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
600     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
601     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
602   }
603 
604   // ARM does not have ROTL.
605   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
606   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
607   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
608   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
609     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
610 
611   // These just redirect to CTTZ and CTLZ on ARM.
612   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
613   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
614 
615   // Only ARMv6 has BSWAP.
616   if (!Subtarget->hasV6Ops())
617     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
618 
619   // These are expanded into libcalls.
620   if (!Subtarget->hasDivide() || !Subtarget->isThumb2()) {
621     // v7M has a hardware divider
622     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
623     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
624   }
625   setOperationAction(ISD::SREM,  MVT::i32, Expand);
626   setOperationAction(ISD::UREM,  MVT::i32, Expand);
627   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
628   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
629 
630   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
631   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
632   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
633   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
634   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
635 
636   setOperationAction(ISD::TRAP, MVT::Other, Legal);
637 
638   // Use the default implementation.
639   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
640   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
641   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
642   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
643   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
644   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
645   setOperationAction(ISD::EHSELECTION,        MVT::i32,   Expand);
646   setOperationAction(ISD::EXCEPTIONADDR,      MVT::i32,   Expand);
647   setExceptionPointerRegister(ARM::R0);
648   setExceptionSelectorRegister(ARM::R1);
649 
650   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
651   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
652   // the default expansion.
653   // FIXME: This should be checking for v6k, not just v6.
654   if (Subtarget->hasDataBarrier() ||
655       (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
656     // membarrier needs custom lowering; the rest are legal and handled
657     // normally.
658     setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
659     setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
660     // Custom lowering for 64-bit ops
661     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i64, Custom);
662     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i64, Custom);
663     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i64, Custom);
664     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i64, Custom);
665     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i64, Custom);
666     setOperationAction(ISD::ATOMIC_SWAP,  MVT::i64, Custom);
667     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
668     // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
669     setInsertFencesForAtomic(true);
670   } else {
671     // Set them all for expansion, which will force libcalls.
672     setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
673     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
674     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
675     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
676     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
677     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
678     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
679     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
680     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
681     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
682     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
683     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
684     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
685     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
686     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
687     // Unordered/Monotonic case.
688     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
689     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
690     // Since the libcalls include locking, fold in the fences
691     setShouldFoldAtomicFences(true);
692   }
693 
694   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
695 
696   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
697   if (!Subtarget->hasV6Ops()) {
698     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
699     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
700   }
701   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
702 
703   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
704       !Subtarget->isThumb1Only()) {
705     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
706     // iff target supports vfp2.
707     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
708     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
709   }
710 
711   // We want to custom lower some of our intrinsics.
712   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
713   if (Subtarget->isTargetDarwin()) {
714     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
715     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
716     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
717   }
718 
719   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
720   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
721   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
722   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
723   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
724   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
725   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
726   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
727   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
728 
729   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
730   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
731   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
732   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
733   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
734 
735   // We don't support sin/cos/fmod/copysign/pow
736   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
737   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
738   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
739   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
740   setOperationAction(ISD::FREM,      MVT::f64, Expand);
741   setOperationAction(ISD::FREM,      MVT::f32, Expand);
742   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
743       !Subtarget->isThumb1Only()) {
744     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
745     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
746   }
747   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
748   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
749 
750   setOperationAction(ISD::FMA, MVT::f64, Expand);
751   setOperationAction(ISD::FMA, MVT::f32, Expand);
752 
753   // Various VFP goodness
754   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
755     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
756     if (Subtarget->hasVFP2()) {
757       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
758       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
759       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
760       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
761     }
762     // Special handling for half-precision FP.
763     if (!Subtarget->hasFP16()) {
764       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
765       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
766     }
767   }
768 
769   // We have target-specific dag combine patterns for the following nodes:
770   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
771   setTargetDAGCombine(ISD::ADD);
772   setTargetDAGCombine(ISD::SUB);
773   setTargetDAGCombine(ISD::MUL);
774 
775   if (Subtarget->hasV6T2Ops() || Subtarget->hasNEON())
776     setTargetDAGCombine(ISD::OR);
777   if (Subtarget->hasNEON())
778     setTargetDAGCombine(ISD::AND);
779 
780   setStackPointerRegisterToSaveRestore(ARM::SP);
781 
782   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
783       !Subtarget->hasVFP2())
784     setSchedulingPreference(Sched::RegPressure);
785   else
786     setSchedulingPreference(Sched::Hybrid);
787 
788   //// temporary - rewrite interface to use type
789   maxStoresPerMemcpy = maxStoresPerMemcpyOptSize = 1;
790   maxStoresPerMemset = 16;
791   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
792 
793   // On ARM arguments smaller than 4 bytes are extended, so all arguments
794   // are at least 4 bytes aligned.
795   setMinStackArgumentAlignment(4);
796 
797   benefitFromCodePlacementOpt = true;
798 
799   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
800 }
801 
802 // FIXME: It might make sense to define the representative register class as the
803 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
804 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
805 // SPR's representative would be DPR_VFP2. This should work well if register
806 // pressure tracking were modified such that a register use would increment the
807 // pressure of the register class's representative and all of it's super
808 // classes' representatives transitively. We have not implemented this because
809 // of the difficulty prior to coalescing of modeling operand register classes
810 // due to the common occurrence of cross class copies and subregister insertions
811 // and extractions.
812 std::pair<const TargetRegisterClass*, uint8_t>
813 ARMTargetLowering::findRepresentativeClass(EVT VT) const{
814   const TargetRegisterClass *RRC = 0;
815   uint8_t Cost = 1;
816   switch (VT.getSimpleVT().SimpleTy) {
817   default:
818     return TargetLowering::findRepresentativeClass(VT);
819   // Use DPR as representative register class for all floating point
820   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
821   // the cost is 1 for both f32 and f64.
822   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
823   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
824     RRC = ARM::DPRRegisterClass;
825     // When NEON is used for SP, only half of the register file is available
826     // because operations that define both SP and DP results will be constrained
827     // to the VFP2 class (D0-D15). We currently model this constraint prior to
828     // coalescing by double-counting the SP regs. See the FIXME above.
829     if (Subtarget->useNEONForSinglePrecisionFP())
830       Cost = 2;
831     break;
832   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
833   case MVT::v4f32: case MVT::v2f64:
834     RRC = ARM::DPRRegisterClass;
835     Cost = 2;
836     break;
837   case MVT::v4i64:
838     RRC = ARM::DPRRegisterClass;
839     Cost = 4;
840     break;
841   case MVT::v8i64:
842     RRC = ARM::DPRRegisterClass;
843     Cost = 8;
844     break;
845   }
846   return std::make_pair(RRC, Cost);
847 }
848 
849 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
850   switch (Opcode) {
851   default: return 0;
852   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
853   case ARMISD::WrapperDYN:    return "ARMISD::WrapperDYN";
854   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
855   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
856   case ARMISD::CALL:          return "ARMISD::CALL";
857   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
858   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
859   case ARMISD::tCALL:         return "ARMISD::tCALL";
860   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
861   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
862   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
863   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
864   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
865   case ARMISD::CMP:           return "ARMISD::CMP";
866   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
867   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
868   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
869   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
870   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
871   case ARMISD::CMOV:          return "ARMISD::CMOV";
872 
873   case ARMISD::RBIT:          return "ARMISD::RBIT";
874 
875   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
876   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
877   case ARMISD::SITOF:         return "ARMISD::SITOF";
878   case ARMISD::UITOF:         return "ARMISD::UITOF";
879 
880   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
881   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
882   case ARMISD::RRX:           return "ARMISD::RRX";
883 
884   case ARMISD::ADDC:          return "ARMISD::ADDC";
885   case ARMISD::ADDE:          return "ARMISD::ADDE";
886   case ARMISD::SUBC:          return "ARMISD::SUBC";
887   case ARMISD::SUBE:          return "ARMISD::SUBE";
888 
889   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
890   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
891 
892   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
893   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
894 
895   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
896 
897   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
898 
899   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
900 
901   case ARMISD::MEMBARRIER:    return "ARMISD::MEMBARRIER";
902   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
903 
904   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
905 
906   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
907   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
908   case ARMISD::VCGE:          return "ARMISD::VCGE";
909   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
910   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
911   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
912   case ARMISD::VCGT:          return "ARMISD::VCGT";
913   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
914   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
915   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
916   case ARMISD::VTST:          return "ARMISD::VTST";
917 
918   case ARMISD::VSHL:          return "ARMISD::VSHL";
919   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
920   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
921   case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
922   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
923   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
924   case ARMISD::VSHRN:         return "ARMISD::VSHRN";
925   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
926   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
927   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
928   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
929   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
930   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
931   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
932   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
933   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
934   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
935   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
936   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
937   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
938   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
939   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
940   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
941   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
942   case ARMISD::VDUP:          return "ARMISD::VDUP";
943   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
944   case ARMISD::VEXT:          return "ARMISD::VEXT";
945   case ARMISD::VREV64:        return "ARMISD::VREV64";
946   case ARMISD::VREV32:        return "ARMISD::VREV32";
947   case ARMISD::VREV16:        return "ARMISD::VREV16";
948   case ARMISD::VZIP:          return "ARMISD::VZIP";
949   case ARMISD::VUZP:          return "ARMISD::VUZP";
950   case ARMISD::VTRN:          return "ARMISD::VTRN";
951   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
952   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
953   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
954   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
955   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
956   case ARMISD::FMAX:          return "ARMISD::FMAX";
957   case ARMISD::FMIN:          return "ARMISD::FMIN";
958   case ARMISD::BFI:           return "ARMISD::BFI";
959   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
960   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
961   case ARMISD::VBSL:          return "ARMISD::VBSL";
962   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
963   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
964   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
965   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
966   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
967   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
968   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
969   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
970   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
971   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
972   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
973   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
974   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
975   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
976   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
977   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
978   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
979   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
980   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
981   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
982   }
983 }
984 
985 EVT ARMTargetLowering::getSetCCResultType(EVT VT) const {
986   if (!VT.isVector()) return getPointerTy();
987   return VT.changeVectorElementTypeToInteger();
988 }
989 
990 /// getRegClassFor - Return the register class that should be used for the
991 /// specified value type.
992 TargetRegisterClass *ARMTargetLowering::getRegClassFor(EVT VT) const {
993   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
994   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
995   // load / store 4 to 8 consecutive D registers.
996   if (Subtarget->hasNEON()) {
997     if (VT == MVT::v4i64)
998       return ARM::QQPRRegisterClass;
999     else if (VT == MVT::v8i64)
1000       return ARM::QQQQPRRegisterClass;
1001   }
1002   return TargetLowering::getRegClassFor(VT);
1003 }
1004 
1005 // Create a fast isel object.
1006 FastISel *
1007 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
1008   return ARM::createFastISel(funcInfo);
1009 }
1010 
1011 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1012 /// be used for loads / stores from the global.
1013 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1014   return (Subtarget->isThumb1Only() ? 127 : 4095);
1015 }
1016 
1017 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1018   unsigned NumVals = N->getNumValues();
1019   if (!NumVals)
1020     return Sched::RegPressure;
1021 
1022   for (unsigned i = 0; i != NumVals; ++i) {
1023     EVT VT = N->getValueType(i);
1024     if (VT == MVT::Glue || VT == MVT::Other)
1025       continue;
1026     if (VT.isFloatingPoint() || VT.isVector())
1027       return Sched::ILP;
1028   }
1029 
1030   if (!N->isMachineOpcode())
1031     return Sched::RegPressure;
1032 
1033   // Load are scheduled for latency even if there instruction itinerary
1034   // is not available.
1035   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1036   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1037 
1038   if (MCID.getNumDefs() == 0)
1039     return Sched::RegPressure;
1040   if (!Itins->isEmpty() &&
1041       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1042     return Sched::ILP;
1043 
1044   return Sched::RegPressure;
1045 }
1046 
1047 //===----------------------------------------------------------------------===//
1048 // Lowering Code
1049 //===----------------------------------------------------------------------===//
1050 
1051 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1052 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1053   switch (CC) {
1054   default: llvm_unreachable("Unknown condition code!");
1055   case ISD::SETNE:  return ARMCC::NE;
1056   case ISD::SETEQ:  return ARMCC::EQ;
1057   case ISD::SETGT:  return ARMCC::GT;
1058   case ISD::SETGE:  return ARMCC::GE;
1059   case ISD::SETLT:  return ARMCC::LT;
1060   case ISD::SETLE:  return ARMCC::LE;
1061   case ISD::SETUGT: return ARMCC::HI;
1062   case ISD::SETUGE: return ARMCC::HS;
1063   case ISD::SETULT: return ARMCC::LO;
1064   case ISD::SETULE: return ARMCC::LS;
1065   }
1066 }
1067 
1068 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1069 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1070                         ARMCC::CondCodes &CondCode2) {
1071   CondCode2 = ARMCC::AL;
1072   switch (CC) {
1073   default: llvm_unreachable("Unknown FP condition!");
1074   case ISD::SETEQ:
1075   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1076   case ISD::SETGT:
1077   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1078   case ISD::SETGE:
1079   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1080   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1081   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1082   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1083   case ISD::SETO:   CondCode = ARMCC::VC; break;
1084   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1085   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1086   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1087   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1088   case ISD::SETLT:
1089   case ISD::SETULT: CondCode = ARMCC::LT; break;
1090   case ISD::SETLE:
1091   case ISD::SETULE: CondCode = ARMCC::LE; break;
1092   case ISD::SETNE:
1093   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1094   }
1095 }
1096 
1097 //===----------------------------------------------------------------------===//
1098 //                      Calling Convention Implementation
1099 //===----------------------------------------------------------------------===//
1100 
1101 #include "ARMGenCallingConv.inc"
1102 
1103 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1104 /// given CallingConvention value.
1105 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1106                                                  bool Return,
1107                                                  bool isVarArg) const {
1108   switch (CC) {
1109   default:
1110     llvm_unreachable("Unsupported calling convention");
1111   case CallingConv::Fast:
1112     if (Subtarget->hasVFP2() && !isVarArg) {
1113       if (!Subtarget->isAAPCS_ABI())
1114         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1115       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1116       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1117     }
1118     // Fallthrough
1119   case CallingConv::C: {
1120     // Use target triple & subtarget features to do actual dispatch.
1121     if (!Subtarget->isAAPCS_ABI())
1122       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1123     else if (Subtarget->hasVFP2() &&
1124              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1125              !isVarArg)
1126       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1127     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1128   }
1129   case CallingConv::ARM_AAPCS_VFP:
1130     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1131   case CallingConv::ARM_AAPCS:
1132     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1133   case CallingConv::ARM_APCS:
1134     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1135   }
1136 }
1137 
1138 /// LowerCallResult - Lower the result values of a call into the
1139 /// appropriate copies out of appropriate physical registers.
1140 SDValue
1141 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1142                                    CallingConv::ID CallConv, bool isVarArg,
1143                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1144                                    DebugLoc dl, SelectionDAG &DAG,
1145                                    SmallVectorImpl<SDValue> &InVals) const {
1146 
1147   // Assign locations to each value returned by this call.
1148   SmallVector<CCValAssign, 16> RVLocs;
1149   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1150                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1151   CCInfo.AnalyzeCallResult(Ins,
1152                            CCAssignFnForNode(CallConv, /* Return*/ true,
1153                                              isVarArg));
1154 
1155   // Copy all of the result registers out of their specified physreg.
1156   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1157     CCValAssign VA = RVLocs[i];
1158 
1159     SDValue Val;
1160     if (VA.needsCustom()) {
1161       // Handle f64 or half of a v2f64.
1162       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1163                                       InFlag);
1164       Chain = Lo.getValue(1);
1165       InFlag = Lo.getValue(2);
1166       VA = RVLocs[++i]; // skip ahead to next loc
1167       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1168                                       InFlag);
1169       Chain = Hi.getValue(1);
1170       InFlag = Hi.getValue(2);
1171       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1172 
1173       if (VA.getLocVT() == MVT::v2f64) {
1174         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1175         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1176                           DAG.getConstant(0, MVT::i32));
1177 
1178         VA = RVLocs[++i]; // skip ahead to next loc
1179         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1180         Chain = Lo.getValue(1);
1181         InFlag = Lo.getValue(2);
1182         VA = RVLocs[++i]; // skip ahead to next loc
1183         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1184         Chain = Hi.getValue(1);
1185         InFlag = Hi.getValue(2);
1186         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1187         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1188                           DAG.getConstant(1, MVT::i32));
1189       }
1190     } else {
1191       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1192                                InFlag);
1193       Chain = Val.getValue(1);
1194       InFlag = Val.getValue(2);
1195     }
1196 
1197     switch (VA.getLocInfo()) {
1198     default: llvm_unreachable("Unknown loc info!");
1199     case CCValAssign::Full: break;
1200     case CCValAssign::BCvt:
1201       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1202       break;
1203     }
1204 
1205     InVals.push_back(Val);
1206   }
1207 
1208   return Chain;
1209 }
1210 
1211 /// LowerMemOpCallTo - Store the argument to the stack.
1212 SDValue
1213 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1214                                     SDValue StackPtr, SDValue Arg,
1215                                     DebugLoc dl, SelectionDAG &DAG,
1216                                     const CCValAssign &VA,
1217                                     ISD::ArgFlagsTy Flags) const {
1218   unsigned LocMemOffset = VA.getLocMemOffset();
1219   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1220   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1221   return DAG.getStore(Chain, dl, Arg, PtrOff,
1222                       MachinePointerInfo::getStack(LocMemOffset),
1223                       false, false, 0);
1224 }
1225 
1226 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
1227                                          SDValue Chain, SDValue &Arg,
1228                                          RegsToPassVector &RegsToPass,
1229                                          CCValAssign &VA, CCValAssign &NextVA,
1230                                          SDValue &StackPtr,
1231                                          SmallVector<SDValue, 8> &MemOpChains,
1232                                          ISD::ArgFlagsTy Flags) const {
1233 
1234   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1235                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1236   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1237 
1238   if (NextVA.isRegLoc())
1239     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1240   else {
1241     assert(NextVA.isMemLoc());
1242     if (StackPtr.getNode() == 0)
1243       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1244 
1245     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1246                                            dl, DAG, NextVA,
1247                                            Flags));
1248   }
1249 }
1250 
1251 /// LowerCall - Lowering a call into a callseq_start <-
1252 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1253 /// nodes.
1254 SDValue
1255 ARMTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1256                              CallingConv::ID CallConv, bool isVarArg,
1257                              bool &isTailCall,
1258                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1259                              const SmallVectorImpl<SDValue> &OutVals,
1260                              const SmallVectorImpl<ISD::InputArg> &Ins,
1261                              DebugLoc dl, SelectionDAG &DAG,
1262                              SmallVectorImpl<SDValue> &InVals) const {
1263   MachineFunction &MF = DAG.getMachineFunction();
1264   bool IsStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1265   bool IsSibCall = false;
1266   // Disable tail calls if they're not supported.
1267   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1268     isTailCall = false;
1269   if (isTailCall) {
1270     // Check if it's really possible to do a tail call.
1271     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1272                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1273                                                    Outs, OutVals, Ins, DAG);
1274     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1275     // detected sibcalls.
1276     if (isTailCall) {
1277       ++NumTailCalls;
1278       IsSibCall = true;
1279     }
1280   }
1281 
1282   // Analyze operands of the call, assigning locations to each operand.
1283   SmallVector<CCValAssign, 16> ArgLocs;
1284   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1285                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1286   CCInfo.AnalyzeCallOperands(Outs,
1287                              CCAssignFnForNode(CallConv, /* Return*/ false,
1288                                                isVarArg));
1289 
1290   // Get a count of how many bytes are to be pushed on the stack.
1291   unsigned NumBytes = CCInfo.getNextStackOffset();
1292 
1293   // For tail calls, memory operands are available in our caller's stack.
1294   if (IsSibCall)
1295     NumBytes = 0;
1296 
1297   // Adjust the stack pointer for the new arguments...
1298   // These operations are automatically eliminated by the prolog/epilog pass
1299   if (!IsSibCall)
1300     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1301 
1302   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1303 
1304   RegsToPassVector RegsToPass;
1305   SmallVector<SDValue, 8> MemOpChains;
1306 
1307   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1308   // of tail call optimization, arguments are handled later.
1309   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1310        i != e;
1311        ++i, ++realArgIdx) {
1312     CCValAssign &VA = ArgLocs[i];
1313     SDValue Arg = OutVals[realArgIdx];
1314     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1315     bool isByVal = Flags.isByVal();
1316 
1317     // Promote the value if needed.
1318     switch (VA.getLocInfo()) {
1319     default: llvm_unreachable("Unknown loc info!");
1320     case CCValAssign::Full: break;
1321     case CCValAssign::SExt:
1322       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1323       break;
1324     case CCValAssign::ZExt:
1325       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1326       break;
1327     case CCValAssign::AExt:
1328       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1329       break;
1330     case CCValAssign::BCvt:
1331       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1332       break;
1333     }
1334 
1335     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1336     if (VA.needsCustom()) {
1337       if (VA.getLocVT() == MVT::v2f64) {
1338         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1339                                   DAG.getConstant(0, MVT::i32));
1340         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1341                                   DAG.getConstant(1, MVT::i32));
1342 
1343         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1344                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1345 
1346         VA = ArgLocs[++i]; // skip ahead to next loc
1347         if (VA.isRegLoc()) {
1348           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1349                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1350         } else {
1351           assert(VA.isMemLoc());
1352 
1353           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1354                                                  dl, DAG, VA, Flags));
1355         }
1356       } else {
1357         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1358                          StackPtr, MemOpChains, Flags);
1359       }
1360     } else if (VA.isRegLoc()) {
1361       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1362     } else if (isByVal) {
1363       assert(VA.isMemLoc());
1364       unsigned offset = 0;
1365 
1366       // True if this byval aggregate will be split between registers
1367       // and memory.
1368       if (CCInfo.isFirstByValRegValid()) {
1369         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1370         unsigned int i, j;
1371         for (i = 0, j = CCInfo.getFirstByValReg(); j < ARM::R4; i++, j++) {
1372           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1373           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1374           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1375                                      MachinePointerInfo(),
1376                                      false, false, false, 0);
1377           MemOpChains.push_back(Load.getValue(1));
1378           RegsToPass.push_back(std::make_pair(j, Load));
1379         }
1380         offset = ARM::R4 - CCInfo.getFirstByValReg();
1381         CCInfo.clearFirstByValReg();
1382       }
1383 
1384       unsigned LocMemOffset = VA.getLocMemOffset();
1385       SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1386       SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1387                                 StkPtrOff);
1388       SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1389       SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1390       SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1391                                          MVT::i32);
1392       MemOpChains.push_back(DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
1393                                           Flags.getByValAlign(),
1394                                           /*isVolatile=*/false,
1395                                           /*AlwaysInline=*/false,
1396                                           MachinePointerInfo(0),
1397                                           MachinePointerInfo(0)));
1398 
1399     } else if (!IsSibCall) {
1400       assert(VA.isMemLoc());
1401 
1402       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1403                                              dl, DAG, VA, Flags));
1404     }
1405   }
1406 
1407   if (!MemOpChains.empty())
1408     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1409                         &MemOpChains[0], MemOpChains.size());
1410 
1411   // Build a sequence of copy-to-reg nodes chained together with token chain
1412   // and flag operands which copy the outgoing args into the appropriate regs.
1413   SDValue InFlag;
1414   // Tail call byval lowering might overwrite argument registers so in case of
1415   // tail call optimization the copies to registers are lowered later.
1416   if (!isTailCall)
1417     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1418       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1419                                RegsToPass[i].second, InFlag);
1420       InFlag = Chain.getValue(1);
1421     }
1422 
1423   // For tail calls lower the arguments to the 'real' stack slot.
1424   if (isTailCall) {
1425     // Force all the incoming stack arguments to be loaded from the stack
1426     // before any new outgoing arguments are stored to the stack, because the
1427     // outgoing stack slots may alias the incoming argument stack slots, and
1428     // the alias isn't otherwise explicit. This is slightly more conservative
1429     // than necessary, because it means that each store effectively depends
1430     // on every argument instead of just those arguments it would clobber.
1431 
1432     // Do not flag preceding copytoreg stuff together with the following stuff.
1433     InFlag = SDValue();
1434     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1435       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1436                                RegsToPass[i].second, InFlag);
1437       InFlag = Chain.getValue(1);
1438     }
1439     InFlag =SDValue();
1440   }
1441 
1442   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1443   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1444   // node so that legalize doesn't hack it.
1445   bool isDirect = false;
1446   bool isARMFunc = false;
1447   bool isLocalARMFunc = false;
1448   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1449 
1450   if (EnableARMLongCalls) {
1451     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1452             && "long-calls with non-static relocation model!");
1453     // Handle a global address or an external symbol. If it's not one of
1454     // those, the target's already in a register, so we don't need to do
1455     // anything extra.
1456     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1457       const GlobalValue *GV = G->getGlobal();
1458       // Create a constant pool entry for the callee address
1459       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1460       ARMConstantPoolValue *CPV =
1461         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1462 
1463       // Get the address of the callee into a register
1464       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1465       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1466       Callee = DAG.getLoad(getPointerTy(), dl,
1467                            DAG.getEntryNode(), CPAddr,
1468                            MachinePointerInfo::getConstantPool(),
1469                            false, false, false, 0);
1470     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1471       const char *Sym = S->getSymbol();
1472 
1473       // Create a constant pool entry for the callee address
1474       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1475       ARMConstantPoolValue *CPV =
1476         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1477                                       ARMPCLabelIndex, 0);
1478       // Get the address of the callee into a register
1479       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1480       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1481       Callee = DAG.getLoad(getPointerTy(), dl,
1482                            DAG.getEntryNode(), CPAddr,
1483                            MachinePointerInfo::getConstantPool(),
1484                            false, false, false, 0);
1485     }
1486   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1487     const GlobalValue *GV = G->getGlobal();
1488     isDirect = true;
1489     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1490     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1491                    getTargetMachine().getRelocationModel() != Reloc::Static;
1492     isARMFunc = !Subtarget->isThumb() || isStub;
1493     // ARM call to a local ARM function is predicable.
1494     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1495     // tBX takes a register source operand.
1496     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1497       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1498       ARMConstantPoolValue *CPV =
1499         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1500       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1501       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1502       Callee = DAG.getLoad(getPointerTy(), dl,
1503                            DAG.getEntryNode(), CPAddr,
1504                            MachinePointerInfo::getConstantPool(),
1505                            false, false, false, 0);
1506       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1507       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1508                            getPointerTy(), Callee, PICLabel);
1509     } else {
1510       // On ELF targets for PIC code, direct calls should go through the PLT
1511       unsigned OpFlags = 0;
1512       if (Subtarget->isTargetELF() &&
1513                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1514         OpFlags = ARMII::MO_PLT;
1515       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1516     }
1517   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1518     isDirect = true;
1519     bool isStub = Subtarget->isTargetDarwin() &&
1520                   getTargetMachine().getRelocationModel() != Reloc::Static;
1521     isARMFunc = !Subtarget->isThumb() || isStub;
1522     // tBX takes a register source operand.
1523     const char *Sym = S->getSymbol();
1524     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1525       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1526       ARMConstantPoolValue *CPV =
1527         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1528                                       ARMPCLabelIndex, 4);
1529       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1530       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1531       Callee = DAG.getLoad(getPointerTy(), dl,
1532                            DAG.getEntryNode(), CPAddr,
1533                            MachinePointerInfo::getConstantPool(),
1534                            false, false, false, 0);
1535       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1536       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1537                            getPointerTy(), Callee, PICLabel);
1538     } else {
1539       unsigned OpFlags = 0;
1540       // On ELF targets for PIC code, direct calls should go through the PLT
1541       if (Subtarget->isTargetELF() &&
1542                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1543         OpFlags = ARMII::MO_PLT;
1544       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1545     }
1546   }
1547 
1548   // FIXME: handle tail calls differently.
1549   unsigned CallOpc;
1550   if (Subtarget->isThumb()) {
1551     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1552       CallOpc = ARMISD::CALL_NOLINK;
1553     else
1554       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1555   } else {
1556     CallOpc = (isDirect || Subtarget->hasV5TOps())
1557       ? (isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL)
1558       : ARMISD::CALL_NOLINK;
1559   }
1560 
1561   std::vector<SDValue> Ops;
1562   Ops.push_back(Chain);
1563   Ops.push_back(Callee);
1564 
1565   // Add argument registers to the end of the list so that they are known live
1566   // into the call.
1567   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1568     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1569                                   RegsToPass[i].second.getValueType()));
1570 
1571   if (InFlag.getNode())
1572     Ops.push_back(InFlag);
1573 
1574   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1575   if (isTailCall)
1576     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1577 
1578   // Returns a chain and a flag for retval copy to use.
1579   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1580   InFlag = Chain.getValue(1);
1581 
1582   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1583                              DAG.getIntPtrConstant(0, true), InFlag);
1584   if (!Ins.empty())
1585     InFlag = Chain.getValue(1);
1586 
1587   // Handle result values, copying them out of physregs into vregs that we
1588   // return.
1589   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1590                          dl, DAG, InVals);
1591 }
1592 
1593 /// HandleByVal - Every parameter *after* a byval parameter is passed
1594 /// on the stack.  Remember the next parameter register to allocate,
1595 /// and then confiscate the rest of the parameter registers to insure
1596 /// this.
1597 void
1598 llvm::ARMTargetLowering::HandleByVal(CCState *State, unsigned &size) const {
1599   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1600   assert((State->getCallOrPrologue() == Prologue ||
1601           State->getCallOrPrologue() == Call) &&
1602          "unhandled ParmContext");
1603   if ((!State->isFirstByValRegValid()) &&
1604       (ARM::R0 <= reg) && (reg <= ARM::R3)) {
1605     State->setFirstByValReg(reg);
1606     // At a call site, a byval parameter that is split between
1607     // registers and memory needs its size truncated here.  In a
1608     // function prologue, such byval parameters are reassembled in
1609     // memory, and are not truncated.
1610     if (State->getCallOrPrologue() == Call) {
1611       unsigned excess = 4 * (ARM::R4 - reg);
1612       assert(size >= excess && "expected larger existing stack allocation");
1613       size -= excess;
1614     }
1615   }
1616   // Confiscate any remaining parameter registers to preclude their
1617   // assignment to subsequent parameters.
1618   while (State->AllocateReg(GPRArgRegs, 4))
1619     ;
1620 }
1621 
1622 /// MatchingStackOffset - Return true if the given stack call argument is
1623 /// already available in the same position (relatively) of the caller's
1624 /// incoming argument stack.
1625 static
1626 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1627                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1628                          const ARMInstrInfo *TII) {
1629   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1630   int FI = INT_MAX;
1631   if (Arg.getOpcode() == ISD::CopyFromReg) {
1632     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1633     if (!TargetRegisterInfo::isVirtualRegister(VR))
1634       return false;
1635     MachineInstr *Def = MRI->getVRegDef(VR);
1636     if (!Def)
1637       return false;
1638     if (!Flags.isByVal()) {
1639       if (!TII->isLoadFromStackSlot(Def, FI))
1640         return false;
1641     } else {
1642       return false;
1643     }
1644   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1645     if (Flags.isByVal())
1646       // ByVal argument is passed in as a pointer but it's now being
1647       // dereferenced. e.g.
1648       // define @foo(%struct.X* %A) {
1649       //   tail call @bar(%struct.X* byval %A)
1650       // }
1651       return false;
1652     SDValue Ptr = Ld->getBasePtr();
1653     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1654     if (!FINode)
1655       return false;
1656     FI = FINode->getIndex();
1657   } else
1658     return false;
1659 
1660   assert(FI != INT_MAX);
1661   if (!MFI->isFixedObjectIndex(FI))
1662     return false;
1663   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1664 }
1665 
1666 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1667 /// for tail call optimization. Targets which want to do tail call
1668 /// optimization should implement this function.
1669 bool
1670 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1671                                                      CallingConv::ID CalleeCC,
1672                                                      bool isVarArg,
1673                                                      bool isCalleeStructRet,
1674                                                      bool isCallerStructRet,
1675                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1676                                     const SmallVectorImpl<SDValue> &OutVals,
1677                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1678                                                      SelectionDAG& DAG) const {
1679   const Function *CallerF = DAG.getMachineFunction().getFunction();
1680   CallingConv::ID CallerCC = CallerF->getCallingConv();
1681   bool CCMatch = CallerCC == CalleeCC;
1682 
1683   // Look for obvious safe cases to perform tail call optimization that do not
1684   // require ABI changes. This is what gcc calls sibcall.
1685 
1686   // Do not sibcall optimize vararg calls unless the call site is not passing
1687   // any arguments.
1688   if (isVarArg && !Outs.empty())
1689     return false;
1690 
1691   // Also avoid sibcall optimization if either caller or callee uses struct
1692   // return semantics.
1693   if (isCalleeStructRet || isCallerStructRet)
1694     return false;
1695 
1696   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1697   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1698   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1699   // support in the assembler and linker to be used. This would need to be
1700   // fixed to fully support tail calls in Thumb1.
1701   //
1702   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1703   // LR.  This means if we need to reload LR, it takes an extra instructions,
1704   // which outweighs the value of the tail call; but here we don't know yet
1705   // whether LR is going to be used.  Probably the right approach is to
1706   // generate the tail call here and turn it back into CALL/RET in
1707   // emitEpilogue if LR is used.
1708 
1709   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1710   // but we need to make sure there are enough registers; the only valid
1711   // registers are the 4 used for parameters.  We don't currently do this
1712   // case.
1713   if (Subtarget->isThumb1Only())
1714     return false;
1715 
1716   // If the calling conventions do not match, then we'd better make sure the
1717   // results are returned in the same way as what the caller expects.
1718   if (!CCMatch) {
1719     SmallVector<CCValAssign, 16> RVLocs1;
1720     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1721                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1722     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1723 
1724     SmallVector<CCValAssign, 16> RVLocs2;
1725     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1726                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1727     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1728 
1729     if (RVLocs1.size() != RVLocs2.size())
1730       return false;
1731     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1732       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1733         return false;
1734       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1735         return false;
1736       if (RVLocs1[i].isRegLoc()) {
1737         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1738           return false;
1739       } else {
1740         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1741           return false;
1742       }
1743     }
1744   }
1745 
1746   // If the callee takes no arguments then go on to check the results of the
1747   // call.
1748   if (!Outs.empty()) {
1749     // Check if stack adjustment is needed. For now, do not do this if any
1750     // argument is passed on the stack.
1751     SmallVector<CCValAssign, 16> ArgLocs;
1752     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1753                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1754     CCInfo.AnalyzeCallOperands(Outs,
1755                                CCAssignFnForNode(CalleeCC, false, isVarArg));
1756     if (CCInfo.getNextStackOffset()) {
1757       MachineFunction &MF = DAG.getMachineFunction();
1758 
1759       // Check if the arguments are already laid out in the right way as
1760       // the caller's fixed stack objects.
1761       MachineFrameInfo *MFI = MF.getFrameInfo();
1762       const MachineRegisterInfo *MRI = &MF.getRegInfo();
1763       const ARMInstrInfo *TII =
1764         ((ARMTargetMachine&)getTargetMachine()).getInstrInfo();
1765       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1766            i != e;
1767            ++i, ++realArgIdx) {
1768         CCValAssign &VA = ArgLocs[i];
1769         EVT RegVT = VA.getLocVT();
1770         SDValue Arg = OutVals[realArgIdx];
1771         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1772         if (VA.getLocInfo() == CCValAssign::Indirect)
1773           return false;
1774         if (VA.needsCustom()) {
1775           // f64 and vector types are split into multiple registers or
1776           // register/stack-slot combinations.  The types will not match
1777           // the registers; give up on memory f64 refs until we figure
1778           // out what to do about this.
1779           if (!VA.isRegLoc())
1780             return false;
1781           if (!ArgLocs[++i].isRegLoc())
1782             return false;
1783           if (RegVT == MVT::v2f64) {
1784             if (!ArgLocs[++i].isRegLoc())
1785               return false;
1786             if (!ArgLocs[++i].isRegLoc())
1787               return false;
1788           }
1789         } else if (!VA.isRegLoc()) {
1790           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1791                                    MFI, MRI, TII))
1792             return false;
1793         }
1794       }
1795     }
1796   }
1797 
1798   return true;
1799 }
1800 
1801 SDValue
1802 ARMTargetLowering::LowerReturn(SDValue Chain,
1803                                CallingConv::ID CallConv, bool isVarArg,
1804                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1805                                const SmallVectorImpl<SDValue> &OutVals,
1806                                DebugLoc dl, SelectionDAG &DAG) const {
1807 
1808   // CCValAssign - represent the assignment of the return value to a location.
1809   SmallVector<CCValAssign, 16> RVLocs;
1810 
1811   // CCState - Info about the registers and stack slots.
1812   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1813                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1814 
1815   // Analyze outgoing return values.
1816   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1817                                                isVarArg));
1818 
1819   // If this is the first return lowered for this function, add
1820   // the regs to the liveout set for the function.
1821   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1822     for (unsigned i = 0; i != RVLocs.size(); ++i)
1823       if (RVLocs[i].isRegLoc())
1824         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1825   }
1826 
1827   SDValue Flag;
1828 
1829   // Copy the result values into the output registers.
1830   for (unsigned i = 0, realRVLocIdx = 0;
1831        i != RVLocs.size();
1832        ++i, ++realRVLocIdx) {
1833     CCValAssign &VA = RVLocs[i];
1834     assert(VA.isRegLoc() && "Can only return in registers!");
1835 
1836     SDValue Arg = OutVals[realRVLocIdx];
1837 
1838     switch (VA.getLocInfo()) {
1839     default: llvm_unreachable("Unknown loc info!");
1840     case CCValAssign::Full: break;
1841     case CCValAssign::BCvt:
1842       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1843       break;
1844     }
1845 
1846     if (VA.needsCustom()) {
1847       if (VA.getLocVT() == MVT::v2f64) {
1848         // Extract the first half and return it in two registers.
1849         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1850                                    DAG.getConstant(0, MVT::i32));
1851         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
1852                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
1853 
1854         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1855         Flag = Chain.getValue(1);
1856         VA = RVLocs[++i]; // skip ahead to next loc
1857         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1858                                  HalfGPRs.getValue(1), Flag);
1859         Flag = Chain.getValue(1);
1860         VA = RVLocs[++i]; // skip ahead to next loc
1861 
1862         // Extract the 2nd half and fall through to handle it as an f64 value.
1863         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1864                           DAG.getConstant(1, MVT::i32));
1865       }
1866       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
1867       // available.
1868       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1869                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1870       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1871       Flag = Chain.getValue(1);
1872       VA = RVLocs[++i]; // skip ahead to next loc
1873       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1874                                Flag);
1875     } else
1876       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1877 
1878     // Guarantee that all emitted copies are
1879     // stuck together, avoiding something bad.
1880     Flag = Chain.getValue(1);
1881   }
1882 
1883   SDValue result;
1884   if (Flag.getNode())
1885     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
1886   else // Return Void
1887     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain);
1888 
1889   return result;
1890 }
1891 
1892 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N) const {
1893   if (N->getNumValues() != 1)
1894     return false;
1895   if (!N->hasNUsesOfValue(1, 0))
1896     return false;
1897 
1898   unsigned NumCopies = 0;
1899   SDNode* Copies[2];
1900   SDNode *Use = *N->use_begin();
1901   if (Use->getOpcode() == ISD::CopyToReg) {
1902     Copies[NumCopies++] = Use;
1903   } else if (Use->getOpcode() == ARMISD::VMOVRRD) {
1904     // f64 returned in a pair of GPRs.
1905     for (SDNode::use_iterator UI = Use->use_begin(), UE = Use->use_end();
1906          UI != UE; ++UI) {
1907       if (UI->getOpcode() != ISD::CopyToReg)
1908         return false;
1909       Copies[UI.getUse().getResNo()] = *UI;
1910       ++NumCopies;
1911     }
1912   } else if (Use->getOpcode() == ISD::BITCAST) {
1913     // f32 returned in a single GPR.
1914     if (!Use->hasNUsesOfValue(1, 0))
1915       return false;
1916     Use = *Use->use_begin();
1917     if (Use->getOpcode() != ISD::CopyToReg || !Use->hasNUsesOfValue(1, 0))
1918       return false;
1919     Copies[NumCopies++] = Use;
1920   } else {
1921     return false;
1922   }
1923 
1924   if (NumCopies != 1 && NumCopies != 2)
1925     return false;
1926 
1927   bool HasRet = false;
1928   for (unsigned i = 0; i < NumCopies; ++i) {
1929     SDNode *Copy = Copies[i];
1930     for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1931          UI != UE; ++UI) {
1932       if (UI->getOpcode() == ISD::CopyToReg) {
1933         SDNode *Use = *UI;
1934         if (Use == Copies[0] || Use == Copies[1])
1935           continue;
1936         return false;
1937       }
1938       if (UI->getOpcode() != ARMISD::RET_FLAG)
1939         return false;
1940       HasRet = true;
1941     }
1942   }
1943 
1944   return HasRet;
1945 }
1946 
1947 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1948   if (!EnableARMTailCalls)
1949     return false;
1950 
1951   if (!CI->isTailCall())
1952     return false;
1953 
1954   return !Subtarget->isThumb1Only();
1955 }
1956 
1957 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
1958 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
1959 // one of the above mentioned nodes. It has to be wrapped because otherwise
1960 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
1961 // be used to form addressing mode. These wrapped nodes will be selected
1962 // into MOVi.
1963 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
1964   EVT PtrVT = Op.getValueType();
1965   // FIXME there is no actual debug info here
1966   DebugLoc dl = Op.getDebugLoc();
1967   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1968   SDValue Res;
1969   if (CP->isMachineConstantPoolEntry())
1970     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
1971                                     CP->getAlignment());
1972   else
1973     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
1974                                     CP->getAlignment());
1975   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
1976 }
1977 
1978 unsigned ARMTargetLowering::getJumpTableEncoding() const {
1979   return MachineJumpTableInfo::EK_Inline;
1980 }
1981 
1982 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
1983                                              SelectionDAG &DAG) const {
1984   MachineFunction &MF = DAG.getMachineFunction();
1985   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1986   unsigned ARMPCLabelIndex = 0;
1987   DebugLoc DL = Op.getDebugLoc();
1988   EVT PtrVT = getPointerTy();
1989   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1990   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
1991   SDValue CPAddr;
1992   if (RelocM == Reloc::Static) {
1993     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
1994   } else {
1995     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
1996     ARMPCLabelIndex = AFI->createPICLabelUId();
1997     ARMConstantPoolValue *CPV =
1998       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
1999                                       ARMCP::CPBlockAddress, PCAdj);
2000     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2001   }
2002   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2003   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2004                                MachinePointerInfo::getConstantPool(),
2005                                false, false, false, 0);
2006   if (RelocM == Reloc::Static)
2007     return Result;
2008   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2009   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2010 }
2011 
2012 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2013 SDValue
2014 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2015                                                  SelectionDAG &DAG) const {
2016   DebugLoc dl = GA->getDebugLoc();
2017   EVT PtrVT = getPointerTy();
2018   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2019   MachineFunction &MF = DAG.getMachineFunction();
2020   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2021   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2022   ARMConstantPoolValue *CPV =
2023     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2024                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2025   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2026   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2027   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2028                          MachinePointerInfo::getConstantPool(),
2029                          false, false, false, 0);
2030   SDValue Chain = Argument.getValue(1);
2031 
2032   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2033   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2034 
2035   // call __tls_get_addr.
2036   ArgListTy Args;
2037   ArgListEntry Entry;
2038   Entry.Node = Argument;
2039   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2040   Args.push_back(Entry);
2041   // FIXME: is there useful debug info available here?
2042   std::pair<SDValue, SDValue> CallResult =
2043     LowerCallTo(Chain, (Type *) Type::getInt32Ty(*DAG.getContext()),
2044                 false, false, false, false,
2045                 0, CallingConv::C, false, /*isReturnValueUsed=*/true,
2046                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2047   return CallResult.first;
2048 }
2049 
2050 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2051 // "local exec" model.
2052 SDValue
2053 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2054                                         SelectionDAG &DAG) const {
2055   const GlobalValue *GV = GA->getGlobal();
2056   DebugLoc dl = GA->getDebugLoc();
2057   SDValue Offset;
2058   SDValue Chain = DAG.getEntryNode();
2059   EVT PtrVT = getPointerTy();
2060   // Get the Thread Pointer
2061   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2062 
2063   if (GV->isDeclaration()) {
2064     MachineFunction &MF = DAG.getMachineFunction();
2065     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2066     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2067     // Initial exec model.
2068     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2069     ARMConstantPoolValue *CPV =
2070       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2071                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2072                                       true);
2073     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2074     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2075     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2076                          MachinePointerInfo::getConstantPool(),
2077                          false, false, false, 0);
2078     Chain = Offset.getValue(1);
2079 
2080     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2081     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2082 
2083     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2084                          MachinePointerInfo::getConstantPool(),
2085                          false, false, false, 0);
2086   } else {
2087     // local exec model
2088     ARMConstantPoolValue *CPV =
2089       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2090     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2091     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2092     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2093                          MachinePointerInfo::getConstantPool(),
2094                          false, false, false, 0);
2095   }
2096 
2097   // The address of the thread local variable is the add of the thread
2098   // pointer with the offset of the variable.
2099   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2100 }
2101 
2102 SDValue
2103 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2104   // TODO: implement the "local dynamic" model
2105   assert(Subtarget->isTargetELF() &&
2106          "TLS not implemented for non-ELF targets");
2107   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2108   // If the relocation model is PIC, use the "General Dynamic" TLS Model,
2109   // otherwise use the "Local Exec" TLS Model
2110   if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
2111     return LowerToTLSGeneralDynamicModel(GA, DAG);
2112   else
2113     return LowerToTLSExecModels(GA, DAG);
2114 }
2115 
2116 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2117                                                  SelectionDAG &DAG) const {
2118   EVT PtrVT = getPointerTy();
2119   DebugLoc dl = Op.getDebugLoc();
2120   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2121   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2122   if (RelocM == Reloc::PIC_) {
2123     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2124     ARMConstantPoolValue *CPV =
2125       ARMConstantPoolConstant::Create(GV,
2126                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2127     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2128     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2129     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2130                                  CPAddr,
2131                                  MachinePointerInfo::getConstantPool(),
2132                                  false, false, false, 0);
2133     SDValue Chain = Result.getValue(1);
2134     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2135     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2136     if (!UseGOTOFF)
2137       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2138                            MachinePointerInfo::getGOT(),
2139                            false, false, false, 0);
2140     return Result;
2141   }
2142 
2143   // If we have T2 ops, we can materialize the address directly via movt/movw
2144   // pair. This is always cheaper.
2145   if (Subtarget->useMovt()) {
2146     ++NumMovwMovt;
2147     // FIXME: Once remat is capable of dealing with instructions with register
2148     // operands, expand this into two nodes.
2149     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2150                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2151   } else {
2152     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2153     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2154     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2155                        MachinePointerInfo::getConstantPool(),
2156                        false, false, false, 0);
2157   }
2158 }
2159 
2160 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2161                                                     SelectionDAG &DAG) const {
2162   EVT PtrVT = getPointerTy();
2163   DebugLoc dl = Op.getDebugLoc();
2164   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2165   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2166   MachineFunction &MF = DAG.getMachineFunction();
2167   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2168 
2169   // FIXME: Enable this for static codegen when tool issues are fixed.  Also
2170   // update ARMFastISel::ARMMaterializeGV.
2171   if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2172     ++NumMovwMovt;
2173     // FIXME: Once remat is capable of dealing with instructions with register
2174     // operands, expand this into two nodes.
2175     if (RelocM == Reloc::Static)
2176       return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2177                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2178 
2179     unsigned Wrapper = (RelocM == Reloc::PIC_)
2180       ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2181     SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2182                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2183     if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2184       Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2185                            MachinePointerInfo::getGOT(),
2186                            false, false, false, 0);
2187     return Result;
2188   }
2189 
2190   unsigned ARMPCLabelIndex = 0;
2191   SDValue CPAddr;
2192   if (RelocM == Reloc::Static) {
2193     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2194   } else {
2195     ARMPCLabelIndex = AFI->createPICLabelUId();
2196     unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2197     ARMConstantPoolValue *CPV =
2198       ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2199                                       PCAdj);
2200     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2201   }
2202   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2203 
2204   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2205                                MachinePointerInfo::getConstantPool(),
2206                                false, false, false, 0);
2207   SDValue Chain = Result.getValue(1);
2208 
2209   if (RelocM == Reloc::PIC_) {
2210     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2211     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2212   }
2213 
2214   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2215     Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2216                          false, false, false, 0);
2217 
2218   return Result;
2219 }
2220 
2221 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2222                                                     SelectionDAG &DAG) const {
2223   assert(Subtarget->isTargetELF() &&
2224          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2225   MachineFunction &MF = DAG.getMachineFunction();
2226   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2227   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2228   EVT PtrVT = getPointerTy();
2229   DebugLoc dl = Op.getDebugLoc();
2230   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2231   ARMConstantPoolValue *CPV =
2232     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2233                                   ARMPCLabelIndex, PCAdj);
2234   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2235   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2236   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2237                                MachinePointerInfo::getConstantPool(),
2238                                false, false, false, 0);
2239   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2240   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2241 }
2242 
2243 SDValue
2244 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2245   DebugLoc dl = Op.getDebugLoc();
2246   SDValue Val = DAG.getConstant(0, MVT::i32);
2247   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2248                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2249                      Op.getOperand(1), Val);
2250 }
2251 
2252 SDValue
2253 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2254   DebugLoc dl = Op.getDebugLoc();
2255   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2256                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2257 }
2258 
2259 SDValue
2260 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2261                                           const ARMSubtarget *Subtarget) const {
2262   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2263   DebugLoc dl = Op.getDebugLoc();
2264   switch (IntNo) {
2265   default: return SDValue();    // Don't custom lower most intrinsics.
2266   case Intrinsic::arm_thread_pointer: {
2267     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2268     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2269   }
2270   case Intrinsic::eh_sjlj_lsda: {
2271     MachineFunction &MF = DAG.getMachineFunction();
2272     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2273     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2274     EVT PtrVT = getPointerTy();
2275     DebugLoc dl = Op.getDebugLoc();
2276     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2277     SDValue CPAddr;
2278     unsigned PCAdj = (RelocM != Reloc::PIC_)
2279       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2280     ARMConstantPoolValue *CPV =
2281       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2282                                       ARMCP::CPLSDA, PCAdj);
2283     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2284     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2285     SDValue Result =
2286       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2287                   MachinePointerInfo::getConstantPool(),
2288                   false, false, false, 0);
2289 
2290     if (RelocM == Reloc::PIC_) {
2291       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2292       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2293     }
2294     return Result;
2295   }
2296   case Intrinsic::arm_neon_vmulls:
2297   case Intrinsic::arm_neon_vmullu: {
2298     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2299       ? ARMISD::VMULLs : ARMISD::VMULLu;
2300     return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2301                        Op.getOperand(1), Op.getOperand(2));
2302   }
2303   }
2304 }
2305 
2306 static SDValue LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG,
2307                                const ARMSubtarget *Subtarget) {
2308   DebugLoc dl = Op.getDebugLoc();
2309   if (!Subtarget->hasDataBarrier()) {
2310     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2311     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2312     // here.
2313     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2314            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2315     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2316                        DAG.getConstant(0, MVT::i32));
2317   }
2318 
2319   SDValue Op5 = Op.getOperand(5);
2320   bool isDeviceBarrier = cast<ConstantSDNode>(Op5)->getZExtValue() != 0;
2321   unsigned isLL = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2322   unsigned isLS = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2323   bool isOnlyStoreBarrier = (isLL == 0 && isLS == 0);
2324 
2325   ARM_MB::MemBOpt DMBOpt;
2326   if (isDeviceBarrier)
2327     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ST : ARM_MB::SY;
2328   else
2329     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ISHST : ARM_MB::ISH;
2330   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2331                      DAG.getConstant(DMBOpt, MVT::i32));
2332 }
2333 
2334 
2335 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2336                                  const ARMSubtarget *Subtarget) {
2337   // FIXME: handle "fence singlethread" more efficiently.
2338   DebugLoc dl = Op.getDebugLoc();
2339   if (!Subtarget->hasDataBarrier()) {
2340     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2341     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2342     // here.
2343     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2344            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2345     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2346                        DAG.getConstant(0, MVT::i32));
2347   }
2348 
2349   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2350                      DAG.getConstant(ARM_MB::ISH, MVT::i32));
2351 }
2352 
2353 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2354                              const ARMSubtarget *Subtarget) {
2355   // ARM pre v5TE and Thumb1 does not have preload instructions.
2356   if (!(Subtarget->isThumb2() ||
2357         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2358     // Just preserve the chain.
2359     return Op.getOperand(0);
2360 
2361   DebugLoc dl = Op.getDebugLoc();
2362   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2363   if (!isRead &&
2364       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2365     // ARMv7 with MP extension has PLDW.
2366     return Op.getOperand(0);
2367 
2368   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2369   if (Subtarget->isThumb()) {
2370     // Invert the bits.
2371     isRead = ~isRead & 1;
2372     isData = ~isData & 1;
2373   }
2374 
2375   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2376                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2377                      DAG.getConstant(isData, MVT::i32));
2378 }
2379 
2380 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2381   MachineFunction &MF = DAG.getMachineFunction();
2382   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2383 
2384   // vastart just stores the address of the VarArgsFrameIndex slot into the
2385   // memory location argument.
2386   DebugLoc dl = Op.getDebugLoc();
2387   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2388   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2389   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2390   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2391                       MachinePointerInfo(SV), false, false, 0);
2392 }
2393 
2394 SDValue
2395 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2396                                         SDValue &Root, SelectionDAG &DAG,
2397                                         DebugLoc dl) const {
2398   MachineFunction &MF = DAG.getMachineFunction();
2399   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2400 
2401   TargetRegisterClass *RC;
2402   if (AFI->isThumb1OnlyFunction())
2403     RC = ARM::tGPRRegisterClass;
2404   else
2405     RC = ARM::GPRRegisterClass;
2406 
2407   // Transform the arguments stored in physical registers into virtual ones.
2408   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2409   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2410 
2411   SDValue ArgValue2;
2412   if (NextVA.isMemLoc()) {
2413     MachineFrameInfo *MFI = MF.getFrameInfo();
2414     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2415 
2416     // Create load node to retrieve arguments from the stack.
2417     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2418     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2419                             MachinePointerInfo::getFixedStack(FI),
2420                             false, false, false, 0);
2421   } else {
2422     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2423     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2424   }
2425 
2426   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2427 }
2428 
2429 void
2430 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2431                                   unsigned &VARegSize, unsigned &VARegSaveSize)
2432   const {
2433   unsigned NumGPRs;
2434   if (CCInfo.isFirstByValRegValid())
2435     NumGPRs = ARM::R4 - CCInfo.getFirstByValReg();
2436   else {
2437     unsigned int firstUnalloced;
2438     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2439                                                 sizeof(GPRArgRegs) /
2440                                                 sizeof(GPRArgRegs[0]));
2441     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2442   }
2443 
2444   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2445   VARegSize = NumGPRs * 4;
2446   VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
2447 }
2448 
2449 // The remaining GPRs hold either the beginning of variable-argument
2450 // data, or the beginning of an aggregate passed by value (usuall
2451 // byval).  Either way, we allocate stack slots adjacent to the data
2452 // provided by our caller, and store the unallocated registers there.
2453 // If this is a variadic function, the va_list pointer will begin with
2454 // these values; otherwise, this reassembles a (byval) structure that
2455 // was split between registers and memory.
2456 void
2457 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2458                                         DebugLoc dl, SDValue &Chain,
2459                                         unsigned ArgOffset) const {
2460   MachineFunction &MF = DAG.getMachineFunction();
2461   MachineFrameInfo *MFI = MF.getFrameInfo();
2462   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2463   unsigned firstRegToSaveIndex;
2464   if (CCInfo.isFirstByValRegValid())
2465     firstRegToSaveIndex = CCInfo.getFirstByValReg() - ARM::R0;
2466   else {
2467     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2468       (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2469   }
2470 
2471   unsigned VARegSize, VARegSaveSize;
2472   computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2473   if (VARegSaveSize) {
2474     // If this function is vararg, store any remaining integer argument regs
2475     // to their spots on the stack so that they may be loaded by deferencing
2476     // the result of va_next.
2477     AFI->setVarArgsRegSaveSize(VARegSaveSize);
2478     AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(VARegSaveSize,
2479                                                      ArgOffset + VARegSaveSize
2480                                                      - VARegSize,
2481                                                      false));
2482     SDValue FIN = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(),
2483                                     getPointerTy());
2484 
2485     SmallVector<SDValue, 4> MemOps;
2486     for (; firstRegToSaveIndex < 4; ++firstRegToSaveIndex) {
2487       TargetRegisterClass *RC;
2488       if (AFI->isThumb1OnlyFunction())
2489         RC = ARM::tGPRRegisterClass;
2490       else
2491         RC = ARM::GPRRegisterClass;
2492 
2493       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2494       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2495       SDValue Store =
2496         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2497                  MachinePointerInfo::getFixedStack(AFI->getVarArgsFrameIndex()),
2498                      false, false, 0);
2499       MemOps.push_back(Store);
2500       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2501                         DAG.getConstant(4, getPointerTy()));
2502     }
2503     if (!MemOps.empty())
2504       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2505                           &MemOps[0], MemOps.size());
2506   } else
2507     // This will point to the next argument passed via stack.
2508     AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(4, ArgOffset, true));
2509 }
2510 
2511 SDValue
2512 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2513                                         CallingConv::ID CallConv, bool isVarArg,
2514                                         const SmallVectorImpl<ISD::InputArg>
2515                                           &Ins,
2516                                         DebugLoc dl, SelectionDAG &DAG,
2517                                         SmallVectorImpl<SDValue> &InVals)
2518                                           const {
2519   MachineFunction &MF = DAG.getMachineFunction();
2520   MachineFrameInfo *MFI = MF.getFrameInfo();
2521 
2522   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2523 
2524   // Assign locations to all of the incoming arguments.
2525   SmallVector<CCValAssign, 16> ArgLocs;
2526   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2527                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2528   CCInfo.AnalyzeFormalArguments(Ins,
2529                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2530                                                   isVarArg));
2531 
2532   SmallVector<SDValue, 16> ArgValues;
2533   int lastInsIndex = -1;
2534 
2535   SDValue ArgValue;
2536   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2537     CCValAssign &VA = ArgLocs[i];
2538 
2539     // Arguments stored in registers.
2540     if (VA.isRegLoc()) {
2541       EVT RegVT = VA.getLocVT();
2542 
2543       if (VA.needsCustom()) {
2544         // f64 and vector types are split up into multiple registers or
2545         // combinations of registers and stack slots.
2546         if (VA.getLocVT() == MVT::v2f64) {
2547           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2548                                                    Chain, DAG, dl);
2549           VA = ArgLocs[++i]; // skip ahead to next loc
2550           SDValue ArgValue2;
2551           if (VA.isMemLoc()) {
2552             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2553             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2554             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2555                                     MachinePointerInfo::getFixedStack(FI),
2556                                     false, false, false, 0);
2557           } else {
2558             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2559                                              Chain, DAG, dl);
2560           }
2561           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2562           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2563                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2564           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2565                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2566         } else
2567           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2568 
2569       } else {
2570         TargetRegisterClass *RC;
2571 
2572         if (RegVT == MVT::f32)
2573           RC = ARM::SPRRegisterClass;
2574         else if (RegVT == MVT::f64)
2575           RC = ARM::DPRRegisterClass;
2576         else if (RegVT == MVT::v2f64)
2577           RC = ARM::QPRRegisterClass;
2578         else if (RegVT == MVT::i32)
2579           RC = (AFI->isThumb1OnlyFunction() ?
2580                 ARM::tGPRRegisterClass : ARM::GPRRegisterClass);
2581         else
2582           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2583 
2584         // Transform the arguments in physical registers into virtual ones.
2585         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2586         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2587       }
2588 
2589       // If this is an 8 or 16-bit value, it is really passed promoted
2590       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2591       // truncate to the right size.
2592       switch (VA.getLocInfo()) {
2593       default: llvm_unreachable("Unknown loc info!");
2594       case CCValAssign::Full: break;
2595       case CCValAssign::BCvt:
2596         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2597         break;
2598       case CCValAssign::SExt:
2599         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2600                                DAG.getValueType(VA.getValVT()));
2601         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2602         break;
2603       case CCValAssign::ZExt:
2604         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2605                                DAG.getValueType(VA.getValVT()));
2606         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2607         break;
2608       }
2609 
2610       InVals.push_back(ArgValue);
2611 
2612     } else { // VA.isRegLoc()
2613 
2614       // sanity check
2615       assert(VA.isMemLoc());
2616       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2617 
2618       int index = ArgLocs[i].getValNo();
2619 
2620       // Some Ins[] entries become multiple ArgLoc[] entries.
2621       // Process them only once.
2622       if (index != lastInsIndex)
2623         {
2624           ISD::ArgFlagsTy Flags = Ins[index].Flags;
2625           // FIXME: For now, all byval parameter objects are marked mutable.
2626           // This can be changed with more analysis.
2627           // In case of tail call optimization mark all arguments mutable.
2628           // Since they could be overwritten by lowering of arguments in case of
2629           // a tail call.
2630           if (Flags.isByVal()) {
2631             unsigned VARegSize, VARegSaveSize;
2632             computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2633             VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 0);
2634             unsigned Bytes = Flags.getByValSize() - VARegSize;
2635             if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2636             int FI = MFI->CreateFixedObject(Bytes,
2637                                             VA.getLocMemOffset(), false);
2638             InVals.push_back(DAG.getFrameIndex(FI, getPointerTy()));
2639           } else {
2640             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2641                                             VA.getLocMemOffset(), true);
2642 
2643             // Create load nodes to retrieve arguments from the stack.
2644             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2645             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2646                                          MachinePointerInfo::getFixedStack(FI),
2647                                          false, false, false, 0));
2648           }
2649           lastInsIndex = index;
2650         }
2651     }
2652   }
2653 
2654   // varargs
2655   if (isVarArg)
2656     VarArgStyleRegisters(CCInfo, DAG, dl, Chain, CCInfo.getNextStackOffset());
2657 
2658   return Chain;
2659 }
2660 
2661 /// isFloatingPointZero - Return true if this is +0.0.
2662 static bool isFloatingPointZero(SDValue Op) {
2663   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2664     return CFP->getValueAPF().isPosZero();
2665   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2666     // Maybe this has already been legalized into the constant pool?
2667     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2668       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2669       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2670         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2671           return CFP->getValueAPF().isPosZero();
2672     }
2673   }
2674   return false;
2675 }
2676 
2677 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2678 /// the given operands.
2679 SDValue
2680 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2681                              SDValue &ARMcc, SelectionDAG &DAG,
2682                              DebugLoc dl) const {
2683   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2684     unsigned C = RHSC->getZExtValue();
2685     if (!isLegalICmpImmediate(C)) {
2686       // Constant does not fit, try adjusting it by one?
2687       switch (CC) {
2688       default: break;
2689       case ISD::SETLT:
2690       case ISD::SETGE:
2691         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2692           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2693           RHS = DAG.getConstant(C-1, MVT::i32);
2694         }
2695         break;
2696       case ISD::SETULT:
2697       case ISD::SETUGE:
2698         if (C != 0 && isLegalICmpImmediate(C-1)) {
2699           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2700           RHS = DAG.getConstant(C-1, MVT::i32);
2701         }
2702         break;
2703       case ISD::SETLE:
2704       case ISD::SETGT:
2705         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
2706           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2707           RHS = DAG.getConstant(C+1, MVT::i32);
2708         }
2709         break;
2710       case ISD::SETULE:
2711       case ISD::SETUGT:
2712         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
2713           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2714           RHS = DAG.getConstant(C+1, MVT::i32);
2715         }
2716         break;
2717       }
2718     }
2719   }
2720 
2721   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2722   ARMISD::NodeType CompareType;
2723   switch (CondCode) {
2724   default:
2725     CompareType = ARMISD::CMP;
2726     break;
2727   case ARMCC::EQ:
2728   case ARMCC::NE:
2729     // Uses only Z Flag
2730     CompareType = ARMISD::CMPZ;
2731     break;
2732   }
2733   ARMcc = DAG.getConstant(CondCode, MVT::i32);
2734   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
2735 }
2736 
2737 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
2738 SDValue
2739 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
2740                              DebugLoc dl) const {
2741   SDValue Cmp;
2742   if (!isFloatingPointZero(RHS))
2743     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
2744   else
2745     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
2746   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
2747 }
2748 
2749 /// duplicateCmp - Glue values can have only one use, so this function
2750 /// duplicates a comparison node.
2751 SDValue
2752 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
2753   unsigned Opc = Cmp.getOpcode();
2754   DebugLoc DL = Cmp.getDebugLoc();
2755   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
2756     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2757 
2758   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
2759   Cmp = Cmp.getOperand(0);
2760   Opc = Cmp.getOpcode();
2761   if (Opc == ARMISD::CMPFP)
2762     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2763   else {
2764     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
2765     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
2766   }
2767   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
2768 }
2769 
2770 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2771   SDValue Cond = Op.getOperand(0);
2772   SDValue SelectTrue = Op.getOperand(1);
2773   SDValue SelectFalse = Op.getOperand(2);
2774   DebugLoc dl = Op.getDebugLoc();
2775 
2776   // Convert:
2777   //
2778   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
2779   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
2780   //
2781   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
2782     const ConstantSDNode *CMOVTrue =
2783       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
2784     const ConstantSDNode *CMOVFalse =
2785       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2786 
2787     if (CMOVTrue && CMOVFalse) {
2788       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
2789       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
2790 
2791       SDValue True;
2792       SDValue False;
2793       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
2794         True = SelectTrue;
2795         False = SelectFalse;
2796       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
2797         True = SelectFalse;
2798         False = SelectTrue;
2799       }
2800 
2801       if (True.getNode() && False.getNode()) {
2802         EVT VT = Op.getValueType();
2803         SDValue ARMcc = Cond.getOperand(2);
2804         SDValue CCR = Cond.getOperand(3);
2805         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
2806         assert(True.getValueType() == VT);
2807         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
2808       }
2809     }
2810   }
2811 
2812   return DAG.getSelectCC(dl, Cond,
2813                          DAG.getConstant(0, Cond.getValueType()),
2814                          SelectTrue, SelectFalse, ISD::SETNE);
2815 }
2816 
2817 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2818   EVT VT = Op.getValueType();
2819   SDValue LHS = Op.getOperand(0);
2820   SDValue RHS = Op.getOperand(1);
2821   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2822   SDValue TrueVal = Op.getOperand(2);
2823   SDValue FalseVal = Op.getOperand(3);
2824   DebugLoc dl = Op.getDebugLoc();
2825 
2826   if (LHS.getValueType() == MVT::i32) {
2827     SDValue ARMcc;
2828     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2829     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2830     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
2831   }
2832 
2833   ARMCC::CondCodes CondCode, CondCode2;
2834   FPCCToARMCC(CC, CondCode, CondCode2);
2835 
2836   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
2837   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
2838   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2839   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
2840                                ARMcc, CCR, Cmp);
2841   if (CondCode2 != ARMCC::AL) {
2842     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
2843     // FIXME: Needs another CMP because flag can have but one use.
2844     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
2845     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
2846                          Result, TrueVal, ARMcc2, CCR, Cmp2);
2847   }
2848   return Result;
2849 }
2850 
2851 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
2852 /// to morph to an integer compare sequence.
2853 static bool canChangeToInt(SDValue Op, bool &SeenZero,
2854                            const ARMSubtarget *Subtarget) {
2855   SDNode *N = Op.getNode();
2856   if (!N->hasOneUse())
2857     // Otherwise it requires moving the value from fp to integer registers.
2858     return false;
2859   if (!N->getNumValues())
2860     return false;
2861   EVT VT = Op.getValueType();
2862   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
2863     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
2864     // vmrs are very slow, e.g. cortex-a8.
2865     return false;
2866 
2867   if (isFloatingPointZero(Op)) {
2868     SeenZero = true;
2869     return true;
2870   }
2871   return ISD::isNormalLoad(N);
2872 }
2873 
2874 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
2875   if (isFloatingPointZero(Op))
2876     return DAG.getConstant(0, MVT::i32);
2877 
2878   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
2879     return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2880                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
2881                        Ld->isVolatile(), Ld->isNonTemporal(),
2882                        Ld->isInvariant(), Ld->getAlignment());
2883 
2884   llvm_unreachable("Unknown VFP cmp argument!");
2885 }
2886 
2887 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
2888                            SDValue &RetVal1, SDValue &RetVal2) {
2889   if (isFloatingPointZero(Op)) {
2890     RetVal1 = DAG.getConstant(0, MVT::i32);
2891     RetVal2 = DAG.getConstant(0, MVT::i32);
2892     return;
2893   }
2894 
2895   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
2896     SDValue Ptr = Ld->getBasePtr();
2897     RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2898                           Ld->getChain(), Ptr,
2899                           Ld->getPointerInfo(),
2900                           Ld->isVolatile(), Ld->isNonTemporal(),
2901                           Ld->isInvariant(), Ld->getAlignment());
2902 
2903     EVT PtrType = Ptr.getValueType();
2904     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
2905     SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
2906                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
2907     RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2908                           Ld->getChain(), NewPtr,
2909                           Ld->getPointerInfo().getWithOffset(4),
2910                           Ld->isVolatile(), Ld->isNonTemporal(),
2911                           Ld->isInvariant(), NewAlign);
2912     return;
2913   }
2914 
2915   llvm_unreachable("Unknown VFP cmp argument!");
2916 }
2917 
2918 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
2919 /// f32 and even f64 comparisons to integer ones.
2920 SDValue
2921 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
2922   SDValue Chain = Op.getOperand(0);
2923   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2924   SDValue LHS = Op.getOperand(2);
2925   SDValue RHS = Op.getOperand(3);
2926   SDValue Dest = Op.getOperand(4);
2927   DebugLoc dl = Op.getDebugLoc();
2928 
2929   bool SeenZero = false;
2930   if (canChangeToInt(LHS, SeenZero, Subtarget) &&
2931       canChangeToInt(RHS, SeenZero, Subtarget) &&
2932       // If one of the operand is zero, it's safe to ignore the NaN case since
2933       // we only care about equality comparisons.
2934       (SeenZero || (DAG.isKnownNeverNaN(LHS) && DAG.isKnownNeverNaN(RHS)))) {
2935     // If unsafe fp math optimization is enabled and there are no other uses of
2936     // the CMP operands, and the condition code is EQ or NE, we can optimize it
2937     // to an integer comparison.
2938     if (CC == ISD::SETOEQ)
2939       CC = ISD::SETEQ;
2940     else if (CC == ISD::SETUNE)
2941       CC = ISD::SETNE;
2942 
2943     SDValue ARMcc;
2944     if (LHS.getValueType() == MVT::f32) {
2945       LHS = bitcastf32Toi32(LHS, DAG);
2946       RHS = bitcastf32Toi32(RHS, DAG);
2947       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2948       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2949       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
2950                          Chain, Dest, ARMcc, CCR, Cmp);
2951     }
2952 
2953     SDValue LHS1, LHS2;
2954     SDValue RHS1, RHS2;
2955     expandf64Toi32(LHS, DAG, LHS1, LHS2);
2956     expandf64Toi32(RHS, DAG, RHS1, RHS2);
2957     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2958     ARMcc = DAG.getConstant(CondCode, MVT::i32);
2959     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
2960     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
2961     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
2962   }
2963 
2964   return SDValue();
2965 }
2966 
2967 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
2968   SDValue Chain = Op.getOperand(0);
2969   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2970   SDValue LHS = Op.getOperand(2);
2971   SDValue RHS = Op.getOperand(3);
2972   SDValue Dest = Op.getOperand(4);
2973   DebugLoc dl = Op.getDebugLoc();
2974 
2975   if (LHS.getValueType() == MVT::i32) {
2976     SDValue ARMcc;
2977     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2978     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2979     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
2980                        Chain, Dest, ARMcc, CCR, Cmp);
2981   }
2982 
2983   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
2984 
2985   if (getTargetMachine().Options.UnsafeFPMath &&
2986       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
2987        CC == ISD::SETNE || CC == ISD::SETUNE)) {
2988     SDValue Result = OptimizeVFPBrcond(Op, DAG);
2989     if (Result.getNode())
2990       return Result;
2991   }
2992 
2993   ARMCC::CondCodes CondCode, CondCode2;
2994   FPCCToARMCC(CC, CondCode, CondCode2);
2995 
2996   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
2997   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
2998   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2999   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3000   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3001   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3002   if (CondCode2 != ARMCC::AL) {
3003     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3004     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3005     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3006   }
3007   return Res;
3008 }
3009 
3010 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3011   SDValue Chain = Op.getOperand(0);
3012   SDValue Table = Op.getOperand(1);
3013   SDValue Index = Op.getOperand(2);
3014   DebugLoc dl = Op.getDebugLoc();
3015 
3016   EVT PTy = getPointerTy();
3017   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3018   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3019   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3020   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3021   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3022   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3023   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3024   if (Subtarget->isThumb2()) {
3025     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3026     // which does another jump to the destination. This also makes it easier
3027     // to translate it to TBB / TBH later.
3028     // FIXME: This might not work if the function is extremely large.
3029     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3030                        Addr, Op.getOperand(2), JTI, UId);
3031   }
3032   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3033     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3034                        MachinePointerInfo::getJumpTable(),
3035                        false, false, false, 0);
3036     Chain = Addr.getValue(1);
3037     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3038     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3039   } else {
3040     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3041                        MachinePointerInfo::getJumpTable(),
3042                        false, false, false, 0);
3043     Chain = Addr.getValue(1);
3044     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3045   }
3046 }
3047 
3048 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3049   assert(Op.getValueType().getVectorElementType() == MVT::i32
3050          && "Unexpected custom lowering");
3051 
3052   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3053     return Op;
3054   return DAG.UnrollVectorOp(Op.getNode());
3055 }
3056 
3057 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3058   EVT VT = Op.getValueType();
3059   if (VT.isVector())
3060     return LowerVectorFP_TO_INT(Op, DAG);
3061 
3062   DebugLoc dl = Op.getDebugLoc();
3063   unsigned Opc;
3064 
3065   switch (Op.getOpcode()) {
3066   default:
3067     assert(0 && "Invalid opcode!");
3068   case ISD::FP_TO_SINT:
3069     Opc = ARMISD::FTOSI;
3070     break;
3071   case ISD::FP_TO_UINT:
3072     Opc = ARMISD::FTOUI;
3073     break;
3074   }
3075   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3076   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3077 }
3078 
3079 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3080   EVT VT = Op.getValueType();
3081   DebugLoc dl = Op.getDebugLoc();
3082 
3083   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3084     if (VT.getVectorElementType() == MVT::f32)
3085       return Op;
3086     return DAG.UnrollVectorOp(Op.getNode());
3087   }
3088 
3089   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3090          "Invalid type for custom lowering!");
3091   if (VT != MVT::v4f32)
3092     return DAG.UnrollVectorOp(Op.getNode());
3093 
3094   unsigned CastOpc;
3095   unsigned Opc;
3096   switch (Op.getOpcode()) {
3097   default:
3098     assert(0 && "Invalid opcode!");
3099   case ISD::SINT_TO_FP:
3100     CastOpc = ISD::SIGN_EXTEND;
3101     Opc = ISD::SINT_TO_FP;
3102     break;
3103   case ISD::UINT_TO_FP:
3104     CastOpc = ISD::ZERO_EXTEND;
3105     Opc = ISD::UINT_TO_FP;
3106     break;
3107   }
3108 
3109   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3110   return DAG.getNode(Opc, dl, VT, Op);
3111 }
3112 
3113 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3114   EVT VT = Op.getValueType();
3115   if (VT.isVector())
3116     return LowerVectorINT_TO_FP(Op, DAG);
3117 
3118   DebugLoc dl = Op.getDebugLoc();
3119   unsigned Opc;
3120 
3121   switch (Op.getOpcode()) {
3122   default:
3123     assert(0 && "Invalid opcode!");
3124   case ISD::SINT_TO_FP:
3125     Opc = ARMISD::SITOF;
3126     break;
3127   case ISD::UINT_TO_FP:
3128     Opc = ARMISD::UITOF;
3129     break;
3130   }
3131 
3132   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3133   return DAG.getNode(Opc, dl, VT, Op);
3134 }
3135 
3136 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3137   // Implement fcopysign with a fabs and a conditional fneg.
3138   SDValue Tmp0 = Op.getOperand(0);
3139   SDValue Tmp1 = Op.getOperand(1);
3140   DebugLoc dl = Op.getDebugLoc();
3141   EVT VT = Op.getValueType();
3142   EVT SrcVT = Tmp1.getValueType();
3143   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3144     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3145   bool UseNEON = !InGPR && Subtarget->hasNEON();
3146 
3147   if (UseNEON) {
3148     // Use VBSL to copy the sign bit.
3149     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3150     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3151                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3152     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3153     if (VT == MVT::f64)
3154       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3155                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3156                          DAG.getConstant(32, MVT::i32));
3157     else /*if (VT == MVT::f32)*/
3158       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3159     if (SrcVT == MVT::f32) {
3160       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3161       if (VT == MVT::f64)
3162         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3163                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3164                            DAG.getConstant(32, MVT::i32));
3165     } else if (VT == MVT::f32)
3166       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3167                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3168                          DAG.getConstant(32, MVT::i32));
3169     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3170     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3171 
3172     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3173                                             MVT::i32);
3174     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3175     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3176                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3177 
3178     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3179                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3180                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3181     if (VT == MVT::f32) {
3182       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3183       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3184                         DAG.getConstant(0, MVT::i32));
3185     } else {
3186       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3187     }
3188 
3189     return Res;
3190   }
3191 
3192   // Bitcast operand 1 to i32.
3193   if (SrcVT == MVT::f64)
3194     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3195                        &Tmp1, 1).getValue(1);
3196   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3197 
3198   // Or in the signbit with integer operations.
3199   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3200   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3201   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3202   if (VT == MVT::f32) {
3203     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3204                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3205     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3206                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3207   }
3208 
3209   // f64: Or the high part with signbit and then combine two parts.
3210   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3211                      &Tmp0, 1);
3212   SDValue Lo = Tmp0.getValue(0);
3213   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3214   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3215   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3216 }
3217 
3218 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3219   MachineFunction &MF = DAG.getMachineFunction();
3220   MachineFrameInfo *MFI = MF.getFrameInfo();
3221   MFI->setReturnAddressIsTaken(true);
3222 
3223   EVT VT = Op.getValueType();
3224   DebugLoc dl = Op.getDebugLoc();
3225   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3226   if (Depth) {
3227     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3228     SDValue Offset = DAG.getConstant(4, MVT::i32);
3229     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3230                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3231                        MachinePointerInfo(), false, false, false, 0);
3232   }
3233 
3234   // Return LR, which contains the return address. Mark it an implicit live-in.
3235   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3236   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3237 }
3238 
3239 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3240   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3241   MFI->setFrameAddressIsTaken(true);
3242 
3243   EVT VT = Op.getValueType();
3244   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
3245   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3246   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3247     ? ARM::R7 : ARM::R11;
3248   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3249   while (Depth--)
3250     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3251                             MachinePointerInfo(),
3252                             false, false, false, 0);
3253   return FrameAddr;
3254 }
3255 
3256 /// ExpandBITCAST - If the target supports VFP, this function is called to
3257 /// expand a bit convert where either the source or destination type is i64 to
3258 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3259 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3260 /// vectors), since the legalizer won't know what to do with that.
3261 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3262   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3263   DebugLoc dl = N->getDebugLoc();
3264   SDValue Op = N->getOperand(0);
3265 
3266   // This function is only supposed to be called for i64 types, either as the
3267   // source or destination of the bit convert.
3268   EVT SrcVT = Op.getValueType();
3269   EVT DstVT = N->getValueType(0);
3270   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3271          "ExpandBITCAST called for non-i64 type");
3272 
3273   // Turn i64->f64 into VMOVDRR.
3274   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3275     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3276                              DAG.getConstant(0, MVT::i32));
3277     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3278                              DAG.getConstant(1, MVT::i32));
3279     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3280                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3281   }
3282 
3283   // Turn f64->i64 into VMOVRRD.
3284   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3285     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3286                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3287     // Merge the pieces into a single i64 value.
3288     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3289   }
3290 
3291   return SDValue();
3292 }
3293 
3294 /// getZeroVector - Returns a vector of specified type with all zero elements.
3295 /// Zero vectors are used to represent vector negation and in those cases
3296 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3297 /// not support i64 elements, so sometimes the zero vectors will need to be
3298 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3299 /// zero vector.
3300 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3301   assert(VT.isVector() && "Expected a vector type");
3302   // The canonical modified immediate encoding of a zero vector is....0!
3303   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3304   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3305   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3306   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3307 }
3308 
3309 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3310 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3311 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3312                                                 SelectionDAG &DAG) const {
3313   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3314   EVT VT = Op.getValueType();
3315   unsigned VTBits = VT.getSizeInBits();
3316   DebugLoc dl = Op.getDebugLoc();
3317   SDValue ShOpLo = Op.getOperand(0);
3318   SDValue ShOpHi = Op.getOperand(1);
3319   SDValue ShAmt  = Op.getOperand(2);
3320   SDValue ARMcc;
3321   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3322 
3323   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3324 
3325   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3326                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3327   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3328   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3329                                    DAG.getConstant(VTBits, MVT::i32));
3330   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3331   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3332   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3333 
3334   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3335   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3336                           ARMcc, DAG, dl);
3337   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3338   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3339                            CCR, Cmp);
3340 
3341   SDValue Ops[2] = { Lo, Hi };
3342   return DAG.getMergeValues(Ops, 2, dl);
3343 }
3344 
3345 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3346 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3347 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3348                                                SelectionDAG &DAG) const {
3349   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3350   EVT VT = Op.getValueType();
3351   unsigned VTBits = VT.getSizeInBits();
3352   DebugLoc dl = Op.getDebugLoc();
3353   SDValue ShOpLo = Op.getOperand(0);
3354   SDValue ShOpHi = Op.getOperand(1);
3355   SDValue ShAmt  = Op.getOperand(2);
3356   SDValue ARMcc;
3357 
3358   assert(Op.getOpcode() == ISD::SHL_PARTS);
3359   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3360                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3361   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3362   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3363                                    DAG.getConstant(VTBits, MVT::i32));
3364   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3365   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3366 
3367   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3368   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3369   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3370                           ARMcc, DAG, dl);
3371   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3372   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3373                            CCR, Cmp);
3374 
3375   SDValue Ops[2] = { Lo, Hi };
3376   return DAG.getMergeValues(Ops, 2, dl);
3377 }
3378 
3379 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3380                                             SelectionDAG &DAG) const {
3381   // The rounding mode is in bits 23:22 of the FPSCR.
3382   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3383   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3384   // so that the shift + and get folded into a bitfield extract.
3385   DebugLoc dl = Op.getDebugLoc();
3386   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3387                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3388                                               MVT::i32));
3389   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3390                                   DAG.getConstant(1U << 22, MVT::i32));
3391   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3392                               DAG.getConstant(22, MVT::i32));
3393   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3394                      DAG.getConstant(3, MVT::i32));
3395 }
3396 
3397 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3398                          const ARMSubtarget *ST) {
3399   EVT VT = N->getValueType(0);
3400   DebugLoc dl = N->getDebugLoc();
3401 
3402   if (!ST->hasV6T2Ops())
3403     return SDValue();
3404 
3405   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3406   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3407 }
3408 
3409 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3410                           const ARMSubtarget *ST) {
3411   EVT VT = N->getValueType(0);
3412   DebugLoc dl = N->getDebugLoc();
3413 
3414   if (!VT.isVector())
3415     return SDValue();
3416 
3417   // Lower vector shifts on NEON to use VSHL.
3418   assert(ST->hasNEON() && "unexpected vector shift");
3419 
3420   // Left shifts translate directly to the vshiftu intrinsic.
3421   if (N->getOpcode() == ISD::SHL)
3422     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3423                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3424                        N->getOperand(0), N->getOperand(1));
3425 
3426   assert((N->getOpcode() == ISD::SRA ||
3427           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3428 
3429   // NEON uses the same intrinsics for both left and right shifts.  For
3430   // right shifts, the shift amounts are negative, so negate the vector of
3431   // shift amounts.
3432   EVT ShiftVT = N->getOperand(1).getValueType();
3433   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3434                                      getZeroVector(ShiftVT, DAG, dl),
3435                                      N->getOperand(1));
3436   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3437                              Intrinsic::arm_neon_vshifts :
3438                              Intrinsic::arm_neon_vshiftu);
3439   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3440                      DAG.getConstant(vshiftInt, MVT::i32),
3441                      N->getOperand(0), NegatedCount);
3442 }
3443 
3444 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3445                                 const ARMSubtarget *ST) {
3446   EVT VT = N->getValueType(0);
3447   DebugLoc dl = N->getDebugLoc();
3448 
3449   // We can get here for a node like i32 = ISD::SHL i32, i64
3450   if (VT != MVT::i64)
3451     return SDValue();
3452 
3453   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3454          "Unknown shift to lower!");
3455 
3456   // We only lower SRA, SRL of 1 here, all others use generic lowering.
3457   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3458       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3459     return SDValue();
3460 
3461   // If we are in thumb mode, we don't have RRX.
3462   if (ST->isThumb1Only()) return SDValue();
3463 
3464   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
3465   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3466                            DAG.getConstant(0, MVT::i32));
3467   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3468                            DAG.getConstant(1, MVT::i32));
3469 
3470   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3471   // captures the result into a carry flag.
3472   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3473   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3474 
3475   // The low part is an ARMISD::RRX operand, which shifts the carry in.
3476   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3477 
3478   // Merge the pieces into a single i64 value.
3479  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3480 }
3481 
3482 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3483   SDValue TmpOp0, TmpOp1;
3484   bool Invert = false;
3485   bool Swap = false;
3486   unsigned Opc = 0;
3487 
3488   SDValue Op0 = Op.getOperand(0);
3489   SDValue Op1 = Op.getOperand(1);
3490   SDValue CC = Op.getOperand(2);
3491   EVT VT = Op.getValueType();
3492   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3493   DebugLoc dl = Op.getDebugLoc();
3494 
3495   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3496     switch (SetCCOpcode) {
3497     default: llvm_unreachable("Illegal FP comparison"); break;
3498     case ISD::SETUNE:
3499     case ISD::SETNE:  Invert = true; // Fallthrough
3500     case ISD::SETOEQ:
3501     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3502     case ISD::SETOLT:
3503     case ISD::SETLT: Swap = true; // Fallthrough
3504     case ISD::SETOGT:
3505     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3506     case ISD::SETOLE:
3507     case ISD::SETLE:  Swap = true; // Fallthrough
3508     case ISD::SETOGE:
3509     case ISD::SETGE: Opc = ARMISD::VCGE; break;
3510     case ISD::SETUGE: Swap = true; // Fallthrough
3511     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3512     case ISD::SETUGT: Swap = true; // Fallthrough
3513     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3514     case ISD::SETUEQ: Invert = true; // Fallthrough
3515     case ISD::SETONE:
3516       // Expand this to (OLT | OGT).
3517       TmpOp0 = Op0;
3518       TmpOp1 = Op1;
3519       Opc = ISD::OR;
3520       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3521       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3522       break;
3523     case ISD::SETUO: Invert = true; // Fallthrough
3524     case ISD::SETO:
3525       // Expand this to (OLT | OGE).
3526       TmpOp0 = Op0;
3527       TmpOp1 = Op1;
3528       Opc = ISD::OR;
3529       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3530       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3531       break;
3532     }
3533   } else {
3534     // Integer comparisons.
3535     switch (SetCCOpcode) {
3536     default: llvm_unreachable("Illegal integer comparison"); break;
3537     case ISD::SETNE:  Invert = true;
3538     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3539     case ISD::SETLT:  Swap = true;
3540     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3541     case ISD::SETLE:  Swap = true;
3542     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
3543     case ISD::SETULT: Swap = true;
3544     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
3545     case ISD::SETULE: Swap = true;
3546     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
3547     }
3548 
3549     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
3550     if (Opc == ARMISD::VCEQ) {
3551 
3552       SDValue AndOp;
3553       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3554         AndOp = Op0;
3555       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
3556         AndOp = Op1;
3557 
3558       // Ignore bitconvert.
3559       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
3560         AndOp = AndOp.getOperand(0);
3561 
3562       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
3563         Opc = ARMISD::VTST;
3564         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
3565         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
3566         Invert = !Invert;
3567       }
3568     }
3569   }
3570 
3571   if (Swap)
3572     std::swap(Op0, Op1);
3573 
3574   // If one of the operands is a constant vector zero, attempt to fold the
3575   // comparison to a specialized compare-against-zero form.
3576   SDValue SingleOp;
3577   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3578     SingleOp = Op0;
3579   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
3580     if (Opc == ARMISD::VCGE)
3581       Opc = ARMISD::VCLEZ;
3582     else if (Opc == ARMISD::VCGT)
3583       Opc = ARMISD::VCLTZ;
3584     SingleOp = Op1;
3585   }
3586 
3587   SDValue Result;
3588   if (SingleOp.getNode()) {
3589     switch (Opc) {
3590     case ARMISD::VCEQ:
3591       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
3592     case ARMISD::VCGE:
3593       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
3594     case ARMISD::VCLEZ:
3595       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
3596     case ARMISD::VCGT:
3597       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
3598     case ARMISD::VCLTZ:
3599       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
3600     default:
3601       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3602     }
3603   } else {
3604      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3605   }
3606 
3607   if (Invert)
3608     Result = DAG.getNOT(dl, Result, VT);
3609 
3610   return Result;
3611 }
3612 
3613 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
3614 /// valid vector constant for a NEON instruction with a "modified immediate"
3615 /// operand (e.g., VMOV).  If so, return the encoded value.
3616 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
3617                                  unsigned SplatBitSize, SelectionDAG &DAG,
3618                                  EVT &VT, bool is128Bits, NEONModImmType type) {
3619   unsigned OpCmode, Imm;
3620 
3621   // SplatBitSize is set to the smallest size that splats the vector, so a
3622   // zero vector will always have SplatBitSize == 8.  However, NEON modified
3623   // immediate instructions others than VMOV do not support the 8-bit encoding
3624   // of a zero vector, and the default encoding of zero is supposed to be the
3625   // 32-bit version.
3626   if (SplatBits == 0)
3627     SplatBitSize = 32;
3628 
3629   switch (SplatBitSize) {
3630   case 8:
3631     if (type != VMOVModImm)
3632       return SDValue();
3633     // Any 1-byte value is OK.  Op=0, Cmode=1110.
3634     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
3635     OpCmode = 0xe;
3636     Imm = SplatBits;
3637     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
3638     break;
3639 
3640   case 16:
3641     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
3642     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3643     if ((SplatBits & ~0xff) == 0) {
3644       // Value = 0x00nn: Op=x, Cmode=100x.
3645       OpCmode = 0x8;
3646       Imm = SplatBits;
3647       break;
3648     }
3649     if ((SplatBits & ~0xff00) == 0) {
3650       // Value = 0xnn00: Op=x, Cmode=101x.
3651       OpCmode = 0xa;
3652       Imm = SplatBits >> 8;
3653       break;
3654     }
3655     return SDValue();
3656 
3657   case 32:
3658     // NEON's 32-bit VMOV supports splat values where:
3659     // * only one byte is nonzero, or
3660     // * the least significant byte is 0xff and the second byte is nonzero, or
3661     // * the least significant 2 bytes are 0xff and the third is nonzero.
3662     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3663     if ((SplatBits & ~0xff) == 0) {
3664       // Value = 0x000000nn: Op=x, Cmode=000x.
3665       OpCmode = 0;
3666       Imm = SplatBits;
3667       break;
3668     }
3669     if ((SplatBits & ~0xff00) == 0) {
3670       // Value = 0x0000nn00: Op=x, Cmode=001x.
3671       OpCmode = 0x2;
3672       Imm = SplatBits >> 8;
3673       break;
3674     }
3675     if ((SplatBits & ~0xff0000) == 0) {
3676       // Value = 0x00nn0000: Op=x, Cmode=010x.
3677       OpCmode = 0x4;
3678       Imm = SplatBits >> 16;
3679       break;
3680     }
3681     if ((SplatBits & ~0xff000000) == 0) {
3682       // Value = 0xnn000000: Op=x, Cmode=011x.
3683       OpCmode = 0x6;
3684       Imm = SplatBits >> 24;
3685       break;
3686     }
3687 
3688     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
3689     if (type == OtherModImm) return SDValue();
3690 
3691     if ((SplatBits & ~0xffff) == 0 &&
3692         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
3693       // Value = 0x0000nnff: Op=x, Cmode=1100.
3694       OpCmode = 0xc;
3695       Imm = SplatBits >> 8;
3696       SplatBits |= 0xff;
3697       break;
3698     }
3699 
3700     if ((SplatBits & ~0xffffff) == 0 &&
3701         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
3702       // Value = 0x00nnffff: Op=x, Cmode=1101.
3703       OpCmode = 0xd;
3704       Imm = SplatBits >> 16;
3705       SplatBits |= 0xffff;
3706       break;
3707     }
3708 
3709     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
3710     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
3711     // VMOV.I32.  A (very) minor optimization would be to replicate the value
3712     // and fall through here to test for a valid 64-bit splat.  But, then the
3713     // caller would also need to check and handle the change in size.
3714     return SDValue();
3715 
3716   case 64: {
3717     if (type != VMOVModImm)
3718       return SDValue();
3719     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
3720     uint64_t BitMask = 0xff;
3721     uint64_t Val = 0;
3722     unsigned ImmMask = 1;
3723     Imm = 0;
3724     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
3725       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
3726         Val |= BitMask;
3727         Imm |= ImmMask;
3728       } else if ((SplatBits & BitMask) != 0) {
3729         return SDValue();
3730       }
3731       BitMask <<= 8;
3732       ImmMask <<= 1;
3733     }
3734     // Op=1, Cmode=1110.
3735     OpCmode = 0x1e;
3736     SplatBits = Val;
3737     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
3738     break;
3739   }
3740 
3741   default:
3742     llvm_unreachable("unexpected size for isNEONModifiedImm");
3743     return SDValue();
3744   }
3745 
3746   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
3747   return DAG.getTargetConstant(EncodedVal, MVT::i32);
3748 }
3749 
3750 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
3751                        bool &ReverseVEXT, unsigned &Imm) {
3752   unsigned NumElts = VT.getVectorNumElements();
3753   ReverseVEXT = false;
3754 
3755   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
3756   if (M[0] < 0)
3757     return false;
3758 
3759   Imm = M[0];
3760 
3761   // If this is a VEXT shuffle, the immediate value is the index of the first
3762   // element.  The other shuffle indices must be the successive elements after
3763   // the first one.
3764   unsigned ExpectedElt = Imm;
3765   for (unsigned i = 1; i < NumElts; ++i) {
3766     // Increment the expected index.  If it wraps around, it may still be
3767     // a VEXT but the source vectors must be swapped.
3768     ExpectedElt += 1;
3769     if (ExpectedElt == NumElts * 2) {
3770       ExpectedElt = 0;
3771       ReverseVEXT = true;
3772     }
3773 
3774     if (M[i] < 0) continue; // ignore UNDEF indices
3775     if (ExpectedElt != static_cast<unsigned>(M[i]))
3776       return false;
3777   }
3778 
3779   // Adjust the index value if the source operands will be swapped.
3780   if (ReverseVEXT)
3781     Imm -= NumElts;
3782 
3783   return true;
3784 }
3785 
3786 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
3787 /// instruction with the specified blocksize.  (The order of the elements
3788 /// within each block of the vector is reversed.)
3789 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
3790   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
3791          "Only possible block sizes for VREV are: 16, 32, 64");
3792 
3793   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3794   if (EltSz == 64)
3795     return false;
3796 
3797   unsigned NumElts = VT.getVectorNumElements();
3798   unsigned BlockElts = M[0] + 1;
3799   // If the first shuffle index is UNDEF, be optimistic.
3800   if (M[0] < 0)
3801     BlockElts = BlockSize / EltSz;
3802 
3803   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
3804     return false;
3805 
3806   for (unsigned i = 0; i < NumElts; ++i) {
3807     if (M[i] < 0) continue; // ignore UNDEF indices
3808     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
3809       return false;
3810   }
3811 
3812   return true;
3813 }
3814 
3815 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
3816   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
3817   // range, then 0 is placed into the resulting vector. So pretty much any mask
3818   // of 8 elements can work here.
3819   return VT == MVT::v8i8 && M.size() == 8;
3820 }
3821 
3822 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
3823   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3824   if (EltSz == 64)
3825     return false;
3826 
3827   unsigned NumElts = VT.getVectorNumElements();
3828   WhichResult = (M[0] == 0 ? 0 : 1);
3829   for (unsigned i = 0; i < NumElts; i += 2) {
3830     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3831         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
3832       return false;
3833   }
3834   return true;
3835 }
3836 
3837 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
3838 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
3839 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
3840 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
3841   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3842   if (EltSz == 64)
3843     return false;
3844 
3845   unsigned NumElts = VT.getVectorNumElements();
3846   WhichResult = (M[0] == 0 ? 0 : 1);
3847   for (unsigned i = 0; i < NumElts; i += 2) {
3848     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3849         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
3850       return false;
3851   }
3852   return true;
3853 }
3854 
3855 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
3856   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3857   if (EltSz == 64)
3858     return false;
3859 
3860   unsigned NumElts = VT.getVectorNumElements();
3861   WhichResult = (M[0] == 0 ? 0 : 1);
3862   for (unsigned i = 0; i != NumElts; ++i) {
3863     if (M[i] < 0) continue; // ignore UNDEF indices
3864     if ((unsigned) M[i] != 2 * i + WhichResult)
3865       return false;
3866   }
3867 
3868   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
3869   if (VT.is64BitVector() && EltSz == 32)
3870     return false;
3871 
3872   return true;
3873 }
3874 
3875 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
3876 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
3877 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
3878 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
3879   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3880   if (EltSz == 64)
3881     return false;
3882 
3883   unsigned Half = VT.getVectorNumElements() / 2;
3884   WhichResult = (M[0] == 0 ? 0 : 1);
3885   for (unsigned j = 0; j != 2; ++j) {
3886     unsigned Idx = WhichResult;
3887     for (unsigned i = 0; i != Half; ++i) {
3888       int MIdx = M[i + j * Half];
3889       if (MIdx >= 0 && (unsigned) MIdx != Idx)
3890         return false;
3891       Idx += 2;
3892     }
3893   }
3894 
3895   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
3896   if (VT.is64BitVector() && EltSz == 32)
3897     return false;
3898 
3899   return true;
3900 }
3901 
3902 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
3903   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3904   if (EltSz == 64)
3905     return false;
3906 
3907   unsigned NumElts = VT.getVectorNumElements();
3908   WhichResult = (M[0] == 0 ? 0 : 1);
3909   unsigned Idx = WhichResult * NumElts / 2;
3910   for (unsigned i = 0; i != NumElts; i += 2) {
3911     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
3912         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
3913       return false;
3914     Idx += 1;
3915   }
3916 
3917   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
3918   if (VT.is64BitVector() && EltSz == 32)
3919     return false;
3920 
3921   return true;
3922 }
3923 
3924 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
3925 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
3926 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
3927 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
3928   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3929   if (EltSz == 64)
3930     return false;
3931 
3932   unsigned NumElts = VT.getVectorNumElements();
3933   WhichResult = (M[0] == 0 ? 0 : 1);
3934   unsigned Idx = WhichResult * NumElts / 2;
3935   for (unsigned i = 0; i != NumElts; i += 2) {
3936     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
3937         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
3938       return false;
3939     Idx += 1;
3940   }
3941 
3942   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
3943   if (VT.is64BitVector() && EltSz == 32)
3944     return false;
3945 
3946   return true;
3947 }
3948 
3949 // If N is an integer constant that can be moved into a register in one
3950 // instruction, return an SDValue of such a constant (will become a MOV
3951 // instruction).  Otherwise return null.
3952 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
3953                                      const ARMSubtarget *ST, DebugLoc dl) {
3954   uint64_t Val;
3955   if (!isa<ConstantSDNode>(N))
3956     return SDValue();
3957   Val = cast<ConstantSDNode>(N)->getZExtValue();
3958 
3959   if (ST->isThumb1Only()) {
3960     if (Val <= 255 || ~Val <= 255)
3961       return DAG.getConstant(Val, MVT::i32);
3962   } else {
3963     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
3964       return DAG.getConstant(Val, MVT::i32);
3965   }
3966   return SDValue();
3967 }
3968 
3969 // If this is a case we can't handle, return null and let the default
3970 // expansion code take care of it.
3971 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
3972                                              const ARMSubtarget *ST) const {
3973   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
3974   DebugLoc dl = Op.getDebugLoc();
3975   EVT VT = Op.getValueType();
3976 
3977   APInt SplatBits, SplatUndef;
3978   unsigned SplatBitSize;
3979   bool HasAnyUndefs;
3980   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
3981     if (SplatBitSize <= 64) {
3982       // Check if an immediate VMOV works.
3983       EVT VmovVT;
3984       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
3985                                       SplatUndef.getZExtValue(), SplatBitSize,
3986                                       DAG, VmovVT, VT.is128BitVector(),
3987                                       VMOVModImm);
3988       if (Val.getNode()) {
3989         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
3990         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3991       }
3992 
3993       // Try an immediate VMVN.
3994       uint64_t NegatedImm = (~SplatBits).getZExtValue();
3995       Val = isNEONModifiedImm(NegatedImm,
3996                                       SplatUndef.getZExtValue(), SplatBitSize,
3997                                       DAG, VmovVT, VT.is128BitVector(),
3998                                       VMVNModImm);
3999       if (Val.getNode()) {
4000         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4001         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4002       }
4003 
4004       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4005       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4006         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4007         if (ImmVal != -1) {
4008           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4009           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4010         }
4011       }
4012     }
4013   }
4014 
4015   // Scan through the operands to see if only one value is used.
4016   unsigned NumElts = VT.getVectorNumElements();
4017   bool isOnlyLowElement = true;
4018   bool usesOnlyOneValue = true;
4019   bool isConstant = true;
4020   SDValue Value;
4021   for (unsigned i = 0; i < NumElts; ++i) {
4022     SDValue V = Op.getOperand(i);
4023     if (V.getOpcode() == ISD::UNDEF)
4024       continue;
4025     if (i > 0)
4026       isOnlyLowElement = false;
4027     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4028       isConstant = false;
4029 
4030     if (!Value.getNode())
4031       Value = V;
4032     else if (V != Value)
4033       usesOnlyOneValue = false;
4034   }
4035 
4036   if (!Value.getNode())
4037     return DAG.getUNDEF(VT);
4038 
4039   if (isOnlyLowElement)
4040     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4041 
4042   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4043 
4044   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4045   // i32 and try again.
4046   if (usesOnlyOneValue && EltSize <= 32) {
4047     if (!isConstant)
4048       return DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4049     if (VT.getVectorElementType().isFloatingPoint()) {
4050       SmallVector<SDValue, 8> Ops;
4051       for (unsigned i = 0; i < NumElts; ++i)
4052         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4053                                   Op.getOperand(i)));
4054       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4055       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4056       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4057       if (Val.getNode())
4058         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4059     }
4060     SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4061     if (Val.getNode())
4062       return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4063   }
4064 
4065   // If all elements are constants and the case above didn't get hit, fall back
4066   // to the default expansion, which will generate a load from the constant
4067   // pool.
4068   if (isConstant)
4069     return SDValue();
4070 
4071   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4072   if (NumElts >= 4) {
4073     SDValue shuffle = ReconstructShuffle(Op, DAG);
4074     if (shuffle != SDValue())
4075       return shuffle;
4076   }
4077 
4078   // Vectors with 32- or 64-bit elements can be built by directly assigning
4079   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4080   // will be legalized.
4081   if (EltSize >= 32) {
4082     // Do the expansion with floating-point types, since that is what the VFP
4083     // registers are defined to use, and since i64 is not legal.
4084     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4085     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4086     SmallVector<SDValue, 8> Ops;
4087     for (unsigned i = 0; i < NumElts; ++i)
4088       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4089     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4090     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4091   }
4092 
4093   return SDValue();
4094 }
4095 
4096 // Gather data to see if the operation can be modelled as a
4097 // shuffle in combination with VEXTs.
4098 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4099                                               SelectionDAG &DAG) const {
4100   DebugLoc dl = Op.getDebugLoc();
4101   EVT VT = Op.getValueType();
4102   unsigned NumElts = VT.getVectorNumElements();
4103 
4104   SmallVector<SDValue, 2> SourceVecs;
4105   SmallVector<unsigned, 2> MinElts;
4106   SmallVector<unsigned, 2> MaxElts;
4107 
4108   for (unsigned i = 0; i < NumElts; ++i) {
4109     SDValue V = Op.getOperand(i);
4110     if (V.getOpcode() == ISD::UNDEF)
4111       continue;
4112     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4113       // A shuffle can only come from building a vector from various
4114       // elements of other vectors.
4115       return SDValue();
4116     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4117                VT.getVectorElementType()) {
4118       // This code doesn't know how to handle shuffles where the vector
4119       // element types do not match (this happens because type legalization
4120       // promotes the return type of EXTRACT_VECTOR_ELT).
4121       // FIXME: It might be appropriate to extend this code to handle
4122       // mismatched types.
4123       return SDValue();
4124     }
4125 
4126     // Record this extraction against the appropriate vector if possible...
4127     SDValue SourceVec = V.getOperand(0);
4128     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4129     bool FoundSource = false;
4130     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4131       if (SourceVecs[j] == SourceVec) {
4132         if (MinElts[j] > EltNo)
4133           MinElts[j] = EltNo;
4134         if (MaxElts[j] < EltNo)
4135           MaxElts[j] = EltNo;
4136         FoundSource = true;
4137         break;
4138       }
4139     }
4140 
4141     // Or record a new source if not...
4142     if (!FoundSource) {
4143       SourceVecs.push_back(SourceVec);
4144       MinElts.push_back(EltNo);
4145       MaxElts.push_back(EltNo);
4146     }
4147   }
4148 
4149   // Currently only do something sane when at most two source vectors
4150   // involved.
4151   if (SourceVecs.size() > 2)
4152     return SDValue();
4153 
4154   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4155   int VEXTOffsets[2] = {0, 0};
4156 
4157   // This loop extracts the usage patterns of the source vectors
4158   // and prepares appropriate SDValues for a shuffle if possible.
4159   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4160     if (SourceVecs[i].getValueType() == VT) {
4161       // No VEXT necessary
4162       ShuffleSrcs[i] = SourceVecs[i];
4163       VEXTOffsets[i] = 0;
4164       continue;
4165     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4166       // It probably isn't worth padding out a smaller vector just to
4167       // break it down again in a shuffle.
4168       return SDValue();
4169     }
4170 
4171     // Since only 64-bit and 128-bit vectors are legal on ARM and
4172     // we've eliminated the other cases...
4173     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4174            "unexpected vector sizes in ReconstructShuffle");
4175 
4176     if (MaxElts[i] - MinElts[i] >= NumElts) {
4177       // Span too large for a VEXT to cope
4178       return SDValue();
4179     }
4180 
4181     if (MinElts[i] >= NumElts) {
4182       // The extraction can just take the second half
4183       VEXTOffsets[i] = NumElts;
4184       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4185                                    SourceVecs[i],
4186                                    DAG.getIntPtrConstant(NumElts));
4187     } else if (MaxElts[i] < NumElts) {
4188       // The extraction can just take the first half
4189       VEXTOffsets[i] = 0;
4190       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4191                                    SourceVecs[i],
4192                                    DAG.getIntPtrConstant(0));
4193     } else {
4194       // An actual VEXT is needed
4195       VEXTOffsets[i] = MinElts[i];
4196       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4197                                      SourceVecs[i],
4198                                      DAG.getIntPtrConstant(0));
4199       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4200                                      SourceVecs[i],
4201                                      DAG.getIntPtrConstant(NumElts));
4202       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4203                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
4204     }
4205   }
4206 
4207   SmallVector<int, 8> Mask;
4208 
4209   for (unsigned i = 0; i < NumElts; ++i) {
4210     SDValue Entry = Op.getOperand(i);
4211     if (Entry.getOpcode() == ISD::UNDEF) {
4212       Mask.push_back(-1);
4213       continue;
4214     }
4215 
4216     SDValue ExtractVec = Entry.getOperand(0);
4217     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4218                                           .getOperand(1))->getSExtValue();
4219     if (ExtractVec == SourceVecs[0]) {
4220       Mask.push_back(ExtractElt - VEXTOffsets[0]);
4221     } else {
4222       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4223     }
4224   }
4225 
4226   // Final check before we try to produce nonsense...
4227   if (isShuffleMaskLegal(Mask, VT))
4228     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4229                                 &Mask[0]);
4230 
4231   return SDValue();
4232 }
4233 
4234 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4235 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4236 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4237 /// are assumed to be legal.
4238 bool
4239 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4240                                       EVT VT) const {
4241   if (VT.getVectorNumElements() == 4 &&
4242       (VT.is128BitVector() || VT.is64BitVector())) {
4243     unsigned PFIndexes[4];
4244     for (unsigned i = 0; i != 4; ++i) {
4245       if (M[i] < 0)
4246         PFIndexes[i] = 8;
4247       else
4248         PFIndexes[i] = M[i];
4249     }
4250 
4251     // Compute the index in the perfect shuffle table.
4252     unsigned PFTableIndex =
4253       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4254     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4255     unsigned Cost = (PFEntry >> 30);
4256 
4257     if (Cost <= 4)
4258       return true;
4259   }
4260 
4261   bool ReverseVEXT;
4262   unsigned Imm, WhichResult;
4263 
4264   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4265   return (EltSize >= 32 ||
4266           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4267           isVREVMask(M, VT, 64) ||
4268           isVREVMask(M, VT, 32) ||
4269           isVREVMask(M, VT, 16) ||
4270           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4271           isVTBLMask(M, VT) ||
4272           isVTRNMask(M, VT, WhichResult) ||
4273           isVUZPMask(M, VT, WhichResult) ||
4274           isVZIPMask(M, VT, WhichResult) ||
4275           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4276           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4277           isVZIP_v_undef_Mask(M, VT, WhichResult));
4278 }
4279 
4280 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4281 /// the specified operations to build the shuffle.
4282 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4283                                       SDValue RHS, SelectionDAG &DAG,
4284                                       DebugLoc dl) {
4285   unsigned OpNum = (PFEntry >> 26) & 0x0F;
4286   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4287   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
4288 
4289   enum {
4290     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4291     OP_VREV,
4292     OP_VDUP0,
4293     OP_VDUP1,
4294     OP_VDUP2,
4295     OP_VDUP3,
4296     OP_VEXT1,
4297     OP_VEXT2,
4298     OP_VEXT3,
4299     OP_VUZPL, // VUZP, left result
4300     OP_VUZPR, // VUZP, right result
4301     OP_VZIPL, // VZIP, left result
4302     OP_VZIPR, // VZIP, right result
4303     OP_VTRNL, // VTRN, left result
4304     OP_VTRNR  // VTRN, right result
4305   };
4306 
4307   if (OpNum == OP_COPY) {
4308     if (LHSID == (1*9+2)*9+3) return LHS;
4309     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4310     return RHS;
4311   }
4312 
4313   SDValue OpLHS, OpRHS;
4314   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4315   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4316   EVT VT = OpLHS.getValueType();
4317 
4318   switch (OpNum) {
4319   default: llvm_unreachable("Unknown shuffle opcode!");
4320   case OP_VREV:
4321     // VREV divides the vector in half and swaps within the half.
4322     if (VT.getVectorElementType() == MVT::i32 ||
4323         VT.getVectorElementType() == MVT::f32)
4324       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4325     // vrev <4 x i16> -> VREV32
4326     if (VT.getVectorElementType() == MVT::i16)
4327       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4328     // vrev <4 x i8> -> VREV16
4329     assert(VT.getVectorElementType() == MVT::i8);
4330     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4331   case OP_VDUP0:
4332   case OP_VDUP1:
4333   case OP_VDUP2:
4334   case OP_VDUP3:
4335     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4336                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4337   case OP_VEXT1:
4338   case OP_VEXT2:
4339   case OP_VEXT3:
4340     return DAG.getNode(ARMISD::VEXT, dl, VT,
4341                        OpLHS, OpRHS,
4342                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4343   case OP_VUZPL:
4344   case OP_VUZPR:
4345     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4346                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4347   case OP_VZIPL:
4348   case OP_VZIPR:
4349     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4350                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4351   case OP_VTRNL:
4352   case OP_VTRNR:
4353     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4354                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4355   }
4356 }
4357 
4358 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4359                                        ArrayRef<int> ShuffleMask,
4360                                        SelectionDAG &DAG) {
4361   // Check to see if we can use the VTBL instruction.
4362   SDValue V1 = Op.getOperand(0);
4363   SDValue V2 = Op.getOperand(1);
4364   DebugLoc DL = Op.getDebugLoc();
4365 
4366   SmallVector<SDValue, 8> VTBLMask;
4367   for (ArrayRef<int>::iterator
4368          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
4369     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
4370 
4371   if (V2.getNode()->getOpcode() == ISD::UNDEF)
4372     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
4373                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4374                                    &VTBLMask[0], 8));
4375 
4376   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
4377                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4378                                  &VTBLMask[0], 8));
4379 }
4380 
4381 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4382   SDValue V1 = Op.getOperand(0);
4383   SDValue V2 = Op.getOperand(1);
4384   DebugLoc dl = Op.getDebugLoc();
4385   EVT VT = Op.getValueType();
4386   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4387 
4388   // Convert shuffles that are directly supported on NEON to target-specific
4389   // DAG nodes, instead of keeping them as shuffles and matching them again
4390   // during code selection.  This is more efficient and avoids the possibility
4391   // of inconsistencies between legalization and selection.
4392   // FIXME: floating-point vectors should be canonicalized to integer vectors
4393   // of the same time so that they get CSEd properly.
4394   ArrayRef<int> ShuffleMask = SVN->getMask();
4395 
4396   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4397   if (EltSize <= 32) {
4398     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4399       int Lane = SVN->getSplatIndex();
4400       // If this is undef splat, generate it via "just" vdup, if possible.
4401       if (Lane == -1) Lane = 0;
4402 
4403       // Test if V1 is a SCALAR_TO_VECTOR.
4404       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4405         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4406       }
4407       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
4408       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
4409       // reaches it).
4410       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
4411           !isa<ConstantSDNode>(V1.getOperand(0))) {
4412         bool IsScalarToVector = true;
4413         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
4414           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
4415             IsScalarToVector = false;
4416             break;
4417           }
4418         if (IsScalarToVector)
4419           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4420       }
4421       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
4422                          DAG.getConstant(Lane, MVT::i32));
4423     }
4424 
4425     bool ReverseVEXT;
4426     unsigned Imm;
4427     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
4428       if (ReverseVEXT)
4429         std::swap(V1, V2);
4430       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
4431                          DAG.getConstant(Imm, MVT::i32));
4432     }
4433 
4434     if (isVREVMask(ShuffleMask, VT, 64))
4435       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
4436     if (isVREVMask(ShuffleMask, VT, 32))
4437       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
4438     if (isVREVMask(ShuffleMask, VT, 16))
4439       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
4440 
4441     // Check for Neon shuffles that modify both input vectors in place.
4442     // If both results are used, i.e., if there are two shuffles with the same
4443     // source operands and with masks corresponding to both results of one of
4444     // these operations, DAG memoization will ensure that a single node is
4445     // used for both shuffles.
4446     unsigned WhichResult;
4447     if (isVTRNMask(ShuffleMask, VT, WhichResult))
4448       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4449                          V1, V2).getValue(WhichResult);
4450     if (isVUZPMask(ShuffleMask, VT, WhichResult))
4451       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4452                          V1, V2).getValue(WhichResult);
4453     if (isVZIPMask(ShuffleMask, VT, WhichResult))
4454       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4455                          V1, V2).getValue(WhichResult);
4456 
4457     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
4458       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4459                          V1, V1).getValue(WhichResult);
4460     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4461       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4462                          V1, V1).getValue(WhichResult);
4463     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4464       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4465                          V1, V1).getValue(WhichResult);
4466   }
4467 
4468   // If the shuffle is not directly supported and it has 4 elements, use
4469   // the PerfectShuffle-generated table to synthesize it from other shuffles.
4470   unsigned NumElts = VT.getVectorNumElements();
4471   if (NumElts == 4) {
4472     unsigned PFIndexes[4];
4473     for (unsigned i = 0; i != 4; ++i) {
4474       if (ShuffleMask[i] < 0)
4475         PFIndexes[i] = 8;
4476       else
4477         PFIndexes[i] = ShuffleMask[i];
4478     }
4479 
4480     // Compute the index in the perfect shuffle table.
4481     unsigned PFTableIndex =
4482       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4483     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4484     unsigned Cost = (PFEntry >> 30);
4485 
4486     if (Cost <= 4)
4487       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4488   }
4489 
4490   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
4491   if (EltSize >= 32) {
4492     // Do the expansion with floating-point types, since that is what the VFP
4493     // registers are defined to use, and since i64 is not legal.
4494     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4495     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4496     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
4497     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
4498     SmallVector<SDValue, 8> Ops;
4499     for (unsigned i = 0; i < NumElts; ++i) {
4500       if (ShuffleMask[i] < 0)
4501         Ops.push_back(DAG.getUNDEF(EltVT));
4502       else
4503         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
4504                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
4505                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
4506                                                   MVT::i32)));
4507     }
4508     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4509     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4510   }
4511 
4512   if (VT == MVT::v8i8) {
4513     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
4514     if (NewOp.getNode())
4515       return NewOp;
4516   }
4517 
4518   return SDValue();
4519 }
4520 
4521 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4522   // INSERT_VECTOR_ELT is legal only for immediate indexes.
4523   SDValue Lane = Op.getOperand(2);
4524   if (!isa<ConstantSDNode>(Lane))
4525     return SDValue();
4526 
4527   return Op;
4528 }
4529 
4530 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4531   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
4532   SDValue Lane = Op.getOperand(1);
4533   if (!isa<ConstantSDNode>(Lane))
4534     return SDValue();
4535 
4536   SDValue Vec = Op.getOperand(0);
4537   if (Op.getValueType() == MVT::i32 &&
4538       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
4539     DebugLoc dl = Op.getDebugLoc();
4540     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
4541   }
4542 
4543   return Op;
4544 }
4545 
4546 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
4547   // The only time a CONCAT_VECTORS operation can have legal types is when
4548   // two 64-bit vectors are concatenated to a 128-bit vector.
4549   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
4550          "unexpected CONCAT_VECTORS");
4551   DebugLoc dl = Op.getDebugLoc();
4552   SDValue Val = DAG.getUNDEF(MVT::v2f64);
4553   SDValue Op0 = Op.getOperand(0);
4554   SDValue Op1 = Op.getOperand(1);
4555   if (Op0.getOpcode() != ISD::UNDEF)
4556     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4557                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
4558                       DAG.getIntPtrConstant(0));
4559   if (Op1.getOpcode() != ISD::UNDEF)
4560     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4561                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
4562                       DAG.getIntPtrConstant(1));
4563   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
4564 }
4565 
4566 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
4567 /// element has been zero/sign-extended, depending on the isSigned parameter,
4568 /// from an integer type half its size.
4569 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
4570                                    bool isSigned) {
4571   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
4572   EVT VT = N->getValueType(0);
4573   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
4574     SDNode *BVN = N->getOperand(0).getNode();
4575     if (BVN->getValueType(0) != MVT::v4i32 ||
4576         BVN->getOpcode() != ISD::BUILD_VECTOR)
4577       return false;
4578     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4579     unsigned HiElt = 1 - LoElt;
4580     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
4581     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
4582     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
4583     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
4584     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
4585       return false;
4586     if (isSigned) {
4587       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
4588           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
4589         return true;
4590     } else {
4591       if (Hi0->isNullValue() && Hi1->isNullValue())
4592         return true;
4593     }
4594     return false;
4595   }
4596 
4597   if (N->getOpcode() != ISD::BUILD_VECTOR)
4598     return false;
4599 
4600   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
4601     SDNode *Elt = N->getOperand(i).getNode();
4602     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
4603       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4604       unsigned HalfSize = EltSize / 2;
4605       if (isSigned) {
4606         if (!isIntN(HalfSize, C->getSExtValue()))
4607           return false;
4608       } else {
4609         if (!isUIntN(HalfSize, C->getZExtValue()))
4610           return false;
4611       }
4612       continue;
4613     }
4614     return false;
4615   }
4616 
4617   return true;
4618 }
4619 
4620 /// isSignExtended - Check if a node is a vector value that is sign-extended
4621 /// or a constant BUILD_VECTOR with sign-extended elements.
4622 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
4623   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
4624     return true;
4625   if (isExtendedBUILD_VECTOR(N, DAG, true))
4626     return true;
4627   return false;
4628 }
4629 
4630 /// isZeroExtended - Check if a node is a vector value that is zero-extended
4631 /// or a constant BUILD_VECTOR with zero-extended elements.
4632 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
4633   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
4634     return true;
4635   if (isExtendedBUILD_VECTOR(N, DAG, false))
4636     return true;
4637   return false;
4638 }
4639 
4640 /// SkipExtension - For a node that is a SIGN_EXTEND, ZERO_EXTEND, extending
4641 /// load, or BUILD_VECTOR with extended elements, return the unextended value.
4642 static SDValue SkipExtension(SDNode *N, SelectionDAG &DAG) {
4643   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
4644     return N->getOperand(0);
4645   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
4646     return DAG.getLoad(LD->getMemoryVT(), N->getDebugLoc(), LD->getChain(),
4647                        LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
4648                        LD->isNonTemporal(), LD->isInvariant(),
4649                        LD->getAlignment());
4650   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
4651   // have been legalized as a BITCAST from v4i32.
4652   if (N->getOpcode() == ISD::BITCAST) {
4653     SDNode *BVN = N->getOperand(0).getNode();
4654     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
4655            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
4656     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4657     return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
4658                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
4659   }
4660   // Construct a new BUILD_VECTOR with elements truncated to half the size.
4661   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
4662   EVT VT = N->getValueType(0);
4663   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
4664   unsigned NumElts = VT.getVectorNumElements();
4665   MVT TruncVT = MVT::getIntegerVT(EltSize);
4666   SmallVector<SDValue, 8> Ops;
4667   for (unsigned i = 0; i != NumElts; ++i) {
4668     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
4669     const APInt &CInt = C->getAPIntValue();
4670     Ops.push_back(DAG.getConstant(CInt.trunc(EltSize), TruncVT));
4671   }
4672   return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
4673                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
4674 }
4675 
4676 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
4677   unsigned Opcode = N->getOpcode();
4678   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4679     SDNode *N0 = N->getOperand(0).getNode();
4680     SDNode *N1 = N->getOperand(1).getNode();
4681     return N0->hasOneUse() && N1->hasOneUse() &&
4682       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
4683   }
4684   return false;
4685 }
4686 
4687 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
4688   unsigned Opcode = N->getOpcode();
4689   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4690     SDNode *N0 = N->getOperand(0).getNode();
4691     SDNode *N1 = N->getOperand(1).getNode();
4692     return N0->hasOneUse() && N1->hasOneUse() &&
4693       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
4694   }
4695   return false;
4696 }
4697 
4698 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
4699   // Multiplications are only custom-lowered for 128-bit vectors so that
4700   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
4701   EVT VT = Op.getValueType();
4702   assert(VT.is128BitVector() && "unexpected type for custom-lowering ISD::MUL");
4703   SDNode *N0 = Op.getOperand(0).getNode();
4704   SDNode *N1 = Op.getOperand(1).getNode();
4705   unsigned NewOpc = 0;
4706   bool isMLA = false;
4707   bool isN0SExt = isSignExtended(N0, DAG);
4708   bool isN1SExt = isSignExtended(N1, DAG);
4709   if (isN0SExt && isN1SExt)
4710     NewOpc = ARMISD::VMULLs;
4711   else {
4712     bool isN0ZExt = isZeroExtended(N0, DAG);
4713     bool isN1ZExt = isZeroExtended(N1, DAG);
4714     if (isN0ZExt && isN1ZExt)
4715       NewOpc = ARMISD::VMULLu;
4716     else if (isN1SExt || isN1ZExt) {
4717       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
4718       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
4719       if (isN1SExt && isAddSubSExt(N0, DAG)) {
4720         NewOpc = ARMISD::VMULLs;
4721         isMLA = true;
4722       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
4723         NewOpc = ARMISD::VMULLu;
4724         isMLA = true;
4725       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
4726         std::swap(N0, N1);
4727         NewOpc = ARMISD::VMULLu;
4728         isMLA = true;
4729       }
4730     }
4731 
4732     if (!NewOpc) {
4733       if (VT == MVT::v2i64)
4734         // Fall through to expand this.  It is not legal.
4735         return SDValue();
4736       else
4737         // Other vector multiplications are legal.
4738         return Op;
4739     }
4740   }
4741 
4742   // Legalize to a VMULL instruction.
4743   DebugLoc DL = Op.getDebugLoc();
4744   SDValue Op0;
4745   SDValue Op1 = SkipExtension(N1, DAG);
4746   if (!isMLA) {
4747     Op0 = SkipExtension(N0, DAG);
4748     assert(Op0.getValueType().is64BitVector() &&
4749            Op1.getValueType().is64BitVector() &&
4750            "unexpected types for extended operands to VMULL");
4751     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
4752   }
4753 
4754   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
4755   // isel lowering to take advantage of no-stall back to back vmul + vmla.
4756   //   vmull q0, d4, d6
4757   //   vmlal q0, d5, d6
4758   // is faster than
4759   //   vaddl q0, d4, d5
4760   //   vmovl q1, d6
4761   //   vmul  q0, q0, q1
4762   SDValue N00 = SkipExtension(N0->getOperand(0).getNode(), DAG);
4763   SDValue N01 = SkipExtension(N0->getOperand(1).getNode(), DAG);
4764   EVT Op1VT = Op1.getValueType();
4765   return DAG.getNode(N0->getOpcode(), DL, VT,
4766                      DAG.getNode(NewOpc, DL, VT,
4767                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
4768                      DAG.getNode(NewOpc, DL, VT,
4769                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
4770 }
4771 
4772 static SDValue
4773 LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
4774   // Convert to float
4775   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
4776   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
4777   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
4778   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
4779   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
4780   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
4781   // Get reciprocal estimate.
4782   // float4 recip = vrecpeq_f32(yf);
4783   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4784                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
4785   // Because char has a smaller range than uchar, we can actually get away
4786   // without any newton steps.  This requires that we use a weird bias
4787   // of 0xb000, however (again, this has been exhaustively tested).
4788   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
4789   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
4790   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
4791   Y = DAG.getConstant(0xb000, MVT::i32);
4792   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
4793   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
4794   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
4795   // Convert back to short.
4796   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
4797   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
4798   return X;
4799 }
4800 
4801 static SDValue
4802 LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
4803   SDValue N2;
4804   // Convert to float.
4805   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
4806   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
4807   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
4808   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
4809   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
4810   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
4811 
4812   // Use reciprocal estimate and one refinement step.
4813   // float4 recip = vrecpeq_f32(yf);
4814   // recip *= vrecpsq_f32(yf, recip);
4815   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4816                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
4817   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4818                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
4819                    N1, N2);
4820   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
4821   // Because short has a smaller range than ushort, we can actually get away
4822   // with only a single newton step.  This requires that we use a weird bias
4823   // of 89, however (again, this has been exhaustively tested).
4824   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
4825   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
4826   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
4827   N1 = DAG.getConstant(0x89, MVT::i32);
4828   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
4829   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
4830   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
4831   // Convert back to integer and return.
4832   // return vmovn_s32(vcvt_s32_f32(result));
4833   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
4834   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
4835   return N0;
4836 }
4837 
4838 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
4839   EVT VT = Op.getValueType();
4840   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
4841          "unexpected type for custom-lowering ISD::SDIV");
4842 
4843   DebugLoc dl = Op.getDebugLoc();
4844   SDValue N0 = Op.getOperand(0);
4845   SDValue N1 = Op.getOperand(1);
4846   SDValue N2, N3;
4847 
4848   if (VT == MVT::v8i8) {
4849     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
4850     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
4851 
4852     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
4853                      DAG.getIntPtrConstant(4));
4854     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
4855                      DAG.getIntPtrConstant(4));
4856     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
4857                      DAG.getIntPtrConstant(0));
4858     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
4859                      DAG.getIntPtrConstant(0));
4860 
4861     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
4862     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
4863 
4864     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
4865     N0 = LowerCONCAT_VECTORS(N0, DAG);
4866 
4867     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
4868     return N0;
4869   }
4870   return LowerSDIV_v4i16(N0, N1, dl, DAG);
4871 }
4872 
4873 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
4874   EVT VT = Op.getValueType();
4875   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
4876          "unexpected type for custom-lowering ISD::UDIV");
4877 
4878   DebugLoc dl = Op.getDebugLoc();
4879   SDValue N0 = Op.getOperand(0);
4880   SDValue N1 = Op.getOperand(1);
4881   SDValue N2, N3;
4882 
4883   if (VT == MVT::v8i8) {
4884     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
4885     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
4886 
4887     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
4888                      DAG.getIntPtrConstant(4));
4889     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
4890                      DAG.getIntPtrConstant(4));
4891     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
4892                      DAG.getIntPtrConstant(0));
4893     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
4894                      DAG.getIntPtrConstant(0));
4895 
4896     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
4897     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
4898 
4899     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
4900     N0 = LowerCONCAT_VECTORS(N0, DAG);
4901 
4902     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
4903                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
4904                      N0);
4905     return N0;
4906   }
4907 
4908   // v4i16 sdiv ... Convert to float.
4909   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
4910   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
4911   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
4912   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
4913   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
4914   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
4915 
4916   // Use reciprocal estimate and two refinement steps.
4917   // float4 recip = vrecpeq_f32(yf);
4918   // recip *= vrecpsq_f32(yf, recip);
4919   // recip *= vrecpsq_f32(yf, recip);
4920   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4921                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
4922   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4923                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
4924                    BN1, N2);
4925   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
4926   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4927                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
4928                    BN1, N2);
4929   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
4930   // Simply multiplying by the reciprocal estimate can leave us a few ulps
4931   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
4932   // and that it will never cause us to return an answer too large).
4933   // float4 result = as_float4(as_int4(xf*recip) + 2);
4934   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
4935   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
4936   N1 = DAG.getConstant(2, MVT::i32);
4937   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
4938   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
4939   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
4940   // Convert back to integer and return.
4941   // return vmovn_u32(vcvt_s32_f32(result));
4942   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
4943   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
4944   return N0;
4945 }
4946 
4947 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
4948   EVT VT = Op.getNode()->getValueType(0);
4949   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4950 
4951   unsigned Opc;
4952   bool ExtraOp = false;
4953   switch (Op.getOpcode()) {
4954   default: assert(0 && "Invalid code");
4955   case ISD::ADDC: Opc = ARMISD::ADDC; break;
4956   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
4957   case ISD::SUBC: Opc = ARMISD::SUBC; break;
4958   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
4959   }
4960 
4961   if (!ExtraOp)
4962     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
4963                        Op.getOperand(1));
4964   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
4965                      Op.getOperand(1), Op.getOperand(2));
4966 }
4967 
4968 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
4969   // Monotonic load/store is legal for all targets
4970   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
4971     return Op;
4972 
4973   // Aquire/Release load/store is not legal for targets without a
4974   // dmb or equivalent available.
4975   return SDValue();
4976 }
4977 
4978 
4979 static void
4980 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
4981                     SelectionDAG &DAG, unsigned NewOp) {
4982   DebugLoc dl = Node->getDebugLoc();
4983   assert (Node->getValueType(0) == MVT::i64 &&
4984           "Only know how to expand i64 atomics");
4985 
4986   SmallVector<SDValue, 6> Ops;
4987   Ops.push_back(Node->getOperand(0)); // Chain
4988   Ops.push_back(Node->getOperand(1)); // Ptr
4989   // Low part of Val1
4990   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4991                             Node->getOperand(2), DAG.getIntPtrConstant(0)));
4992   // High part of Val1
4993   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4994                             Node->getOperand(2), DAG.getIntPtrConstant(1)));
4995   if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
4996     // High part of Val1
4997     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4998                               Node->getOperand(3), DAG.getIntPtrConstant(0)));
4999     // High part of Val2
5000     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5001                               Node->getOperand(3), DAG.getIntPtrConstant(1)));
5002   }
5003   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5004   SDValue Result =
5005     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5006                             cast<MemSDNode>(Node)->getMemOperand());
5007   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5008   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5009   Results.push_back(Result.getValue(2));
5010 }
5011 
5012 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5013   switch (Op.getOpcode()) {
5014   default: llvm_unreachable("Don't know how to custom lower this!");
5015   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
5016   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
5017   case ISD::GlobalAddress:
5018     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5019       LowerGlobalAddressELF(Op, DAG);
5020   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5021   case ISD::SELECT:        return LowerSELECT(Op, DAG);
5022   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
5023   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
5024   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
5025   case ISD::VASTART:       return LowerVASTART(Op, DAG);
5026   case ISD::MEMBARRIER:    return LowerMEMBARRIER(Op, DAG, Subtarget);
5027   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5028   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
5029   case ISD::SINT_TO_FP:
5030   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
5031   case ISD::FP_TO_SINT:
5032   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
5033   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
5034   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
5035   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
5036   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5037   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5038   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5039   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5040                                                                Subtarget);
5041   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
5042   case ISD::SHL:
5043   case ISD::SRL:
5044   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
5045   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
5046   case ISD::SRL_PARTS:
5047   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
5048   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5049   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
5050   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5051   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5052   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5053   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5054   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5055   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
5056   case ISD::MUL:           return LowerMUL(Op, DAG);
5057   case ISD::SDIV:          return LowerSDIV(Op, DAG);
5058   case ISD::UDIV:          return LowerUDIV(Op, DAG);
5059   case ISD::ADDC:
5060   case ISD::ADDE:
5061   case ISD::SUBC:
5062   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5063   case ISD::ATOMIC_LOAD:
5064   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
5065   }
5066   return SDValue();
5067 }
5068 
5069 /// ReplaceNodeResults - Replace the results of node with an illegal result
5070 /// type with new values built out of custom code.
5071 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5072                                            SmallVectorImpl<SDValue>&Results,
5073                                            SelectionDAG &DAG) const {
5074   SDValue Res;
5075   switch (N->getOpcode()) {
5076   default:
5077     llvm_unreachable("Don't know how to custom expand this!");
5078     break;
5079   case ISD::BITCAST:
5080     Res = ExpandBITCAST(N, DAG);
5081     break;
5082   case ISD::SRL:
5083   case ISD::SRA:
5084     Res = Expand64BitShift(N, DAG, Subtarget);
5085     break;
5086   case ISD::ATOMIC_LOAD_ADD:
5087     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5088     return;
5089   case ISD::ATOMIC_LOAD_AND:
5090     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5091     return;
5092   case ISD::ATOMIC_LOAD_NAND:
5093     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5094     return;
5095   case ISD::ATOMIC_LOAD_OR:
5096     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5097     return;
5098   case ISD::ATOMIC_LOAD_SUB:
5099     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5100     return;
5101   case ISD::ATOMIC_LOAD_XOR:
5102     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5103     return;
5104   case ISD::ATOMIC_SWAP:
5105     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5106     return;
5107   case ISD::ATOMIC_CMP_SWAP:
5108     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5109     return;
5110   }
5111   if (Res.getNode())
5112     Results.push_back(Res);
5113 }
5114 
5115 //===----------------------------------------------------------------------===//
5116 //                           ARM Scheduler Hooks
5117 //===----------------------------------------------------------------------===//
5118 
5119 MachineBasicBlock *
5120 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5121                                      MachineBasicBlock *BB,
5122                                      unsigned Size) const {
5123   unsigned dest    = MI->getOperand(0).getReg();
5124   unsigned ptr     = MI->getOperand(1).getReg();
5125   unsigned oldval  = MI->getOperand(2).getReg();
5126   unsigned newval  = MI->getOperand(3).getReg();
5127   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5128   DebugLoc dl = MI->getDebugLoc();
5129   bool isThumb2 = Subtarget->isThumb2();
5130 
5131   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5132   unsigned scratch =
5133     MRI.createVirtualRegister(isThumb2 ? ARM::rGPRRegisterClass
5134                                        : ARM::GPRRegisterClass);
5135 
5136   if (isThumb2) {
5137     MRI.constrainRegClass(dest, ARM::rGPRRegisterClass);
5138     MRI.constrainRegClass(oldval, ARM::rGPRRegisterClass);
5139     MRI.constrainRegClass(newval, ARM::rGPRRegisterClass);
5140   }
5141 
5142   unsigned ldrOpc, strOpc;
5143   switch (Size) {
5144   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5145   case 1:
5146     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5147     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5148     break;
5149   case 2:
5150     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5151     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5152     break;
5153   case 4:
5154     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5155     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5156     break;
5157   }
5158 
5159   MachineFunction *MF = BB->getParent();
5160   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5161   MachineFunction::iterator It = BB;
5162   ++It; // insert the new blocks after the current block
5163 
5164   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5165   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5166   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5167   MF->insert(It, loop1MBB);
5168   MF->insert(It, loop2MBB);
5169   MF->insert(It, exitMBB);
5170 
5171   // Transfer the remainder of BB and its successor edges to exitMBB.
5172   exitMBB->splice(exitMBB->begin(), BB,
5173                   llvm::next(MachineBasicBlock::iterator(MI)),
5174                   BB->end());
5175   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5176 
5177   //  thisMBB:
5178   //   ...
5179   //   fallthrough --> loop1MBB
5180   BB->addSuccessor(loop1MBB);
5181 
5182   // loop1MBB:
5183   //   ldrex dest, [ptr]
5184   //   cmp dest, oldval
5185   //   bne exitMBB
5186   BB = loop1MBB;
5187   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5188   if (ldrOpc == ARM::t2LDREX)
5189     MIB.addImm(0);
5190   AddDefaultPred(MIB);
5191   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5192                  .addReg(dest).addReg(oldval));
5193   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5194     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5195   BB->addSuccessor(loop2MBB);
5196   BB->addSuccessor(exitMBB);
5197 
5198   // loop2MBB:
5199   //   strex scratch, newval, [ptr]
5200   //   cmp scratch, #0
5201   //   bne loop1MBB
5202   BB = loop2MBB;
5203   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5204   if (strOpc == ARM::t2STREX)
5205     MIB.addImm(0);
5206   AddDefaultPred(MIB);
5207   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5208                  .addReg(scratch).addImm(0));
5209   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5210     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5211   BB->addSuccessor(loop1MBB);
5212   BB->addSuccessor(exitMBB);
5213 
5214   //  exitMBB:
5215   //   ...
5216   BB = exitMBB;
5217 
5218   MI->eraseFromParent();   // The instruction is gone now.
5219 
5220   return BB;
5221 }
5222 
5223 MachineBasicBlock *
5224 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5225                                     unsigned Size, unsigned BinOpcode) const {
5226   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5227   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5228 
5229   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5230   MachineFunction *MF = BB->getParent();
5231   MachineFunction::iterator It = BB;
5232   ++It;
5233 
5234   unsigned dest = MI->getOperand(0).getReg();
5235   unsigned ptr = MI->getOperand(1).getReg();
5236   unsigned incr = MI->getOperand(2).getReg();
5237   DebugLoc dl = MI->getDebugLoc();
5238   bool isThumb2 = Subtarget->isThumb2();
5239 
5240   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5241   if (isThumb2) {
5242     MRI.constrainRegClass(dest, ARM::rGPRRegisterClass);
5243     MRI.constrainRegClass(ptr, ARM::rGPRRegisterClass);
5244   }
5245 
5246   unsigned ldrOpc, strOpc;
5247   switch (Size) {
5248   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5249   case 1:
5250     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5251     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5252     break;
5253   case 2:
5254     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5255     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5256     break;
5257   case 4:
5258     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5259     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5260     break;
5261   }
5262 
5263   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5264   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5265   MF->insert(It, loopMBB);
5266   MF->insert(It, exitMBB);
5267 
5268   // Transfer the remainder of BB and its successor edges to exitMBB.
5269   exitMBB->splice(exitMBB->begin(), BB,
5270                   llvm::next(MachineBasicBlock::iterator(MI)),
5271                   BB->end());
5272   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5273 
5274   TargetRegisterClass *TRC =
5275     isThumb2 ? ARM::tGPRRegisterClass : ARM::GPRRegisterClass;
5276   unsigned scratch = MRI.createVirtualRegister(TRC);
5277   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
5278 
5279   //  thisMBB:
5280   //   ...
5281   //   fallthrough --> loopMBB
5282   BB->addSuccessor(loopMBB);
5283 
5284   //  loopMBB:
5285   //   ldrex dest, ptr
5286   //   <binop> scratch2, dest, incr
5287   //   strex scratch, scratch2, ptr
5288   //   cmp scratch, #0
5289   //   bne- loopMBB
5290   //   fallthrough --> exitMBB
5291   BB = loopMBB;
5292   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5293   if (ldrOpc == ARM::t2LDREX)
5294     MIB.addImm(0);
5295   AddDefaultPred(MIB);
5296   if (BinOpcode) {
5297     // operand order needs to go the other way for NAND
5298     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
5299       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5300                      addReg(incr).addReg(dest)).addReg(0);
5301     else
5302       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5303                      addReg(dest).addReg(incr)).addReg(0);
5304   }
5305 
5306   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5307   if (strOpc == ARM::t2STREX)
5308     MIB.addImm(0);
5309   AddDefaultPred(MIB);
5310   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5311                  .addReg(scratch).addImm(0));
5312   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5313     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5314 
5315   BB->addSuccessor(loopMBB);
5316   BB->addSuccessor(exitMBB);
5317 
5318   //  exitMBB:
5319   //   ...
5320   BB = exitMBB;
5321 
5322   MI->eraseFromParent();   // The instruction is gone now.
5323 
5324   return BB;
5325 }
5326 
5327 MachineBasicBlock *
5328 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
5329                                           MachineBasicBlock *BB,
5330                                           unsigned Size,
5331                                           bool signExtend,
5332                                           ARMCC::CondCodes Cond) const {
5333   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5334 
5335   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5336   MachineFunction *MF = BB->getParent();
5337   MachineFunction::iterator It = BB;
5338   ++It;
5339 
5340   unsigned dest = MI->getOperand(0).getReg();
5341   unsigned ptr = MI->getOperand(1).getReg();
5342   unsigned incr = MI->getOperand(2).getReg();
5343   unsigned oldval = dest;
5344   DebugLoc dl = MI->getDebugLoc();
5345   bool isThumb2 = Subtarget->isThumb2();
5346 
5347   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5348   if (isThumb2) {
5349     MRI.constrainRegClass(dest, ARM::rGPRRegisterClass);
5350     MRI.constrainRegClass(ptr, ARM::rGPRRegisterClass);
5351   }
5352 
5353   unsigned ldrOpc, strOpc, extendOpc;
5354   switch (Size) {
5355   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5356   case 1:
5357     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5358     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5359     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
5360     break;
5361   case 2:
5362     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5363     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5364     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
5365     break;
5366   case 4:
5367     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5368     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5369     extendOpc = 0;
5370     break;
5371   }
5372 
5373   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5374   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5375   MF->insert(It, loopMBB);
5376   MF->insert(It, exitMBB);
5377 
5378   // Transfer the remainder of BB and its successor edges to exitMBB.
5379   exitMBB->splice(exitMBB->begin(), BB,
5380                   llvm::next(MachineBasicBlock::iterator(MI)),
5381                   BB->end());
5382   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5383 
5384   TargetRegisterClass *TRC =
5385     isThumb2 ? ARM::tGPRRegisterClass : ARM::GPRRegisterClass;
5386   unsigned scratch = MRI.createVirtualRegister(TRC);
5387   unsigned scratch2 = MRI.createVirtualRegister(TRC);
5388 
5389   //  thisMBB:
5390   //   ...
5391   //   fallthrough --> loopMBB
5392   BB->addSuccessor(loopMBB);
5393 
5394   //  loopMBB:
5395   //   ldrex dest, ptr
5396   //   (sign extend dest, if required)
5397   //   cmp dest, incr
5398   //   cmov.cond scratch2, dest, incr
5399   //   strex scratch, scratch2, ptr
5400   //   cmp scratch, #0
5401   //   bne- loopMBB
5402   //   fallthrough --> exitMBB
5403   BB = loopMBB;
5404   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5405   if (ldrOpc == ARM::t2LDREX)
5406     MIB.addImm(0);
5407   AddDefaultPred(MIB);
5408 
5409   // Sign extend the value, if necessary.
5410   if (signExtend && extendOpc) {
5411     oldval = MRI.createVirtualRegister(ARM::GPRRegisterClass);
5412     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
5413                      .addReg(dest)
5414                      .addImm(0));
5415   }
5416 
5417   // Build compare and cmov instructions.
5418   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5419                  .addReg(oldval).addReg(incr));
5420   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
5421          .addReg(oldval).addReg(incr).addImm(Cond).addReg(ARM::CPSR);
5422 
5423   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5424   if (strOpc == ARM::t2STREX)
5425     MIB.addImm(0);
5426   AddDefaultPred(MIB);
5427   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5428                  .addReg(scratch).addImm(0));
5429   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5430     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5431 
5432   BB->addSuccessor(loopMBB);
5433   BB->addSuccessor(exitMBB);
5434 
5435   //  exitMBB:
5436   //   ...
5437   BB = exitMBB;
5438 
5439   MI->eraseFromParent();   // The instruction is gone now.
5440 
5441   return BB;
5442 }
5443 
5444 MachineBasicBlock *
5445 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
5446                                       unsigned Op1, unsigned Op2,
5447                                       bool NeedsCarry, bool IsCmpxchg) const {
5448   // This also handles ATOMIC_SWAP, indicated by Op1==0.
5449   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5450 
5451   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5452   MachineFunction *MF = BB->getParent();
5453   MachineFunction::iterator It = BB;
5454   ++It;
5455 
5456   unsigned destlo = MI->getOperand(0).getReg();
5457   unsigned desthi = MI->getOperand(1).getReg();
5458   unsigned ptr = MI->getOperand(2).getReg();
5459   unsigned vallo = MI->getOperand(3).getReg();
5460   unsigned valhi = MI->getOperand(4).getReg();
5461   DebugLoc dl = MI->getDebugLoc();
5462   bool isThumb2 = Subtarget->isThumb2();
5463 
5464   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5465   if (isThumb2) {
5466     MRI.constrainRegClass(destlo, ARM::rGPRRegisterClass);
5467     MRI.constrainRegClass(desthi, ARM::rGPRRegisterClass);
5468     MRI.constrainRegClass(ptr, ARM::rGPRRegisterClass);
5469   }
5470 
5471   unsigned ldrOpc = isThumb2 ? ARM::t2LDREXD : ARM::LDREXD;
5472   unsigned strOpc = isThumb2 ? ARM::t2STREXD : ARM::STREXD;
5473 
5474   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5475   MachineBasicBlock *contBB = 0, *cont2BB = 0;
5476   if (IsCmpxchg) {
5477     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
5478     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
5479   }
5480   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5481   MF->insert(It, loopMBB);
5482   if (IsCmpxchg) {
5483     MF->insert(It, contBB);
5484     MF->insert(It, cont2BB);
5485   }
5486   MF->insert(It, exitMBB);
5487 
5488   // Transfer the remainder of BB and its successor edges to exitMBB.
5489   exitMBB->splice(exitMBB->begin(), BB,
5490                   llvm::next(MachineBasicBlock::iterator(MI)),
5491                   BB->end());
5492   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5493 
5494   TargetRegisterClass *TRC =
5495     isThumb2 ? ARM::tGPRRegisterClass : ARM::GPRRegisterClass;
5496   unsigned storesuccess = MRI.createVirtualRegister(TRC);
5497 
5498   //  thisMBB:
5499   //   ...
5500   //   fallthrough --> loopMBB
5501   BB->addSuccessor(loopMBB);
5502 
5503   //  loopMBB:
5504   //   ldrexd r2, r3, ptr
5505   //   <binopa> r0, r2, incr
5506   //   <binopb> r1, r3, incr
5507   //   strexd storesuccess, r0, r1, ptr
5508   //   cmp storesuccess, #0
5509   //   bne- loopMBB
5510   //   fallthrough --> exitMBB
5511   //
5512   // Note that the registers are explicitly specified because there is not any
5513   // way to force the register allocator to allocate a register pair.
5514   //
5515   // FIXME: The hardcoded registers are not necessary for Thumb2, but we
5516   // need to properly enforce the restriction that the two output registers
5517   // for ldrexd must be different.
5518   BB = loopMBB;
5519   // Load
5520   AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
5521                  .addReg(ARM::R2, RegState::Define)
5522                  .addReg(ARM::R3, RegState::Define).addReg(ptr));
5523   // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
5524   BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo).addReg(ARM::R2);
5525   BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi).addReg(ARM::R3);
5526 
5527   if (IsCmpxchg) {
5528     // Add early exit
5529     for (unsigned i = 0; i < 2; i++) {
5530       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
5531                                                          ARM::CMPrr))
5532                      .addReg(i == 0 ? destlo : desthi)
5533                      .addReg(i == 0 ? vallo : valhi));
5534       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5535         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5536       BB->addSuccessor(exitMBB);
5537       BB->addSuccessor(i == 0 ? contBB : cont2BB);
5538       BB = (i == 0 ? contBB : cont2BB);
5539     }
5540 
5541     // Copy to physregs for strexd
5542     unsigned setlo = MI->getOperand(5).getReg();
5543     unsigned sethi = MI->getOperand(6).getReg();
5544     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(setlo);
5545     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(sethi);
5546   } else if (Op1) {
5547     // Perform binary operation
5548     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), ARM::R0)
5549                    .addReg(destlo).addReg(vallo))
5550         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
5551     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), ARM::R1)
5552                    .addReg(desthi).addReg(valhi)).addReg(0);
5553   } else {
5554     // Copy to physregs for strexd
5555     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(vallo);
5556     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(valhi);
5557   }
5558 
5559   // Store
5560   AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
5561                  .addReg(ARM::R0).addReg(ARM::R1).addReg(ptr));
5562   // Cmp+jump
5563   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5564                  .addReg(storesuccess).addImm(0));
5565   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5566     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5567 
5568   BB->addSuccessor(loopMBB);
5569   BB->addSuccessor(exitMBB);
5570 
5571   //  exitMBB:
5572   //   ...
5573   BB = exitMBB;
5574 
5575   MI->eraseFromParent();   // The instruction is gone now.
5576 
5577   return BB;
5578 }
5579 
5580 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
5581 /// registers the function context.
5582 void ARMTargetLowering::
5583 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
5584                        MachineBasicBlock *DispatchBB, int FI) const {
5585   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5586   DebugLoc dl = MI->getDebugLoc();
5587   MachineFunction *MF = MBB->getParent();
5588   MachineRegisterInfo *MRI = &MF->getRegInfo();
5589   MachineConstantPool *MCP = MF->getConstantPool();
5590   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5591   const Function *F = MF->getFunction();
5592 
5593   bool isThumb = Subtarget->isThumb();
5594   bool isThumb2 = Subtarget->isThumb2();
5595 
5596   unsigned PCLabelId = AFI->createPICLabelUId();
5597   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
5598   ARMConstantPoolValue *CPV =
5599     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
5600   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
5601 
5602   const TargetRegisterClass *TRC =
5603     isThumb ? ARM::tGPRRegisterClass : ARM::GPRRegisterClass;
5604 
5605   // Grab constant pool and fixed stack memory operands.
5606   MachineMemOperand *CPMMO =
5607     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
5608                              MachineMemOperand::MOLoad, 4, 4);
5609 
5610   MachineMemOperand *FIMMOSt =
5611     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5612                              MachineMemOperand::MOStore, 4, 4);
5613 
5614   // Load the address of the dispatch MBB into the jump buffer.
5615   if (isThumb2) {
5616     // Incoming value: jbuf
5617     //   ldr.n  r5, LCPI1_1
5618     //   orr    r5, r5, #1
5619     //   add    r5, pc
5620     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
5621     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5622     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
5623                    .addConstantPoolIndex(CPI)
5624                    .addMemOperand(CPMMO));
5625     // Set the low bit because of thumb mode.
5626     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5627     AddDefaultCC(
5628       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
5629                      .addReg(NewVReg1, RegState::Kill)
5630                      .addImm(0x01)));
5631     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5632     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
5633       .addReg(NewVReg2, RegState::Kill)
5634       .addImm(PCLabelId);
5635     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
5636                    .addReg(NewVReg3, RegState::Kill)
5637                    .addFrameIndex(FI)
5638                    .addImm(36)  // &jbuf[1] :: pc
5639                    .addMemOperand(FIMMOSt));
5640   } else if (isThumb) {
5641     // Incoming value: jbuf
5642     //   ldr.n  r1, LCPI1_4
5643     //   add    r1, pc
5644     //   mov    r2, #1
5645     //   orrs   r1, r2
5646     //   add    r2, $jbuf, #+4 ; &jbuf[1]
5647     //   str    r1, [r2]
5648     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5649     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
5650                    .addConstantPoolIndex(CPI)
5651                    .addMemOperand(CPMMO));
5652     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5653     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
5654       .addReg(NewVReg1, RegState::Kill)
5655       .addImm(PCLabelId);
5656     // Set the low bit because of thumb mode.
5657     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5658     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
5659                    .addReg(ARM::CPSR, RegState::Define)
5660                    .addImm(1));
5661     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5662     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
5663                    .addReg(ARM::CPSR, RegState::Define)
5664                    .addReg(NewVReg2, RegState::Kill)
5665                    .addReg(NewVReg3, RegState::Kill));
5666     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
5667     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
5668                    .addFrameIndex(FI)
5669                    .addImm(36)); // &jbuf[1] :: pc
5670     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
5671                    .addReg(NewVReg4, RegState::Kill)
5672                    .addReg(NewVReg5, RegState::Kill)
5673                    .addImm(0)
5674                    .addMemOperand(FIMMOSt));
5675   } else {
5676     // Incoming value: jbuf
5677     //   ldr  r1, LCPI1_1
5678     //   add  r1, pc, r1
5679     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
5680     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5681     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
5682                    .addConstantPoolIndex(CPI)
5683                    .addImm(0)
5684                    .addMemOperand(CPMMO));
5685     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5686     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
5687                    .addReg(NewVReg1, RegState::Kill)
5688                    .addImm(PCLabelId));
5689     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
5690                    .addReg(NewVReg2, RegState::Kill)
5691                    .addFrameIndex(FI)
5692                    .addImm(36)  // &jbuf[1] :: pc
5693                    .addMemOperand(FIMMOSt));
5694   }
5695 }
5696 
5697 MachineBasicBlock *ARMTargetLowering::
5698 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
5699   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5700   DebugLoc dl = MI->getDebugLoc();
5701   MachineFunction *MF = MBB->getParent();
5702   MachineRegisterInfo *MRI = &MF->getRegInfo();
5703   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5704   MachineFrameInfo *MFI = MF->getFrameInfo();
5705   int FI = MFI->getFunctionContextIndex();
5706 
5707   const TargetRegisterClass *TRC =
5708     Subtarget->isThumb() ? ARM::tGPRRegisterClass : ARM::GPRRegisterClass;
5709 
5710   // Get a mapping of the call site numbers to all of the landing pads they're
5711   // associated with.
5712   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
5713   unsigned MaxCSNum = 0;
5714   MachineModuleInfo &MMI = MF->getMMI();
5715   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; ++BB) {
5716     if (!BB->isLandingPad()) continue;
5717 
5718     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
5719     // pad.
5720     for (MachineBasicBlock::iterator
5721            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
5722       if (!II->isEHLabel()) continue;
5723 
5724       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
5725       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
5726 
5727       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
5728       for (SmallVectorImpl<unsigned>::iterator
5729              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
5730            CSI != CSE; ++CSI) {
5731         CallSiteNumToLPad[*CSI].push_back(BB);
5732         MaxCSNum = std::max(MaxCSNum, *CSI);
5733       }
5734       break;
5735     }
5736   }
5737 
5738   // Get an ordered list of the machine basic blocks for the jump table.
5739   std::vector<MachineBasicBlock*> LPadList;
5740   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
5741   LPadList.reserve(CallSiteNumToLPad.size());
5742   for (unsigned I = 1; I <= MaxCSNum; ++I) {
5743     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
5744     for (SmallVectorImpl<MachineBasicBlock*>::iterator
5745            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
5746       LPadList.push_back(*II);
5747       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
5748     }
5749   }
5750 
5751   assert(!LPadList.empty() &&
5752          "No landing pad destinations for the dispatch jump table!");
5753 
5754   // Create the jump table and associated information.
5755   MachineJumpTableInfo *JTI =
5756     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
5757   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
5758   unsigned UId = AFI->createJumpTableUId();
5759 
5760   // Create the MBBs for the dispatch code.
5761 
5762   // Shove the dispatch's address into the return slot in the function context.
5763   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
5764   DispatchBB->setIsLandingPad();
5765 
5766   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
5767   BuildMI(TrapBB, dl, TII->get(Subtarget->isThumb() ? ARM::tTRAP : ARM::TRAP));
5768   DispatchBB->addSuccessor(TrapBB);
5769 
5770   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
5771   DispatchBB->addSuccessor(DispContBB);
5772 
5773   // Insert and MBBs.
5774   MF->insert(MF->end(), DispatchBB);
5775   MF->insert(MF->end(), DispContBB);
5776   MF->insert(MF->end(), TrapBB);
5777 
5778   // Insert code into the entry block that creates and registers the function
5779   // context.
5780   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
5781 
5782   MachineMemOperand *FIMMOLd =
5783     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5784                              MachineMemOperand::MOLoad |
5785                              MachineMemOperand::MOVolatile, 4, 4);
5786 
5787   if (AFI->isThumb1OnlyFunction())
5788     BuildMI(DispatchBB, dl, TII->get(ARM::tInt_eh_sjlj_dispatchsetup));
5789   else if (!Subtarget->hasVFP2())
5790     BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup_nofp));
5791   else
5792     BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
5793 
5794   unsigned NumLPads = LPadList.size();
5795   if (Subtarget->isThumb2()) {
5796     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5797     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
5798                    .addFrameIndex(FI)
5799                    .addImm(4)
5800                    .addMemOperand(FIMMOLd));
5801 
5802     if (NumLPads < 256) {
5803       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
5804                      .addReg(NewVReg1)
5805                      .addImm(LPadList.size()));
5806     } else {
5807       unsigned VReg1 = MRI->createVirtualRegister(TRC);
5808       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
5809                      .addImm(NumLPads & 0xFFFF));
5810 
5811       unsigned VReg2 = VReg1;
5812       if ((NumLPads & 0xFFFF0000) != 0) {
5813         VReg2 = MRI->createVirtualRegister(TRC);
5814         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
5815                        .addReg(VReg1)
5816                        .addImm(NumLPads >> 16));
5817       }
5818 
5819       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
5820                      .addReg(NewVReg1)
5821                      .addReg(VReg2));
5822     }
5823 
5824     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
5825       .addMBB(TrapBB)
5826       .addImm(ARMCC::HI)
5827       .addReg(ARM::CPSR);
5828 
5829     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5830     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
5831                    .addJumpTableIndex(MJTI)
5832                    .addImm(UId));
5833 
5834     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5835     AddDefaultCC(
5836       AddDefaultPred(
5837         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
5838         .addReg(NewVReg3, RegState::Kill)
5839         .addReg(NewVReg1)
5840         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
5841 
5842     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
5843       .addReg(NewVReg4, RegState::Kill)
5844       .addReg(NewVReg1)
5845       .addJumpTableIndex(MJTI)
5846       .addImm(UId);
5847   } else if (Subtarget->isThumb()) {
5848     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5849     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
5850                    .addFrameIndex(FI)
5851                    .addImm(1)
5852                    .addMemOperand(FIMMOLd));
5853 
5854     if (NumLPads < 256) {
5855       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
5856                      .addReg(NewVReg1)
5857                      .addImm(NumLPads));
5858     } else {
5859       MachineConstantPool *ConstantPool = MF->getConstantPool();
5860       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
5861       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
5862 
5863       // MachineConstantPool wants an explicit alignment.
5864       unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
5865       if (Align == 0)
5866         Align = getTargetData()->getTypeAllocSize(C->getType());
5867       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
5868 
5869       unsigned VReg1 = MRI->createVirtualRegister(TRC);
5870       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
5871                      .addReg(VReg1, RegState::Define)
5872                      .addConstantPoolIndex(Idx));
5873       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
5874                      .addReg(NewVReg1)
5875                      .addReg(VReg1));
5876     }
5877 
5878     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
5879       .addMBB(TrapBB)
5880       .addImm(ARMCC::HI)
5881       .addReg(ARM::CPSR);
5882 
5883     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5884     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
5885                    .addReg(ARM::CPSR, RegState::Define)
5886                    .addReg(NewVReg1)
5887                    .addImm(2));
5888 
5889     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5890     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
5891                    .addJumpTableIndex(MJTI)
5892                    .addImm(UId));
5893 
5894     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5895     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
5896                    .addReg(ARM::CPSR, RegState::Define)
5897                    .addReg(NewVReg2, RegState::Kill)
5898                    .addReg(NewVReg3));
5899 
5900     MachineMemOperand *JTMMOLd =
5901       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
5902                                MachineMemOperand::MOLoad, 4, 4);
5903 
5904     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
5905     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
5906                    .addReg(NewVReg4, RegState::Kill)
5907                    .addImm(0)
5908                    .addMemOperand(JTMMOLd));
5909 
5910     unsigned NewVReg6 = MRI->createVirtualRegister(TRC);
5911     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
5912                    .addReg(ARM::CPSR, RegState::Define)
5913                    .addReg(NewVReg5, RegState::Kill)
5914                    .addReg(NewVReg3));
5915 
5916     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
5917       .addReg(NewVReg6, RegState::Kill)
5918       .addJumpTableIndex(MJTI)
5919       .addImm(UId);
5920   } else {
5921     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5922     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
5923                    .addFrameIndex(FI)
5924                    .addImm(4)
5925                    .addMemOperand(FIMMOLd));
5926 
5927     if (NumLPads < 256) {
5928       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
5929                      .addReg(NewVReg1)
5930                      .addImm(NumLPads));
5931     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
5932       unsigned VReg1 = MRI->createVirtualRegister(TRC);
5933       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
5934                      .addImm(NumLPads & 0xFFFF));
5935 
5936       unsigned VReg2 = VReg1;
5937       if ((NumLPads & 0xFFFF0000) != 0) {
5938         VReg2 = MRI->createVirtualRegister(TRC);
5939         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
5940                        .addReg(VReg1)
5941                        .addImm(NumLPads >> 16));
5942       }
5943 
5944       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
5945                      .addReg(NewVReg1)
5946                      .addReg(VReg2));
5947     } else {
5948       MachineConstantPool *ConstantPool = MF->getConstantPool();
5949       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
5950       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
5951 
5952       // MachineConstantPool wants an explicit alignment.
5953       unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
5954       if (Align == 0)
5955         Align = getTargetData()->getTypeAllocSize(C->getType());
5956       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
5957 
5958       unsigned VReg1 = MRI->createVirtualRegister(TRC);
5959       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
5960                      .addReg(VReg1, RegState::Define)
5961                      .addConstantPoolIndex(Idx)
5962                      .addImm(0));
5963       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
5964                      .addReg(NewVReg1)
5965                      .addReg(VReg1, RegState::Kill));
5966     }
5967 
5968     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
5969       .addMBB(TrapBB)
5970       .addImm(ARMCC::HI)
5971       .addReg(ARM::CPSR);
5972 
5973     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5974     AddDefaultCC(
5975       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
5976                      .addReg(NewVReg1)
5977                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
5978     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5979     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
5980                    .addJumpTableIndex(MJTI)
5981                    .addImm(UId));
5982 
5983     MachineMemOperand *JTMMOLd =
5984       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
5985                                MachineMemOperand::MOLoad, 4, 4);
5986     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
5987     AddDefaultPred(
5988       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
5989       .addReg(NewVReg3, RegState::Kill)
5990       .addReg(NewVReg4)
5991       .addImm(0)
5992       .addMemOperand(JTMMOLd));
5993 
5994     BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
5995       .addReg(NewVReg5, RegState::Kill)
5996       .addReg(NewVReg4)
5997       .addJumpTableIndex(MJTI)
5998       .addImm(UId);
5999   }
6000 
6001   // Add the jump table entries as successors to the MBB.
6002   MachineBasicBlock *PrevMBB = 0;
6003   for (std::vector<MachineBasicBlock*>::iterator
6004          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6005     MachineBasicBlock *CurMBB = *I;
6006     if (PrevMBB != CurMBB)
6007       DispContBB->addSuccessor(CurMBB);
6008     PrevMBB = CurMBB;
6009   }
6010 
6011   // N.B. the order the invoke BBs are processed in doesn't matter here.
6012   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6013   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6014   const unsigned *SavedRegs = RI.getCalleeSavedRegs(MF);
6015   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6016   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6017          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6018     MachineBasicBlock *BB = *I;
6019 
6020     // Remove the landing pad successor from the invoke block and replace it
6021     // with the new dispatch block.
6022     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6023                                                   BB->succ_end());
6024     while (!Successors.empty()) {
6025       MachineBasicBlock *SMBB = Successors.pop_back_val();
6026       if (SMBB->isLandingPad()) {
6027         BB->removeSuccessor(SMBB);
6028         MBBLPads.push_back(SMBB);
6029       }
6030     }
6031 
6032     BB->addSuccessor(DispatchBB);
6033 
6034     // Find the invoke call and mark all of the callee-saved registers as
6035     // 'implicit defined' so that they're spilled. This prevents code from
6036     // moving instructions to before the EH block, where they will never be
6037     // executed.
6038     for (MachineBasicBlock::reverse_iterator
6039            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6040       if (!II->isCall()) continue;
6041 
6042       DenseMap<unsigned, bool> DefRegs;
6043       for (MachineInstr::mop_iterator
6044              OI = II->operands_begin(), OE = II->operands_end();
6045            OI != OE; ++OI) {
6046         if (!OI->isReg()) continue;
6047         DefRegs[OI->getReg()] = true;
6048       }
6049 
6050       MachineInstrBuilder MIB(&*II);
6051 
6052       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6053         unsigned Reg = SavedRegs[i];
6054         if (Subtarget->isThumb2() &&
6055             !ARM::tGPRRegisterClass->contains(Reg) &&
6056             !ARM::hGPRRegisterClass->contains(Reg))
6057           continue;
6058         else if (Subtarget->isThumb1Only() &&
6059                  !ARM::tGPRRegisterClass->contains(Reg))
6060           continue;
6061         else if (!Subtarget->isThumb() &&
6062                  !ARM::GPRRegisterClass->contains(Reg))
6063           continue;
6064         if (!DefRegs[Reg])
6065           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6066       }
6067 
6068       break;
6069     }
6070   }
6071 
6072   // Mark all former landing pads as non-landing pads. The dispatch is the only
6073   // landing pad now.
6074   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6075          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6076     (*I)->setIsLandingPad(false);
6077 
6078   // The instruction is gone now.
6079   MI->eraseFromParent();
6080 
6081   return MBB;
6082 }
6083 
6084 static
6085 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6086   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6087        E = MBB->succ_end(); I != E; ++I)
6088     if (*I != Succ)
6089       return *I;
6090   llvm_unreachable("Expecting a BB with two successors!");
6091 }
6092 
6093 MachineBasicBlock *
6094 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6095                                                MachineBasicBlock *BB) const {
6096   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6097   DebugLoc dl = MI->getDebugLoc();
6098   bool isThumb2 = Subtarget->isThumb2();
6099   switch (MI->getOpcode()) {
6100   default: {
6101     MI->dump();
6102     llvm_unreachable("Unexpected instr type to insert");
6103   }
6104   // The Thumb2 pre-indexed stores have the same MI operands, they just
6105   // define them differently in the .td files from the isel patterns, so
6106   // they need pseudos.
6107   case ARM::t2STR_preidx:
6108     MI->setDesc(TII->get(ARM::t2STR_PRE));
6109     return BB;
6110   case ARM::t2STRB_preidx:
6111     MI->setDesc(TII->get(ARM::t2STRB_PRE));
6112     return BB;
6113   case ARM::t2STRH_preidx:
6114     MI->setDesc(TII->get(ARM::t2STRH_PRE));
6115     return BB;
6116 
6117   case ARM::STRi_preidx:
6118   case ARM::STRBi_preidx: {
6119     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
6120       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
6121     // Decode the offset.
6122     unsigned Offset = MI->getOperand(4).getImm();
6123     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
6124     Offset = ARM_AM::getAM2Offset(Offset);
6125     if (isSub)
6126       Offset = -Offset;
6127 
6128     MachineMemOperand *MMO = *MI->memoperands_begin();
6129     BuildMI(*BB, MI, dl, TII->get(NewOpc))
6130       .addOperand(MI->getOperand(0))  // Rn_wb
6131       .addOperand(MI->getOperand(1))  // Rt
6132       .addOperand(MI->getOperand(2))  // Rn
6133       .addImm(Offset)                 // offset (skip GPR==zero_reg)
6134       .addOperand(MI->getOperand(5))  // pred
6135       .addOperand(MI->getOperand(6))
6136       .addMemOperand(MMO);
6137     MI->eraseFromParent();
6138     return BB;
6139   }
6140   case ARM::STRr_preidx:
6141   case ARM::STRBr_preidx:
6142   case ARM::STRH_preidx: {
6143     unsigned NewOpc;
6144     switch (MI->getOpcode()) {
6145     default: llvm_unreachable("unexpected opcode!");
6146     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
6147     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
6148     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
6149     }
6150     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
6151     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
6152       MIB.addOperand(MI->getOperand(i));
6153     MI->eraseFromParent();
6154     return BB;
6155   }
6156   case ARM::ATOMIC_LOAD_ADD_I8:
6157      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6158   case ARM::ATOMIC_LOAD_ADD_I16:
6159      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6160   case ARM::ATOMIC_LOAD_ADD_I32:
6161      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6162 
6163   case ARM::ATOMIC_LOAD_AND_I8:
6164      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6165   case ARM::ATOMIC_LOAD_AND_I16:
6166      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6167   case ARM::ATOMIC_LOAD_AND_I32:
6168      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6169 
6170   case ARM::ATOMIC_LOAD_OR_I8:
6171      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6172   case ARM::ATOMIC_LOAD_OR_I16:
6173      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6174   case ARM::ATOMIC_LOAD_OR_I32:
6175      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6176 
6177   case ARM::ATOMIC_LOAD_XOR_I8:
6178      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6179   case ARM::ATOMIC_LOAD_XOR_I16:
6180      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6181   case ARM::ATOMIC_LOAD_XOR_I32:
6182      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6183 
6184   case ARM::ATOMIC_LOAD_NAND_I8:
6185      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6186   case ARM::ATOMIC_LOAD_NAND_I16:
6187      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6188   case ARM::ATOMIC_LOAD_NAND_I32:
6189      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6190 
6191   case ARM::ATOMIC_LOAD_SUB_I8:
6192      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6193   case ARM::ATOMIC_LOAD_SUB_I16:
6194      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6195   case ARM::ATOMIC_LOAD_SUB_I32:
6196      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6197 
6198   case ARM::ATOMIC_LOAD_MIN_I8:
6199      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
6200   case ARM::ATOMIC_LOAD_MIN_I16:
6201      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
6202   case ARM::ATOMIC_LOAD_MIN_I32:
6203      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
6204 
6205   case ARM::ATOMIC_LOAD_MAX_I8:
6206      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
6207   case ARM::ATOMIC_LOAD_MAX_I16:
6208      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
6209   case ARM::ATOMIC_LOAD_MAX_I32:
6210      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
6211 
6212   case ARM::ATOMIC_LOAD_UMIN_I8:
6213      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
6214   case ARM::ATOMIC_LOAD_UMIN_I16:
6215      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
6216   case ARM::ATOMIC_LOAD_UMIN_I32:
6217      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
6218 
6219   case ARM::ATOMIC_LOAD_UMAX_I8:
6220      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
6221   case ARM::ATOMIC_LOAD_UMAX_I16:
6222      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
6223   case ARM::ATOMIC_LOAD_UMAX_I32:
6224      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
6225 
6226   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
6227   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
6228   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
6229 
6230   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
6231   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
6232   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
6233 
6234 
6235   case ARM::ATOMADD6432:
6236     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
6237                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
6238                               /*NeedsCarry*/ true);
6239   case ARM::ATOMSUB6432:
6240     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6241                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6242                               /*NeedsCarry*/ true);
6243   case ARM::ATOMOR6432:
6244     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
6245                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6246   case ARM::ATOMXOR6432:
6247     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
6248                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6249   case ARM::ATOMAND6432:
6250     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
6251                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6252   case ARM::ATOMSWAP6432:
6253     return EmitAtomicBinary64(MI, BB, 0, 0, false);
6254   case ARM::ATOMCMPXCHG6432:
6255     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6256                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6257                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
6258 
6259   case ARM::tMOVCCr_pseudo: {
6260     // To "insert" a SELECT_CC instruction, we actually have to insert the
6261     // diamond control-flow pattern.  The incoming instruction knows the
6262     // destination vreg to set, the condition code register to branch on, the
6263     // true/false values to select between, and a branch opcode to use.
6264     const BasicBlock *LLVM_BB = BB->getBasicBlock();
6265     MachineFunction::iterator It = BB;
6266     ++It;
6267 
6268     //  thisMBB:
6269     //  ...
6270     //   TrueVal = ...
6271     //   cmpTY ccX, r1, r2
6272     //   bCC copy1MBB
6273     //   fallthrough --> copy0MBB
6274     MachineBasicBlock *thisMBB  = BB;
6275     MachineFunction *F = BB->getParent();
6276     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6277     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
6278     F->insert(It, copy0MBB);
6279     F->insert(It, sinkMBB);
6280 
6281     // Transfer the remainder of BB and its successor edges to sinkMBB.
6282     sinkMBB->splice(sinkMBB->begin(), BB,
6283                     llvm::next(MachineBasicBlock::iterator(MI)),
6284                     BB->end());
6285     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6286 
6287     BB->addSuccessor(copy0MBB);
6288     BB->addSuccessor(sinkMBB);
6289 
6290     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
6291       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
6292 
6293     //  copy0MBB:
6294     //   %FalseValue = ...
6295     //   # fallthrough to sinkMBB
6296     BB = copy0MBB;
6297 
6298     // Update machine-CFG edges
6299     BB->addSuccessor(sinkMBB);
6300 
6301     //  sinkMBB:
6302     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6303     //  ...
6304     BB = sinkMBB;
6305     BuildMI(*BB, BB->begin(), dl,
6306             TII->get(ARM::PHI), MI->getOperand(0).getReg())
6307       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
6308       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6309 
6310     MI->eraseFromParent();   // The pseudo instruction is gone now.
6311     return BB;
6312   }
6313 
6314   case ARM::BCCi64:
6315   case ARM::BCCZi64: {
6316     // If there is an unconditional branch to the other successor, remove it.
6317     BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
6318 
6319     // Compare both parts that make up the double comparison separately for
6320     // equality.
6321     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
6322 
6323     unsigned LHS1 = MI->getOperand(1).getReg();
6324     unsigned LHS2 = MI->getOperand(2).getReg();
6325     if (RHSisZero) {
6326       AddDefaultPred(BuildMI(BB, dl,
6327                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6328                      .addReg(LHS1).addImm(0));
6329       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6330         .addReg(LHS2).addImm(0)
6331         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6332     } else {
6333       unsigned RHS1 = MI->getOperand(3).getReg();
6334       unsigned RHS2 = MI->getOperand(4).getReg();
6335       AddDefaultPred(BuildMI(BB, dl,
6336                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6337                      .addReg(LHS1).addReg(RHS1));
6338       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6339         .addReg(LHS2).addReg(RHS2)
6340         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6341     }
6342 
6343     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
6344     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
6345     if (MI->getOperand(0).getImm() == ARMCC::NE)
6346       std::swap(destMBB, exitMBB);
6347 
6348     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6349       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
6350     if (isThumb2)
6351       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
6352     else
6353       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
6354 
6355     MI->eraseFromParent();   // The pseudo instruction is gone now.
6356     return BB;
6357   }
6358 
6359   case ARM::Int_eh_sjlj_setjmp:
6360   case ARM::Int_eh_sjlj_setjmp_nofp:
6361   case ARM::tInt_eh_sjlj_setjmp:
6362   case ARM::t2Int_eh_sjlj_setjmp:
6363   case ARM::t2Int_eh_sjlj_setjmp_nofp:
6364     EmitSjLjDispatchBlock(MI, BB);
6365     return BB;
6366 
6367   case ARM::ABS:
6368   case ARM::t2ABS: {
6369     // To insert an ABS instruction, we have to insert the
6370     // diamond control-flow pattern.  The incoming instruction knows the
6371     // source vreg to test against 0, the destination vreg to set,
6372     // the condition code register to branch on, the
6373     // true/false values to select between, and a branch opcode to use.
6374     // It transforms
6375     //     V1 = ABS V0
6376     // into
6377     //     V2 = MOVS V0
6378     //     BCC                      (branch to SinkBB if V0 >= 0)
6379     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
6380     //     SinkBB: V1 = PHI(V2, V3)
6381     const BasicBlock *LLVM_BB = BB->getBasicBlock();
6382     MachineFunction::iterator BBI = BB;
6383     ++BBI;
6384     MachineFunction *Fn = BB->getParent();
6385     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
6386     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
6387     Fn->insert(BBI, RSBBB);
6388     Fn->insert(BBI, SinkBB);
6389 
6390     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
6391     unsigned int ABSDstReg = MI->getOperand(0).getReg();
6392     bool isThumb2 = Subtarget->isThumb2();
6393     MachineRegisterInfo &MRI = Fn->getRegInfo();
6394     // In Thumb mode S must not be specified if source register is the SP or
6395     // PC and if destination register is the SP, so restrict register class
6396     unsigned NewMovDstReg = MRI.createVirtualRegister(
6397       isThumb2 ? ARM::rGPRRegisterClass : ARM::GPRRegisterClass);
6398     unsigned NewRsbDstReg = MRI.createVirtualRegister(
6399       isThumb2 ? ARM::rGPRRegisterClass : ARM::GPRRegisterClass);
6400 
6401     // Transfer the remainder of BB and its successor edges to sinkMBB.
6402     SinkBB->splice(SinkBB->begin(), BB,
6403       llvm::next(MachineBasicBlock::iterator(MI)),
6404       BB->end());
6405     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
6406 
6407     BB->addSuccessor(RSBBB);
6408     BB->addSuccessor(SinkBB);
6409 
6410     // fall through to SinkMBB
6411     RSBBB->addSuccessor(SinkBB);
6412 
6413     // insert a movs at the end of BB
6414     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVr : ARM::MOVr),
6415       NewMovDstReg)
6416       .addReg(ABSSrcReg, RegState::Kill)
6417       .addImm((unsigned)ARMCC::AL).addReg(0)
6418       .addReg(ARM::CPSR, RegState::Define);
6419 
6420     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
6421     BuildMI(BB, dl,
6422       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
6423       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
6424 
6425     // insert rsbri in RSBBB
6426     // Note: BCC and rsbri will be converted into predicated rsbmi
6427     // by if-conversion pass
6428     BuildMI(*RSBBB, RSBBB->begin(), dl,
6429       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
6430       .addReg(NewMovDstReg, RegState::Kill)
6431       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
6432 
6433     // insert PHI in SinkBB,
6434     // reuse ABSDstReg to not change uses of ABS instruction
6435     BuildMI(*SinkBB, SinkBB->begin(), dl,
6436       TII->get(ARM::PHI), ABSDstReg)
6437       .addReg(NewRsbDstReg).addMBB(RSBBB)
6438       .addReg(NewMovDstReg).addMBB(BB);
6439 
6440     // remove ABS instruction
6441     MI->eraseFromParent();
6442 
6443     // return last added BB
6444     return SinkBB;
6445   }
6446   }
6447 }
6448 
6449 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
6450                                                       SDNode *Node) const {
6451   if (!MI->hasPostISelHook()) {
6452     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
6453            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
6454     return;
6455   }
6456 
6457   const MCInstrDesc *MCID = &MI->getDesc();
6458   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
6459   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
6460   // operand is still set to noreg. If needed, set the optional operand's
6461   // register to CPSR, and remove the redundant implicit def.
6462   //
6463   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
6464 
6465   // Rename pseudo opcodes.
6466   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
6467   if (NewOpc) {
6468     const ARMBaseInstrInfo *TII =
6469       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
6470     MCID = &TII->get(NewOpc);
6471 
6472     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
6473            "converted opcode should be the same except for cc_out");
6474 
6475     MI->setDesc(*MCID);
6476 
6477     // Add the optional cc_out operand
6478     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
6479   }
6480   unsigned ccOutIdx = MCID->getNumOperands() - 1;
6481 
6482   // Any ARM instruction that sets the 's' bit should specify an optional
6483   // "cc_out" operand in the last operand position.
6484   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
6485     assert(!NewOpc && "Optional cc_out operand required");
6486     return;
6487   }
6488   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
6489   // since we already have an optional CPSR def.
6490   bool definesCPSR = false;
6491   bool deadCPSR = false;
6492   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
6493        i != e; ++i) {
6494     const MachineOperand &MO = MI->getOperand(i);
6495     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
6496       definesCPSR = true;
6497       if (MO.isDead())
6498         deadCPSR = true;
6499       MI->RemoveOperand(i);
6500       break;
6501     }
6502   }
6503   if (!definesCPSR) {
6504     assert(!NewOpc && "Optional cc_out operand required");
6505     return;
6506   }
6507   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
6508   if (deadCPSR) {
6509     assert(!MI->getOperand(ccOutIdx).getReg() &&
6510            "expect uninitialized optional cc_out operand");
6511     return;
6512   }
6513 
6514   // If this instruction was defined with an optional CPSR def and its dag node
6515   // had a live implicit CPSR def, then activate the optional CPSR def.
6516   MachineOperand &MO = MI->getOperand(ccOutIdx);
6517   MO.setReg(ARM::CPSR);
6518   MO.setIsDef(true);
6519 }
6520 
6521 //===----------------------------------------------------------------------===//
6522 //                           ARM Optimization Hooks
6523 //===----------------------------------------------------------------------===//
6524 
6525 static
6526 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
6527                             TargetLowering::DAGCombinerInfo &DCI) {
6528   SelectionDAG &DAG = DCI.DAG;
6529   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6530   EVT VT = N->getValueType(0);
6531   unsigned Opc = N->getOpcode();
6532   bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
6533   SDValue LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
6534   SDValue RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
6535   ISD::CondCode CC = ISD::SETCC_INVALID;
6536 
6537   if (isSlctCC) {
6538     CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
6539   } else {
6540     SDValue CCOp = Slct.getOperand(0);
6541     if (CCOp.getOpcode() == ISD::SETCC)
6542       CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
6543   }
6544 
6545   bool DoXform = false;
6546   bool InvCC = false;
6547   assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
6548           "Bad input!");
6549 
6550   if (LHS.getOpcode() == ISD::Constant &&
6551       cast<ConstantSDNode>(LHS)->isNullValue()) {
6552     DoXform = true;
6553   } else if (CC != ISD::SETCC_INVALID &&
6554              RHS.getOpcode() == ISD::Constant &&
6555              cast<ConstantSDNode>(RHS)->isNullValue()) {
6556     std::swap(LHS, RHS);
6557     SDValue Op0 = Slct.getOperand(0);
6558     EVT OpVT = isSlctCC ? Op0.getValueType() :
6559                           Op0.getOperand(0).getValueType();
6560     bool isInt = OpVT.isInteger();
6561     CC = ISD::getSetCCInverse(CC, isInt);
6562 
6563     if (!TLI.isCondCodeLegal(CC, OpVT))
6564       return SDValue();         // Inverse operator isn't legal.
6565 
6566     DoXform = true;
6567     InvCC = true;
6568   }
6569 
6570   if (DoXform) {
6571     SDValue Result = DAG.getNode(Opc, RHS.getDebugLoc(), VT, OtherOp, RHS);
6572     if (isSlctCC)
6573       return DAG.getSelectCC(N->getDebugLoc(), OtherOp, Result,
6574                              Slct.getOperand(0), Slct.getOperand(1), CC);
6575     SDValue CCOp = Slct.getOperand(0);
6576     if (InvCC)
6577       CCOp = DAG.getSetCC(Slct.getDebugLoc(), CCOp.getValueType(),
6578                           CCOp.getOperand(0), CCOp.getOperand(1), CC);
6579     return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
6580                        CCOp, OtherOp, Result);
6581   }
6582   return SDValue();
6583 }
6584 
6585 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
6586 // (only after legalization).
6587 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
6588                                  TargetLowering::DAGCombinerInfo &DCI,
6589                                  const ARMSubtarget *Subtarget) {
6590 
6591   // Only perform optimization if after legalize, and if NEON is available. We
6592   // also expected both operands to be BUILD_VECTORs.
6593   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
6594       || N0.getOpcode() != ISD::BUILD_VECTOR
6595       || N1.getOpcode() != ISD::BUILD_VECTOR)
6596     return SDValue();
6597 
6598   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
6599   EVT VT = N->getValueType(0);
6600   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
6601     return SDValue();
6602 
6603   // Check that the vector operands are of the right form.
6604   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
6605   // operands, where N is the size of the formed vector.
6606   // Each EXTRACT_VECTOR should have the same input vector and odd or even
6607   // index such that we have a pair wise add pattern.
6608 
6609   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
6610   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6611     return SDValue();
6612   SDValue Vec = N0->getOperand(0)->getOperand(0);
6613   SDNode *V = Vec.getNode();
6614   unsigned nextIndex = 0;
6615 
6616   // For each operands to the ADD which are BUILD_VECTORs,
6617   // check to see if each of their operands are an EXTRACT_VECTOR with
6618   // the same vector and appropriate index.
6619   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
6620     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
6621         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
6622 
6623       SDValue ExtVec0 = N0->getOperand(i);
6624       SDValue ExtVec1 = N1->getOperand(i);
6625 
6626       // First operand is the vector, verify its the same.
6627       if (V != ExtVec0->getOperand(0).getNode() ||
6628           V != ExtVec1->getOperand(0).getNode())
6629         return SDValue();
6630 
6631       // Second is the constant, verify its correct.
6632       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
6633       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
6634 
6635       // For the constant, we want to see all the even or all the odd.
6636       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
6637           || C1->getZExtValue() != nextIndex+1)
6638         return SDValue();
6639 
6640       // Increment index.
6641       nextIndex+=2;
6642     } else
6643       return SDValue();
6644   }
6645 
6646   // Create VPADDL node.
6647   SelectionDAG &DAG = DCI.DAG;
6648   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6649 
6650   // Build operand list.
6651   SmallVector<SDValue, 8> Ops;
6652   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
6653                                 TLI.getPointerTy()));
6654 
6655   // Input is the vector.
6656   Ops.push_back(Vec);
6657 
6658   // Get widened type and narrowed type.
6659   MVT widenType;
6660   unsigned numElem = VT.getVectorNumElements();
6661   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
6662     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
6663     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
6664     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
6665     default:
6666       assert(0 && "Invalid vector element type for padd optimization.");
6667   }
6668 
6669   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
6670                             widenType, &Ops[0], Ops.size());
6671   return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
6672 }
6673 
6674 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
6675 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
6676 /// called with the default operands, and if that fails, with commuted
6677 /// operands.
6678 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
6679                                           TargetLowering::DAGCombinerInfo &DCI,
6680                                           const ARMSubtarget *Subtarget){
6681 
6682   // Attempt to create vpaddl for this add.
6683   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
6684   if (Result.getNode())
6685     return Result;
6686 
6687   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
6688   if (N0.getOpcode() == ISD::SELECT && N0.getNode()->hasOneUse()) {
6689     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
6690     if (Result.getNode()) return Result;
6691   }
6692   return SDValue();
6693 }
6694 
6695 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
6696 ///
6697 static SDValue PerformADDCombine(SDNode *N,
6698                                  TargetLowering::DAGCombinerInfo &DCI,
6699                                  const ARMSubtarget *Subtarget) {
6700   SDValue N0 = N->getOperand(0);
6701   SDValue N1 = N->getOperand(1);
6702 
6703   // First try with the default operand order.
6704   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
6705   if (Result.getNode())
6706     return Result;
6707 
6708   // If that didn't work, try again with the operands commuted.
6709   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
6710 }
6711 
6712 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
6713 ///
6714 static SDValue PerformSUBCombine(SDNode *N,
6715                                  TargetLowering::DAGCombinerInfo &DCI) {
6716   SDValue N0 = N->getOperand(0);
6717   SDValue N1 = N->getOperand(1);
6718 
6719   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
6720   if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
6721     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
6722     if (Result.getNode()) return Result;
6723   }
6724 
6725   return SDValue();
6726 }
6727 
6728 /// PerformVMULCombine
6729 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
6730 /// special multiplier accumulator forwarding.
6731 ///   vmul d3, d0, d2
6732 ///   vmla d3, d1, d2
6733 /// is faster than
6734 ///   vadd d3, d0, d1
6735 ///   vmul d3, d3, d2
6736 static SDValue PerformVMULCombine(SDNode *N,
6737                                   TargetLowering::DAGCombinerInfo &DCI,
6738                                   const ARMSubtarget *Subtarget) {
6739   if (!Subtarget->hasVMLxForwarding())
6740     return SDValue();
6741 
6742   SelectionDAG &DAG = DCI.DAG;
6743   SDValue N0 = N->getOperand(0);
6744   SDValue N1 = N->getOperand(1);
6745   unsigned Opcode = N0.getOpcode();
6746   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
6747       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
6748     Opcode = N1.getOpcode();
6749     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
6750         Opcode != ISD::FADD && Opcode != ISD::FSUB)
6751       return SDValue();
6752     std::swap(N0, N1);
6753   }
6754 
6755   EVT VT = N->getValueType(0);
6756   DebugLoc DL = N->getDebugLoc();
6757   SDValue N00 = N0->getOperand(0);
6758   SDValue N01 = N0->getOperand(1);
6759   return DAG.getNode(Opcode, DL, VT,
6760                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
6761                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
6762 }
6763 
6764 static SDValue PerformMULCombine(SDNode *N,
6765                                  TargetLowering::DAGCombinerInfo &DCI,
6766                                  const ARMSubtarget *Subtarget) {
6767   SelectionDAG &DAG = DCI.DAG;
6768 
6769   if (Subtarget->isThumb1Only())
6770     return SDValue();
6771 
6772   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
6773     return SDValue();
6774 
6775   EVT VT = N->getValueType(0);
6776   if (VT.is64BitVector() || VT.is128BitVector())
6777     return PerformVMULCombine(N, DCI, Subtarget);
6778   if (VT != MVT::i32)
6779     return SDValue();
6780 
6781   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
6782   if (!C)
6783     return SDValue();
6784 
6785   uint64_t MulAmt = C->getZExtValue();
6786   unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
6787   ShiftAmt = ShiftAmt & (32 - 1);
6788   SDValue V = N->getOperand(0);
6789   DebugLoc DL = N->getDebugLoc();
6790 
6791   SDValue Res;
6792   MulAmt >>= ShiftAmt;
6793   if (isPowerOf2_32(MulAmt - 1)) {
6794     // (mul x, 2^N + 1) => (add (shl x, N), x)
6795     Res = DAG.getNode(ISD::ADD, DL, VT,
6796                       V, DAG.getNode(ISD::SHL, DL, VT,
6797                                      V, DAG.getConstant(Log2_32(MulAmt-1),
6798                                                         MVT::i32)));
6799   } else if (isPowerOf2_32(MulAmt + 1)) {
6800     // (mul x, 2^N - 1) => (sub (shl x, N), x)
6801     Res = DAG.getNode(ISD::SUB, DL, VT,
6802                       DAG.getNode(ISD::SHL, DL, VT,
6803                                   V, DAG.getConstant(Log2_32(MulAmt+1),
6804                                                      MVT::i32)),
6805                                                      V);
6806   } else
6807     return SDValue();
6808 
6809   if (ShiftAmt != 0)
6810     Res = DAG.getNode(ISD::SHL, DL, VT, Res,
6811                       DAG.getConstant(ShiftAmt, MVT::i32));
6812 
6813   // Do not add new nodes to DAG combiner worklist.
6814   DCI.CombineTo(N, Res, false);
6815   return SDValue();
6816 }
6817 
6818 static SDValue PerformANDCombine(SDNode *N,
6819                                 TargetLowering::DAGCombinerInfo &DCI) {
6820 
6821   // Attempt to use immediate-form VBIC
6822   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
6823   DebugLoc dl = N->getDebugLoc();
6824   EVT VT = N->getValueType(0);
6825   SelectionDAG &DAG = DCI.DAG;
6826 
6827   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
6828     return SDValue();
6829 
6830   APInt SplatBits, SplatUndef;
6831   unsigned SplatBitSize;
6832   bool HasAnyUndefs;
6833   if (BVN &&
6834       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6835     if (SplatBitSize <= 64) {
6836       EVT VbicVT;
6837       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
6838                                       SplatUndef.getZExtValue(), SplatBitSize,
6839                                       DAG, VbicVT, VT.is128BitVector(),
6840                                       OtherModImm);
6841       if (Val.getNode()) {
6842         SDValue Input =
6843           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
6844         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
6845         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
6846       }
6847     }
6848   }
6849 
6850   return SDValue();
6851 }
6852 
6853 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
6854 static SDValue PerformORCombine(SDNode *N,
6855                                 TargetLowering::DAGCombinerInfo &DCI,
6856                                 const ARMSubtarget *Subtarget) {
6857   // Attempt to use immediate-form VORR
6858   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
6859   DebugLoc dl = N->getDebugLoc();
6860   EVT VT = N->getValueType(0);
6861   SelectionDAG &DAG = DCI.DAG;
6862 
6863   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
6864     return SDValue();
6865 
6866   APInt SplatBits, SplatUndef;
6867   unsigned SplatBitSize;
6868   bool HasAnyUndefs;
6869   if (BVN && Subtarget->hasNEON() &&
6870       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6871     if (SplatBitSize <= 64) {
6872       EVT VorrVT;
6873       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
6874                                       SplatUndef.getZExtValue(), SplatBitSize,
6875                                       DAG, VorrVT, VT.is128BitVector(),
6876                                       OtherModImm);
6877       if (Val.getNode()) {
6878         SDValue Input =
6879           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
6880         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
6881         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
6882       }
6883     }
6884   }
6885 
6886   SDValue N0 = N->getOperand(0);
6887   if (N0.getOpcode() != ISD::AND)
6888     return SDValue();
6889   SDValue N1 = N->getOperand(1);
6890 
6891   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
6892   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
6893       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
6894     APInt SplatUndef;
6895     unsigned SplatBitSize;
6896     bool HasAnyUndefs;
6897 
6898     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
6899     APInt SplatBits0;
6900     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
6901                                   HasAnyUndefs) && !HasAnyUndefs) {
6902       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
6903       APInt SplatBits1;
6904       if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
6905                                     HasAnyUndefs) && !HasAnyUndefs &&
6906           SplatBits0 == ~SplatBits1) {
6907         // Canonicalize the vector type to make instruction selection simpler.
6908         EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
6909         SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
6910                                      N0->getOperand(1), N0->getOperand(0),
6911                                      N1->getOperand(0));
6912         return DAG.getNode(ISD::BITCAST, dl, VT, Result);
6913       }
6914     }
6915   }
6916 
6917   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
6918   // reasonable.
6919 
6920   // BFI is only available on V6T2+
6921   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
6922     return SDValue();
6923 
6924   DebugLoc DL = N->getDebugLoc();
6925   // 1) or (and A, mask), val => ARMbfi A, val, mask
6926   //      iff (val & mask) == val
6927   //
6928   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
6929   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
6930   //          && mask == ~mask2
6931   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
6932   //          && ~mask == mask2
6933   //  (i.e., copy a bitfield value into another bitfield of the same width)
6934 
6935   if (VT != MVT::i32)
6936     return SDValue();
6937 
6938   SDValue N00 = N0.getOperand(0);
6939 
6940   // The value and the mask need to be constants so we can verify this is
6941   // actually a bitfield set. If the mask is 0xffff, we can do better
6942   // via a movt instruction, so don't use BFI in that case.
6943   SDValue MaskOp = N0.getOperand(1);
6944   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
6945   if (!MaskC)
6946     return SDValue();
6947   unsigned Mask = MaskC->getZExtValue();
6948   if (Mask == 0xffff)
6949     return SDValue();
6950   SDValue Res;
6951   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
6952   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
6953   if (N1C) {
6954     unsigned Val = N1C->getZExtValue();
6955     if ((Val & ~Mask) != Val)
6956       return SDValue();
6957 
6958     if (ARM::isBitFieldInvertedMask(Mask)) {
6959       Val >>= CountTrailingZeros_32(~Mask);
6960 
6961       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
6962                         DAG.getConstant(Val, MVT::i32),
6963                         DAG.getConstant(Mask, MVT::i32));
6964 
6965       // Do not add new nodes to DAG combiner worklist.
6966       DCI.CombineTo(N, Res, false);
6967       return SDValue();
6968     }
6969   } else if (N1.getOpcode() == ISD::AND) {
6970     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
6971     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
6972     if (!N11C)
6973       return SDValue();
6974     unsigned Mask2 = N11C->getZExtValue();
6975 
6976     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
6977     // as is to match.
6978     if (ARM::isBitFieldInvertedMask(Mask) &&
6979         (Mask == ~Mask2)) {
6980       // The pack halfword instruction works better for masks that fit it,
6981       // so use that when it's available.
6982       if (Subtarget->hasT2ExtractPack() &&
6983           (Mask == 0xffff || Mask == 0xffff0000))
6984         return SDValue();
6985       // 2a
6986       unsigned amt = CountTrailingZeros_32(Mask2);
6987       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
6988                         DAG.getConstant(amt, MVT::i32));
6989       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
6990                         DAG.getConstant(Mask, MVT::i32));
6991       // Do not add new nodes to DAG combiner worklist.
6992       DCI.CombineTo(N, Res, false);
6993       return SDValue();
6994     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
6995                (~Mask == Mask2)) {
6996       // The pack halfword instruction works better for masks that fit it,
6997       // so use that when it's available.
6998       if (Subtarget->hasT2ExtractPack() &&
6999           (Mask2 == 0xffff || Mask2 == 0xffff0000))
7000         return SDValue();
7001       // 2b
7002       unsigned lsb = CountTrailingZeros_32(Mask);
7003       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
7004                         DAG.getConstant(lsb, MVT::i32));
7005       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
7006                         DAG.getConstant(Mask2, MVT::i32));
7007       // Do not add new nodes to DAG combiner worklist.
7008       DCI.CombineTo(N, Res, false);
7009       return SDValue();
7010     }
7011   }
7012 
7013   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
7014       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
7015       ARM::isBitFieldInvertedMask(~Mask)) {
7016     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
7017     // where lsb(mask) == #shamt and masked bits of B are known zero.
7018     SDValue ShAmt = N00.getOperand(1);
7019     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7020     unsigned LSB = CountTrailingZeros_32(Mask);
7021     if (ShAmtC != LSB)
7022       return SDValue();
7023 
7024     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
7025                       DAG.getConstant(~Mask, MVT::i32));
7026 
7027     // Do not add new nodes to DAG combiner worklist.
7028     DCI.CombineTo(N, Res, false);
7029   }
7030 
7031   return SDValue();
7032 }
7033 
7034 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
7035 /// the bits being cleared by the AND are not demanded by the BFI.
7036 static SDValue PerformBFICombine(SDNode *N,
7037                                  TargetLowering::DAGCombinerInfo &DCI) {
7038   SDValue N1 = N->getOperand(1);
7039   if (N1.getOpcode() == ISD::AND) {
7040     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7041     if (!N11C)
7042       return SDValue();
7043     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
7044     unsigned LSB = CountTrailingZeros_32(~InvMask);
7045     unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
7046     unsigned Mask = (1 << Width)-1;
7047     unsigned Mask2 = N11C->getZExtValue();
7048     if ((Mask & (~Mask2)) == 0)
7049       return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
7050                              N->getOperand(0), N1.getOperand(0),
7051                              N->getOperand(2));
7052   }
7053   return SDValue();
7054 }
7055 
7056 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
7057 /// ARMISD::VMOVRRD.
7058 static SDValue PerformVMOVRRDCombine(SDNode *N,
7059                                      TargetLowering::DAGCombinerInfo &DCI) {
7060   // vmovrrd(vmovdrr x, y) -> x,y
7061   SDValue InDouble = N->getOperand(0);
7062   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
7063     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
7064 
7065   // vmovrrd(load f64) -> (load i32), (load i32)
7066   SDNode *InNode = InDouble.getNode();
7067   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
7068       InNode->getValueType(0) == MVT::f64 &&
7069       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
7070       !cast<LoadSDNode>(InNode)->isVolatile()) {
7071     // TODO: Should this be done for non-FrameIndex operands?
7072     LoadSDNode *LD = cast<LoadSDNode>(InNode);
7073 
7074     SelectionDAG &DAG = DCI.DAG;
7075     DebugLoc DL = LD->getDebugLoc();
7076     SDValue BasePtr = LD->getBasePtr();
7077     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
7078                                  LD->getPointerInfo(), LD->isVolatile(),
7079                                  LD->isNonTemporal(), LD->isInvariant(),
7080                                  LD->getAlignment());
7081 
7082     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
7083                                     DAG.getConstant(4, MVT::i32));
7084     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
7085                                  LD->getPointerInfo(), LD->isVolatile(),
7086                                  LD->isNonTemporal(), LD->isInvariant(),
7087                                  std::min(4U, LD->getAlignment() / 2));
7088 
7089     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
7090     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
7091     DCI.RemoveFromWorklist(LD);
7092     DAG.DeleteNode(LD);
7093     return Result;
7094   }
7095 
7096   return SDValue();
7097 }
7098 
7099 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
7100 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
7101 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
7102   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
7103   SDValue Op0 = N->getOperand(0);
7104   SDValue Op1 = N->getOperand(1);
7105   if (Op0.getOpcode() == ISD::BITCAST)
7106     Op0 = Op0.getOperand(0);
7107   if (Op1.getOpcode() == ISD::BITCAST)
7108     Op1 = Op1.getOperand(0);
7109   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
7110       Op0.getNode() == Op1.getNode() &&
7111       Op0.getResNo() == 0 && Op1.getResNo() == 1)
7112     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
7113                        N->getValueType(0), Op0.getOperand(0));
7114   return SDValue();
7115 }
7116 
7117 /// PerformSTORECombine - Target-specific dag combine xforms for
7118 /// ISD::STORE.
7119 static SDValue PerformSTORECombine(SDNode *N,
7120                                    TargetLowering::DAGCombinerInfo &DCI) {
7121   // Bitcast an i64 store extracted from a vector to f64.
7122   // Otherwise, the i64 value will be legalized to a pair of i32 values.
7123   StoreSDNode *St = cast<StoreSDNode>(N);
7124   SDValue StVal = St->getValue();
7125   if (!ISD::isNormalStore(St) || St->isVolatile())
7126     return SDValue();
7127 
7128   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
7129       StVal.getNode()->hasOneUse() && !St->isVolatile()) {
7130     SelectionDAG  &DAG = DCI.DAG;
7131     DebugLoc DL = St->getDebugLoc();
7132     SDValue BasePtr = St->getBasePtr();
7133     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
7134                                   StVal.getNode()->getOperand(0), BasePtr,
7135                                   St->getPointerInfo(), St->isVolatile(),
7136                                   St->isNonTemporal(), St->getAlignment());
7137 
7138     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
7139                                     DAG.getConstant(4, MVT::i32));
7140     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
7141                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
7142                         St->isNonTemporal(),
7143                         std::min(4U, St->getAlignment() / 2));
7144   }
7145 
7146   if (StVal.getValueType() != MVT::i64 ||
7147       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7148     return SDValue();
7149 
7150   SelectionDAG &DAG = DCI.DAG;
7151   DebugLoc dl = StVal.getDebugLoc();
7152   SDValue IntVec = StVal.getOperand(0);
7153   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
7154                                  IntVec.getValueType().getVectorNumElements());
7155   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
7156   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7157                                Vec, StVal.getOperand(1));
7158   dl = N->getDebugLoc();
7159   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
7160   // Make the DAGCombiner fold the bitcasts.
7161   DCI.AddToWorklist(Vec.getNode());
7162   DCI.AddToWorklist(ExtElt.getNode());
7163   DCI.AddToWorklist(V.getNode());
7164   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
7165                       St->getPointerInfo(), St->isVolatile(),
7166                       St->isNonTemporal(), St->getAlignment(),
7167                       St->getTBAAInfo());
7168 }
7169 
7170 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
7171 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
7172 /// i64 vector to have f64 elements, since the value can then be loaded
7173 /// directly into a VFP register.
7174 static bool hasNormalLoadOperand(SDNode *N) {
7175   unsigned NumElts = N->getValueType(0).getVectorNumElements();
7176   for (unsigned i = 0; i < NumElts; ++i) {
7177     SDNode *Elt = N->getOperand(i).getNode();
7178     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
7179       return true;
7180   }
7181   return false;
7182 }
7183 
7184 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
7185 /// ISD::BUILD_VECTOR.
7186 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
7187                                           TargetLowering::DAGCombinerInfo &DCI){
7188   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
7189   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
7190   // into a pair of GPRs, which is fine when the value is used as a scalar,
7191   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
7192   SelectionDAG &DAG = DCI.DAG;
7193   if (N->getNumOperands() == 2) {
7194     SDValue RV = PerformVMOVDRRCombine(N, DAG);
7195     if (RV.getNode())
7196       return RV;
7197   }
7198 
7199   // Load i64 elements as f64 values so that type legalization does not split
7200   // them up into i32 values.
7201   EVT VT = N->getValueType(0);
7202   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
7203     return SDValue();
7204   DebugLoc dl = N->getDebugLoc();
7205   SmallVector<SDValue, 8> Ops;
7206   unsigned NumElts = VT.getVectorNumElements();
7207   for (unsigned i = 0; i < NumElts; ++i) {
7208     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
7209     Ops.push_back(V);
7210     // Make the DAGCombiner fold the bitcast.
7211     DCI.AddToWorklist(V.getNode());
7212   }
7213   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
7214   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
7215   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
7216 }
7217 
7218 /// PerformInsertEltCombine - Target-specific dag combine xforms for
7219 /// ISD::INSERT_VECTOR_ELT.
7220 static SDValue PerformInsertEltCombine(SDNode *N,
7221                                        TargetLowering::DAGCombinerInfo &DCI) {
7222   // Bitcast an i64 load inserted into a vector to f64.
7223   // Otherwise, the i64 value will be legalized to a pair of i32 values.
7224   EVT VT = N->getValueType(0);
7225   SDNode *Elt = N->getOperand(1).getNode();
7226   if (VT.getVectorElementType() != MVT::i64 ||
7227       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
7228     return SDValue();
7229 
7230   SelectionDAG &DAG = DCI.DAG;
7231   DebugLoc dl = N->getDebugLoc();
7232   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
7233                                  VT.getVectorNumElements());
7234   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
7235   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
7236   // Make the DAGCombiner fold the bitcasts.
7237   DCI.AddToWorklist(Vec.getNode());
7238   DCI.AddToWorklist(V.getNode());
7239   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
7240                                Vec, V, N->getOperand(2));
7241   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
7242 }
7243 
7244 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
7245 /// ISD::VECTOR_SHUFFLE.
7246 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
7247   // The LLVM shufflevector instruction does not require the shuffle mask
7248   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
7249   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
7250   // operands do not match the mask length, they are extended by concatenating
7251   // them with undef vectors.  That is probably the right thing for other
7252   // targets, but for NEON it is better to concatenate two double-register
7253   // size vector operands into a single quad-register size vector.  Do that
7254   // transformation here:
7255   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
7256   //   shuffle(concat(v1, v2), undef)
7257   SDValue Op0 = N->getOperand(0);
7258   SDValue Op1 = N->getOperand(1);
7259   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
7260       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
7261       Op0.getNumOperands() != 2 ||
7262       Op1.getNumOperands() != 2)
7263     return SDValue();
7264   SDValue Concat0Op1 = Op0.getOperand(1);
7265   SDValue Concat1Op1 = Op1.getOperand(1);
7266   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
7267       Concat1Op1.getOpcode() != ISD::UNDEF)
7268     return SDValue();
7269   // Skip the transformation if any of the types are illegal.
7270   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7271   EVT VT = N->getValueType(0);
7272   if (!TLI.isTypeLegal(VT) ||
7273       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
7274       !TLI.isTypeLegal(Concat1Op1.getValueType()))
7275     return SDValue();
7276 
7277   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
7278                                   Op0.getOperand(0), Op1.getOperand(0));
7279   // Translate the shuffle mask.
7280   SmallVector<int, 16> NewMask;
7281   unsigned NumElts = VT.getVectorNumElements();
7282   unsigned HalfElts = NumElts/2;
7283   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
7284   for (unsigned n = 0; n < NumElts; ++n) {
7285     int MaskElt = SVN->getMaskElt(n);
7286     int NewElt = -1;
7287     if (MaskElt < (int)HalfElts)
7288       NewElt = MaskElt;
7289     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
7290       NewElt = HalfElts + MaskElt - NumElts;
7291     NewMask.push_back(NewElt);
7292   }
7293   return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
7294                               DAG.getUNDEF(VT), NewMask.data());
7295 }
7296 
7297 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
7298 /// NEON load/store intrinsics to merge base address updates.
7299 static SDValue CombineBaseUpdate(SDNode *N,
7300                                  TargetLowering::DAGCombinerInfo &DCI) {
7301   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7302     return SDValue();
7303 
7304   SelectionDAG &DAG = DCI.DAG;
7305   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
7306                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
7307   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
7308   SDValue Addr = N->getOperand(AddrOpIdx);
7309 
7310   // Search for a use of the address operand that is an increment.
7311   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
7312          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
7313     SDNode *User = *UI;
7314     if (User->getOpcode() != ISD::ADD ||
7315         UI.getUse().getResNo() != Addr.getResNo())
7316       continue;
7317 
7318     // Check that the add is independent of the load/store.  Otherwise, folding
7319     // it would create a cycle.
7320     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
7321       continue;
7322 
7323     // Find the new opcode for the updating load/store.
7324     bool isLoad = true;
7325     bool isLaneOp = false;
7326     unsigned NewOpc = 0;
7327     unsigned NumVecs = 0;
7328     if (isIntrinsic) {
7329       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7330       switch (IntNo) {
7331       default: assert(0 && "unexpected intrinsic for Neon base update");
7332       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
7333         NumVecs = 1; break;
7334       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
7335         NumVecs = 2; break;
7336       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
7337         NumVecs = 3; break;
7338       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
7339         NumVecs = 4; break;
7340       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
7341         NumVecs = 2; isLaneOp = true; break;
7342       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
7343         NumVecs = 3; isLaneOp = true; break;
7344       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
7345         NumVecs = 4; isLaneOp = true; break;
7346       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
7347         NumVecs = 1; isLoad = false; break;
7348       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
7349         NumVecs = 2; isLoad = false; break;
7350       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
7351         NumVecs = 3; isLoad = false; break;
7352       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
7353         NumVecs = 4; isLoad = false; break;
7354       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
7355         NumVecs = 2; isLoad = false; isLaneOp = true; break;
7356       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
7357         NumVecs = 3; isLoad = false; isLaneOp = true; break;
7358       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
7359         NumVecs = 4; isLoad = false; isLaneOp = true; break;
7360       }
7361     } else {
7362       isLaneOp = true;
7363       switch (N->getOpcode()) {
7364       default: assert(0 && "unexpected opcode for Neon base update");
7365       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
7366       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
7367       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
7368       }
7369     }
7370 
7371     // Find the size of memory referenced by the load/store.
7372     EVT VecTy;
7373     if (isLoad)
7374       VecTy = N->getValueType(0);
7375     else
7376       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
7377     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
7378     if (isLaneOp)
7379       NumBytes /= VecTy.getVectorNumElements();
7380 
7381     // If the increment is a constant, it must match the memory ref size.
7382     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
7383     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
7384       uint64_t IncVal = CInc->getZExtValue();
7385       if (IncVal != NumBytes)
7386         continue;
7387     } else if (NumBytes >= 3 * 16) {
7388       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
7389       // separate instructions that make it harder to use a non-constant update.
7390       continue;
7391     }
7392 
7393     // Create the new updating load/store node.
7394     EVT Tys[6];
7395     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
7396     unsigned n;
7397     for (n = 0; n < NumResultVecs; ++n)
7398       Tys[n] = VecTy;
7399     Tys[n++] = MVT::i32;
7400     Tys[n] = MVT::Other;
7401     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
7402     SmallVector<SDValue, 8> Ops;
7403     Ops.push_back(N->getOperand(0)); // incoming chain
7404     Ops.push_back(N->getOperand(AddrOpIdx));
7405     Ops.push_back(Inc);
7406     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
7407       Ops.push_back(N->getOperand(i));
7408     }
7409     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
7410     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
7411                                            Ops.data(), Ops.size(),
7412                                            MemInt->getMemoryVT(),
7413                                            MemInt->getMemOperand());
7414 
7415     // Update the uses.
7416     std::vector<SDValue> NewResults;
7417     for (unsigned i = 0; i < NumResultVecs; ++i) {
7418       NewResults.push_back(SDValue(UpdN.getNode(), i));
7419     }
7420     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
7421     DCI.CombineTo(N, NewResults);
7422     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
7423 
7424     break;
7425   }
7426   return SDValue();
7427 }
7428 
7429 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
7430 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
7431 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
7432 /// return true.
7433 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
7434   SelectionDAG &DAG = DCI.DAG;
7435   EVT VT = N->getValueType(0);
7436   // vldN-dup instructions only support 64-bit vectors for N > 1.
7437   if (!VT.is64BitVector())
7438     return false;
7439 
7440   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
7441   SDNode *VLD = N->getOperand(0).getNode();
7442   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
7443     return false;
7444   unsigned NumVecs = 0;
7445   unsigned NewOpc = 0;
7446   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
7447   if (IntNo == Intrinsic::arm_neon_vld2lane) {
7448     NumVecs = 2;
7449     NewOpc = ARMISD::VLD2DUP;
7450   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
7451     NumVecs = 3;
7452     NewOpc = ARMISD::VLD3DUP;
7453   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
7454     NumVecs = 4;
7455     NewOpc = ARMISD::VLD4DUP;
7456   } else {
7457     return false;
7458   }
7459 
7460   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
7461   // numbers match the load.
7462   unsigned VLDLaneNo =
7463     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
7464   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
7465        UI != UE; ++UI) {
7466     // Ignore uses of the chain result.
7467     if (UI.getUse().getResNo() == NumVecs)
7468       continue;
7469     SDNode *User = *UI;
7470     if (User->getOpcode() != ARMISD::VDUPLANE ||
7471         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
7472       return false;
7473   }
7474 
7475   // Create the vldN-dup node.
7476   EVT Tys[5];
7477   unsigned n;
7478   for (n = 0; n < NumVecs; ++n)
7479     Tys[n] = VT;
7480   Tys[n] = MVT::Other;
7481   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
7482   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
7483   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
7484   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
7485                                            Ops, 2, VLDMemInt->getMemoryVT(),
7486                                            VLDMemInt->getMemOperand());
7487 
7488   // Update the uses.
7489   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
7490        UI != UE; ++UI) {
7491     unsigned ResNo = UI.getUse().getResNo();
7492     // Ignore uses of the chain result.
7493     if (ResNo == NumVecs)
7494       continue;
7495     SDNode *User = *UI;
7496     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
7497   }
7498 
7499   // Now the vldN-lane intrinsic is dead except for its chain result.
7500   // Update uses of the chain.
7501   std::vector<SDValue> VLDDupResults;
7502   for (unsigned n = 0; n < NumVecs; ++n)
7503     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
7504   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
7505   DCI.CombineTo(VLD, VLDDupResults);
7506 
7507   return true;
7508 }
7509 
7510 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
7511 /// ARMISD::VDUPLANE.
7512 static SDValue PerformVDUPLANECombine(SDNode *N,
7513                                       TargetLowering::DAGCombinerInfo &DCI) {
7514   SDValue Op = N->getOperand(0);
7515 
7516   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
7517   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
7518   if (CombineVLDDUP(N, DCI))
7519     return SDValue(N, 0);
7520 
7521   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
7522   // redundant.  Ignore bit_converts for now; element sizes are checked below.
7523   while (Op.getOpcode() == ISD::BITCAST)
7524     Op = Op.getOperand(0);
7525   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
7526     return SDValue();
7527 
7528   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
7529   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
7530   // The canonical VMOV for a zero vector uses a 32-bit element size.
7531   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7532   unsigned EltBits;
7533   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
7534     EltSize = 8;
7535   EVT VT = N->getValueType(0);
7536   if (EltSize > VT.getVectorElementType().getSizeInBits())
7537     return SDValue();
7538 
7539   return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
7540 }
7541 
7542 // isConstVecPow2 - Return true if each vector element is a power of 2, all
7543 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
7544 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
7545 {
7546   integerPart cN;
7547   integerPart c0 = 0;
7548   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
7549        I != E; I++) {
7550     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
7551     if (!C)
7552       return false;
7553 
7554     bool isExact;
7555     APFloat APF = C->getValueAPF();
7556     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
7557         != APFloat::opOK || !isExact)
7558       return false;
7559 
7560     c0 = (I == 0) ? cN : c0;
7561     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
7562       return false;
7563   }
7564   C = c0;
7565   return true;
7566 }
7567 
7568 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
7569 /// can replace combinations of VMUL and VCVT (floating-point to integer)
7570 /// when the VMUL has a constant operand that is a power of 2.
7571 ///
7572 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
7573 ///  vmul.f32        d16, d17, d16
7574 ///  vcvt.s32.f32    d16, d16
7575 /// becomes:
7576 ///  vcvt.s32.f32    d16, d16, #3
7577 static SDValue PerformVCVTCombine(SDNode *N,
7578                                   TargetLowering::DAGCombinerInfo &DCI,
7579                                   const ARMSubtarget *Subtarget) {
7580   SelectionDAG &DAG = DCI.DAG;
7581   SDValue Op = N->getOperand(0);
7582 
7583   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
7584       Op.getOpcode() != ISD::FMUL)
7585     return SDValue();
7586 
7587   uint64_t C;
7588   SDValue N0 = Op->getOperand(0);
7589   SDValue ConstVec = Op->getOperand(1);
7590   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
7591 
7592   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
7593       !isConstVecPow2(ConstVec, isSigned, C))
7594     return SDValue();
7595 
7596   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
7597     Intrinsic::arm_neon_vcvtfp2fxu;
7598   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7599                      N->getValueType(0),
7600                      DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
7601                      DAG.getConstant(Log2_64(C), MVT::i32));
7602 }
7603 
7604 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
7605 /// can replace combinations of VCVT (integer to floating-point) and VDIV
7606 /// when the VDIV has a constant operand that is a power of 2.
7607 ///
7608 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
7609 ///  vcvt.f32.s32    d16, d16
7610 ///  vdiv.f32        d16, d17, d16
7611 /// becomes:
7612 ///  vcvt.f32.s32    d16, d16, #3
7613 static SDValue PerformVDIVCombine(SDNode *N,
7614                                   TargetLowering::DAGCombinerInfo &DCI,
7615                                   const ARMSubtarget *Subtarget) {
7616   SelectionDAG &DAG = DCI.DAG;
7617   SDValue Op = N->getOperand(0);
7618   unsigned OpOpcode = Op.getNode()->getOpcode();
7619 
7620   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
7621       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
7622     return SDValue();
7623 
7624   uint64_t C;
7625   SDValue ConstVec = N->getOperand(1);
7626   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
7627 
7628   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
7629       !isConstVecPow2(ConstVec, isSigned, C))
7630     return SDValue();
7631 
7632   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
7633     Intrinsic::arm_neon_vcvtfxu2fp;
7634   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7635                      Op.getValueType(),
7636                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
7637                      Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
7638 }
7639 
7640 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
7641 /// operand of a vector shift operation, where all the elements of the
7642 /// build_vector must have the same constant integer value.
7643 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
7644   // Ignore bit_converts.
7645   while (Op.getOpcode() == ISD::BITCAST)
7646     Op = Op.getOperand(0);
7647   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7648   APInt SplatBits, SplatUndef;
7649   unsigned SplatBitSize;
7650   bool HasAnyUndefs;
7651   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
7652                                       HasAnyUndefs, ElementBits) ||
7653       SplatBitSize > ElementBits)
7654     return false;
7655   Cnt = SplatBits.getSExtValue();
7656   return true;
7657 }
7658 
7659 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
7660 /// operand of a vector shift left operation.  That value must be in the range:
7661 ///   0 <= Value < ElementBits for a left shift; or
7662 ///   0 <= Value <= ElementBits for a long left shift.
7663 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
7664   assert(VT.isVector() && "vector shift count is not a vector type");
7665   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
7666   if (! getVShiftImm(Op, ElementBits, Cnt))
7667     return false;
7668   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
7669 }
7670 
7671 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
7672 /// operand of a vector shift right operation.  For a shift opcode, the value
7673 /// is positive, but for an intrinsic the value count must be negative. The
7674 /// absolute value must be in the range:
7675 ///   1 <= |Value| <= ElementBits for a right shift; or
7676 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
7677 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
7678                          int64_t &Cnt) {
7679   assert(VT.isVector() && "vector shift count is not a vector type");
7680   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
7681   if (! getVShiftImm(Op, ElementBits, Cnt))
7682     return false;
7683   if (isIntrinsic)
7684     Cnt = -Cnt;
7685   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
7686 }
7687 
7688 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
7689 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
7690   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7691   switch (IntNo) {
7692   default:
7693     // Don't do anything for most intrinsics.
7694     break;
7695 
7696   // Vector shifts: check for immediate versions and lower them.
7697   // Note: This is done during DAG combining instead of DAG legalizing because
7698   // the build_vectors for 64-bit vector element shift counts are generally
7699   // not legal, and it is hard to see their values after they get legalized to
7700   // loads from a constant pool.
7701   case Intrinsic::arm_neon_vshifts:
7702   case Intrinsic::arm_neon_vshiftu:
7703   case Intrinsic::arm_neon_vshiftls:
7704   case Intrinsic::arm_neon_vshiftlu:
7705   case Intrinsic::arm_neon_vshiftn:
7706   case Intrinsic::arm_neon_vrshifts:
7707   case Intrinsic::arm_neon_vrshiftu:
7708   case Intrinsic::arm_neon_vrshiftn:
7709   case Intrinsic::arm_neon_vqshifts:
7710   case Intrinsic::arm_neon_vqshiftu:
7711   case Intrinsic::arm_neon_vqshiftsu:
7712   case Intrinsic::arm_neon_vqshiftns:
7713   case Intrinsic::arm_neon_vqshiftnu:
7714   case Intrinsic::arm_neon_vqshiftnsu:
7715   case Intrinsic::arm_neon_vqrshiftns:
7716   case Intrinsic::arm_neon_vqrshiftnu:
7717   case Intrinsic::arm_neon_vqrshiftnsu: {
7718     EVT VT = N->getOperand(1).getValueType();
7719     int64_t Cnt;
7720     unsigned VShiftOpc = 0;
7721 
7722     switch (IntNo) {
7723     case Intrinsic::arm_neon_vshifts:
7724     case Intrinsic::arm_neon_vshiftu:
7725       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
7726         VShiftOpc = ARMISD::VSHL;
7727         break;
7728       }
7729       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
7730         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
7731                      ARMISD::VSHRs : ARMISD::VSHRu);
7732         break;
7733       }
7734       return SDValue();
7735 
7736     case Intrinsic::arm_neon_vshiftls:
7737     case Intrinsic::arm_neon_vshiftlu:
7738       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
7739         break;
7740       llvm_unreachable("invalid shift count for vshll intrinsic");
7741 
7742     case Intrinsic::arm_neon_vrshifts:
7743     case Intrinsic::arm_neon_vrshiftu:
7744       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
7745         break;
7746       return SDValue();
7747 
7748     case Intrinsic::arm_neon_vqshifts:
7749     case Intrinsic::arm_neon_vqshiftu:
7750       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
7751         break;
7752       return SDValue();
7753 
7754     case Intrinsic::arm_neon_vqshiftsu:
7755       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
7756         break;
7757       llvm_unreachable("invalid shift count for vqshlu intrinsic");
7758 
7759     case Intrinsic::arm_neon_vshiftn:
7760     case Intrinsic::arm_neon_vrshiftn:
7761     case Intrinsic::arm_neon_vqshiftns:
7762     case Intrinsic::arm_neon_vqshiftnu:
7763     case Intrinsic::arm_neon_vqshiftnsu:
7764     case Intrinsic::arm_neon_vqrshiftns:
7765     case Intrinsic::arm_neon_vqrshiftnu:
7766     case Intrinsic::arm_neon_vqrshiftnsu:
7767       // Narrowing shifts require an immediate right shift.
7768       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
7769         break;
7770       llvm_unreachable("invalid shift count for narrowing vector shift "
7771                        "intrinsic");
7772 
7773     default:
7774       llvm_unreachable("unhandled vector shift");
7775     }
7776 
7777     switch (IntNo) {
7778     case Intrinsic::arm_neon_vshifts:
7779     case Intrinsic::arm_neon_vshiftu:
7780       // Opcode already set above.
7781       break;
7782     case Intrinsic::arm_neon_vshiftls:
7783     case Intrinsic::arm_neon_vshiftlu:
7784       if (Cnt == VT.getVectorElementType().getSizeInBits())
7785         VShiftOpc = ARMISD::VSHLLi;
7786       else
7787         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
7788                      ARMISD::VSHLLs : ARMISD::VSHLLu);
7789       break;
7790     case Intrinsic::arm_neon_vshiftn:
7791       VShiftOpc = ARMISD::VSHRN; break;
7792     case Intrinsic::arm_neon_vrshifts:
7793       VShiftOpc = ARMISD::VRSHRs; break;
7794     case Intrinsic::arm_neon_vrshiftu:
7795       VShiftOpc = ARMISD::VRSHRu; break;
7796     case Intrinsic::arm_neon_vrshiftn:
7797       VShiftOpc = ARMISD::VRSHRN; break;
7798     case Intrinsic::arm_neon_vqshifts:
7799       VShiftOpc = ARMISD::VQSHLs; break;
7800     case Intrinsic::arm_neon_vqshiftu:
7801       VShiftOpc = ARMISD::VQSHLu; break;
7802     case Intrinsic::arm_neon_vqshiftsu:
7803       VShiftOpc = ARMISD::VQSHLsu; break;
7804     case Intrinsic::arm_neon_vqshiftns:
7805       VShiftOpc = ARMISD::VQSHRNs; break;
7806     case Intrinsic::arm_neon_vqshiftnu:
7807       VShiftOpc = ARMISD::VQSHRNu; break;
7808     case Intrinsic::arm_neon_vqshiftnsu:
7809       VShiftOpc = ARMISD::VQSHRNsu; break;
7810     case Intrinsic::arm_neon_vqrshiftns:
7811       VShiftOpc = ARMISD::VQRSHRNs; break;
7812     case Intrinsic::arm_neon_vqrshiftnu:
7813       VShiftOpc = ARMISD::VQRSHRNu; break;
7814     case Intrinsic::arm_neon_vqrshiftnsu:
7815       VShiftOpc = ARMISD::VQRSHRNsu; break;
7816     }
7817 
7818     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
7819                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
7820   }
7821 
7822   case Intrinsic::arm_neon_vshiftins: {
7823     EVT VT = N->getOperand(1).getValueType();
7824     int64_t Cnt;
7825     unsigned VShiftOpc = 0;
7826 
7827     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
7828       VShiftOpc = ARMISD::VSLI;
7829     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
7830       VShiftOpc = ARMISD::VSRI;
7831     else {
7832       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
7833     }
7834 
7835     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
7836                        N->getOperand(1), N->getOperand(2),
7837                        DAG.getConstant(Cnt, MVT::i32));
7838   }
7839 
7840   case Intrinsic::arm_neon_vqrshifts:
7841   case Intrinsic::arm_neon_vqrshiftu:
7842     // No immediate versions of these to check for.
7843     break;
7844   }
7845 
7846   return SDValue();
7847 }
7848 
7849 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
7850 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
7851 /// combining instead of DAG legalizing because the build_vectors for 64-bit
7852 /// vector element shift counts are generally not legal, and it is hard to see
7853 /// their values after they get legalized to loads from a constant pool.
7854 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
7855                                    const ARMSubtarget *ST) {
7856   EVT VT = N->getValueType(0);
7857 
7858   // Nothing to be done for scalar shifts.
7859   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7860   if (!VT.isVector() || !TLI.isTypeLegal(VT))
7861     return SDValue();
7862 
7863   assert(ST->hasNEON() && "unexpected vector shift");
7864   int64_t Cnt;
7865 
7866   switch (N->getOpcode()) {
7867   default: llvm_unreachable("unexpected shift opcode");
7868 
7869   case ISD::SHL:
7870     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
7871       return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
7872                          DAG.getConstant(Cnt, MVT::i32));
7873     break;
7874 
7875   case ISD::SRA:
7876   case ISD::SRL:
7877     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
7878       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
7879                             ARMISD::VSHRs : ARMISD::VSHRu);
7880       return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
7881                          DAG.getConstant(Cnt, MVT::i32));
7882     }
7883   }
7884   return SDValue();
7885 }
7886 
7887 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
7888 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
7889 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
7890                                     const ARMSubtarget *ST) {
7891   SDValue N0 = N->getOperand(0);
7892 
7893   // Check for sign- and zero-extensions of vector extract operations of 8-
7894   // and 16-bit vector elements.  NEON supports these directly.  They are
7895   // handled during DAG combining because type legalization will promote them
7896   // to 32-bit types and it is messy to recognize the operations after that.
7897   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7898     SDValue Vec = N0.getOperand(0);
7899     SDValue Lane = N0.getOperand(1);
7900     EVT VT = N->getValueType(0);
7901     EVT EltVT = N0.getValueType();
7902     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7903 
7904     if (VT == MVT::i32 &&
7905         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
7906         TLI.isTypeLegal(Vec.getValueType()) &&
7907         isa<ConstantSDNode>(Lane)) {
7908 
7909       unsigned Opc = 0;
7910       switch (N->getOpcode()) {
7911       default: llvm_unreachable("unexpected opcode");
7912       case ISD::SIGN_EXTEND:
7913         Opc = ARMISD::VGETLANEs;
7914         break;
7915       case ISD::ZERO_EXTEND:
7916       case ISD::ANY_EXTEND:
7917         Opc = ARMISD::VGETLANEu;
7918         break;
7919       }
7920       return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
7921     }
7922   }
7923 
7924   return SDValue();
7925 }
7926 
7927 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
7928 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
7929 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
7930                                        const ARMSubtarget *ST) {
7931   // If the target supports NEON, try to use vmax/vmin instructions for f32
7932   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
7933   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
7934   // a NaN; only do the transformation when it matches that behavior.
7935 
7936   // For now only do this when using NEON for FP operations; if using VFP, it
7937   // is not obvious that the benefit outweighs the cost of switching to the
7938   // NEON pipeline.
7939   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
7940       N->getValueType(0) != MVT::f32)
7941     return SDValue();
7942 
7943   SDValue CondLHS = N->getOperand(0);
7944   SDValue CondRHS = N->getOperand(1);
7945   SDValue LHS = N->getOperand(2);
7946   SDValue RHS = N->getOperand(3);
7947   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
7948 
7949   unsigned Opcode = 0;
7950   bool IsReversed;
7951   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
7952     IsReversed = false; // x CC y ? x : y
7953   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
7954     IsReversed = true ; // x CC y ? y : x
7955   } else {
7956     return SDValue();
7957   }
7958 
7959   bool IsUnordered;
7960   switch (CC) {
7961   default: break;
7962   case ISD::SETOLT:
7963   case ISD::SETOLE:
7964   case ISD::SETLT:
7965   case ISD::SETLE:
7966   case ISD::SETULT:
7967   case ISD::SETULE:
7968     // If LHS is NaN, an ordered comparison will be false and the result will
7969     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
7970     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
7971     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
7972     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
7973       break;
7974     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
7975     // will return -0, so vmin can only be used for unsafe math or if one of
7976     // the operands is known to be nonzero.
7977     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
7978         !DAG.getTarget().Options.UnsafeFPMath &&
7979         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
7980       break;
7981     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
7982     break;
7983 
7984   case ISD::SETOGT:
7985   case ISD::SETOGE:
7986   case ISD::SETGT:
7987   case ISD::SETGE:
7988   case ISD::SETUGT:
7989   case ISD::SETUGE:
7990     // If LHS is NaN, an ordered comparison will be false and the result will
7991     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
7992     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
7993     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
7994     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
7995       break;
7996     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
7997     // will return +0, so vmax can only be used for unsafe math or if one of
7998     // the operands is known to be nonzero.
7999     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
8000         !DAG.getTarget().Options.UnsafeFPMath &&
8001         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8002       break;
8003     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
8004     break;
8005   }
8006 
8007   if (!Opcode)
8008     return SDValue();
8009   return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
8010 }
8011 
8012 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
8013 SDValue
8014 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
8015   SDValue Cmp = N->getOperand(4);
8016   if (Cmp.getOpcode() != ARMISD::CMPZ)
8017     // Only looking at EQ and NE cases.
8018     return SDValue();
8019 
8020   EVT VT = N->getValueType(0);
8021   DebugLoc dl = N->getDebugLoc();
8022   SDValue LHS = Cmp.getOperand(0);
8023   SDValue RHS = Cmp.getOperand(1);
8024   SDValue FalseVal = N->getOperand(0);
8025   SDValue TrueVal = N->getOperand(1);
8026   SDValue ARMcc = N->getOperand(2);
8027   ARMCC::CondCodes CC =
8028     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
8029 
8030   // Simplify
8031   //   mov     r1, r0
8032   //   cmp     r1, x
8033   //   mov     r0, y
8034   //   moveq   r0, x
8035   // to
8036   //   cmp     r0, x
8037   //   movne   r0, y
8038   //
8039   //   mov     r1, r0
8040   //   cmp     r1, x
8041   //   mov     r0, x
8042   //   movne   r0, y
8043   // to
8044   //   cmp     r0, x
8045   //   movne   r0, y
8046   /// FIXME: Turn this into a target neutral optimization?
8047   SDValue Res;
8048   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
8049     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
8050                       N->getOperand(3), Cmp);
8051   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
8052     SDValue ARMcc;
8053     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
8054     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
8055                       N->getOperand(3), NewCmp);
8056   }
8057 
8058   if (Res.getNode()) {
8059     APInt KnownZero, KnownOne;
8060     APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
8061     DAG.ComputeMaskedBits(SDValue(N,0), Mask, KnownZero, KnownOne);
8062     // Capture demanded bits information that would be otherwise lost.
8063     if (KnownZero == 0xfffffffe)
8064       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8065                         DAG.getValueType(MVT::i1));
8066     else if (KnownZero == 0xffffff00)
8067       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8068                         DAG.getValueType(MVT::i8));
8069     else if (KnownZero == 0xffff0000)
8070       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8071                         DAG.getValueType(MVT::i16));
8072   }
8073 
8074   return Res;
8075 }
8076 
8077 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
8078                                              DAGCombinerInfo &DCI) const {
8079   switch (N->getOpcode()) {
8080   default: break;
8081   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
8082   case ISD::SUB:        return PerformSUBCombine(N, DCI);
8083   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
8084   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
8085   case ISD::AND:        return PerformANDCombine(N, DCI);
8086   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
8087   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
8088   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
8089   case ISD::STORE:      return PerformSTORECombine(N, DCI);
8090   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
8091   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
8092   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
8093   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
8094   case ISD::FP_TO_SINT:
8095   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
8096   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
8097   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
8098   case ISD::SHL:
8099   case ISD::SRA:
8100   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
8101   case ISD::SIGN_EXTEND:
8102   case ISD::ZERO_EXTEND:
8103   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
8104   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
8105   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
8106   case ARMISD::VLD2DUP:
8107   case ARMISD::VLD3DUP:
8108   case ARMISD::VLD4DUP:
8109     return CombineBaseUpdate(N, DCI);
8110   case ISD::INTRINSIC_VOID:
8111   case ISD::INTRINSIC_W_CHAIN:
8112     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8113     case Intrinsic::arm_neon_vld1:
8114     case Intrinsic::arm_neon_vld2:
8115     case Intrinsic::arm_neon_vld3:
8116     case Intrinsic::arm_neon_vld4:
8117     case Intrinsic::arm_neon_vld2lane:
8118     case Intrinsic::arm_neon_vld3lane:
8119     case Intrinsic::arm_neon_vld4lane:
8120     case Intrinsic::arm_neon_vst1:
8121     case Intrinsic::arm_neon_vst2:
8122     case Intrinsic::arm_neon_vst3:
8123     case Intrinsic::arm_neon_vst4:
8124     case Intrinsic::arm_neon_vst2lane:
8125     case Intrinsic::arm_neon_vst3lane:
8126     case Intrinsic::arm_neon_vst4lane:
8127       return CombineBaseUpdate(N, DCI);
8128     default: break;
8129     }
8130     break;
8131   }
8132   return SDValue();
8133 }
8134 
8135 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
8136                                                           EVT VT) const {
8137   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
8138 }
8139 
8140 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
8141   if (!Subtarget->allowsUnalignedMem())
8142     return false;
8143 
8144   switch (VT.getSimpleVT().SimpleTy) {
8145   default:
8146     return false;
8147   case MVT::i8:
8148   case MVT::i16:
8149   case MVT::i32:
8150     return true;
8151   // FIXME: VLD1 etc with standard alignment is legal.
8152   }
8153 }
8154 
8155 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
8156                        unsigned AlignCheck) {
8157   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
8158           (DstAlign == 0 || DstAlign % AlignCheck == 0));
8159 }
8160 
8161 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
8162                                            unsigned DstAlign, unsigned SrcAlign,
8163                                            bool IsZeroVal,
8164                                            bool MemcpyStrSrc,
8165                                            MachineFunction &MF) const {
8166   const Function *F = MF.getFunction();
8167 
8168   // See if we can use NEON instructions for this...
8169   if (IsZeroVal &&
8170       !F->hasFnAttr(Attribute::NoImplicitFloat) &&
8171       Subtarget->hasNEON()) {
8172     if (memOpAlign(SrcAlign, DstAlign, 16) && Size >= 16) {
8173       return MVT::v4i32;
8174     } else if (memOpAlign(SrcAlign, DstAlign, 8) && Size >= 8) {
8175       return MVT::v2i32;
8176     }
8177   }
8178 
8179   // Lowering to i32/i16 if the size permits.
8180   if (Size >= 4) {
8181     return MVT::i32;
8182   } else if (Size >= 2) {
8183     return MVT::i16;
8184   }
8185 
8186   // Let the target-independent logic figure it out.
8187   return MVT::Other;
8188 }
8189 
8190 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
8191   if (V < 0)
8192     return false;
8193 
8194   unsigned Scale = 1;
8195   switch (VT.getSimpleVT().SimpleTy) {
8196   default: return false;
8197   case MVT::i1:
8198   case MVT::i8:
8199     // Scale == 1;
8200     break;
8201   case MVT::i16:
8202     // Scale == 2;
8203     Scale = 2;
8204     break;
8205   case MVT::i32:
8206     // Scale == 4;
8207     Scale = 4;
8208     break;
8209   }
8210 
8211   if ((V & (Scale - 1)) != 0)
8212     return false;
8213   V /= Scale;
8214   return V == (V & ((1LL << 5) - 1));
8215 }
8216 
8217 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
8218                                       const ARMSubtarget *Subtarget) {
8219   bool isNeg = false;
8220   if (V < 0) {
8221     isNeg = true;
8222     V = - V;
8223   }
8224 
8225   switch (VT.getSimpleVT().SimpleTy) {
8226   default: return false;
8227   case MVT::i1:
8228   case MVT::i8:
8229   case MVT::i16:
8230   case MVT::i32:
8231     // + imm12 or - imm8
8232     if (isNeg)
8233       return V == (V & ((1LL << 8) - 1));
8234     return V == (V & ((1LL << 12) - 1));
8235   case MVT::f32:
8236   case MVT::f64:
8237     // Same as ARM mode. FIXME: NEON?
8238     if (!Subtarget->hasVFP2())
8239       return false;
8240     if ((V & 3) != 0)
8241       return false;
8242     V >>= 2;
8243     return V == (V & ((1LL << 8) - 1));
8244   }
8245 }
8246 
8247 /// isLegalAddressImmediate - Return true if the integer value can be used
8248 /// as the offset of the target addressing mode for load / store of the
8249 /// given type.
8250 static bool isLegalAddressImmediate(int64_t V, EVT VT,
8251                                     const ARMSubtarget *Subtarget) {
8252   if (V == 0)
8253     return true;
8254 
8255   if (!VT.isSimple())
8256     return false;
8257 
8258   if (Subtarget->isThumb1Only())
8259     return isLegalT1AddressImmediate(V, VT);
8260   else if (Subtarget->isThumb2())
8261     return isLegalT2AddressImmediate(V, VT, Subtarget);
8262 
8263   // ARM mode.
8264   if (V < 0)
8265     V = - V;
8266   switch (VT.getSimpleVT().SimpleTy) {
8267   default: return false;
8268   case MVT::i1:
8269   case MVT::i8:
8270   case MVT::i32:
8271     // +- imm12
8272     return V == (V & ((1LL << 12) - 1));
8273   case MVT::i16:
8274     // +- imm8
8275     return V == (V & ((1LL << 8) - 1));
8276   case MVT::f32:
8277   case MVT::f64:
8278     if (!Subtarget->hasVFP2()) // FIXME: NEON?
8279       return false;
8280     if ((V & 3) != 0)
8281       return false;
8282     V >>= 2;
8283     return V == (V & ((1LL << 8) - 1));
8284   }
8285 }
8286 
8287 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
8288                                                       EVT VT) const {
8289   int Scale = AM.Scale;
8290   if (Scale < 0)
8291     return false;
8292 
8293   switch (VT.getSimpleVT().SimpleTy) {
8294   default: return false;
8295   case MVT::i1:
8296   case MVT::i8:
8297   case MVT::i16:
8298   case MVT::i32:
8299     if (Scale == 1)
8300       return true;
8301     // r + r << imm
8302     Scale = Scale & ~1;
8303     return Scale == 2 || Scale == 4 || Scale == 8;
8304   case MVT::i64:
8305     // r + r
8306     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
8307       return true;
8308     return false;
8309   case MVT::isVoid:
8310     // Note, we allow "void" uses (basically, uses that aren't loads or
8311     // stores), because arm allows folding a scale into many arithmetic
8312     // operations.  This should be made more precise and revisited later.
8313 
8314     // Allow r << imm, but the imm has to be a multiple of two.
8315     if (Scale & 1) return false;
8316     return isPowerOf2_32(Scale);
8317   }
8318 }
8319 
8320 /// isLegalAddressingMode - Return true if the addressing mode represented
8321 /// by AM is legal for this target, for a load/store of the specified type.
8322 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
8323                                               Type *Ty) const {
8324   EVT VT = getValueType(Ty, true);
8325   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
8326     return false;
8327 
8328   // Can never fold addr of global into load/store.
8329   if (AM.BaseGV)
8330     return false;
8331 
8332   switch (AM.Scale) {
8333   case 0:  // no scale reg, must be "r+i" or "r", or "i".
8334     break;
8335   case 1:
8336     if (Subtarget->isThumb1Only())
8337       return false;
8338     // FALL THROUGH.
8339   default:
8340     // ARM doesn't support any R+R*scale+imm addr modes.
8341     if (AM.BaseOffs)
8342       return false;
8343 
8344     if (!VT.isSimple())
8345       return false;
8346 
8347     if (Subtarget->isThumb2())
8348       return isLegalT2ScaledAddressingMode(AM, VT);
8349 
8350     int Scale = AM.Scale;
8351     switch (VT.getSimpleVT().SimpleTy) {
8352     default: return false;
8353     case MVT::i1:
8354     case MVT::i8:
8355     case MVT::i32:
8356       if (Scale < 0) Scale = -Scale;
8357       if (Scale == 1)
8358         return true;
8359       // r + r << imm
8360       return isPowerOf2_32(Scale & ~1);
8361     case MVT::i16:
8362     case MVT::i64:
8363       // r + r
8364       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
8365         return true;
8366       return false;
8367 
8368     case MVT::isVoid:
8369       // Note, we allow "void" uses (basically, uses that aren't loads or
8370       // stores), because arm allows folding a scale into many arithmetic
8371       // operations.  This should be made more precise and revisited later.
8372 
8373       // Allow r << imm, but the imm has to be a multiple of two.
8374       if (Scale & 1) return false;
8375       return isPowerOf2_32(Scale);
8376     }
8377     break;
8378   }
8379   return true;
8380 }
8381 
8382 /// isLegalICmpImmediate - Return true if the specified immediate is legal
8383 /// icmp immediate, that is the target has icmp instructions which can compare
8384 /// a register against the immediate without having to materialize the
8385 /// immediate into a register.
8386 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
8387   if (!Subtarget->isThumb())
8388     return ARM_AM::getSOImmVal(Imm) != -1;
8389   if (Subtarget->isThumb2())
8390     return ARM_AM::getT2SOImmVal(Imm) != -1;
8391   return Imm >= 0 && Imm <= 255;
8392 }
8393 
8394 /// isLegalAddImmediate - Return true if the specified immediate is legal
8395 /// add immediate, that is the target has add instructions which can add
8396 /// a register with the immediate without having to materialize the
8397 /// immediate into a register.
8398 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
8399   return ARM_AM::getSOImmVal(Imm) != -1;
8400 }
8401 
8402 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
8403                                       bool isSEXTLoad, SDValue &Base,
8404                                       SDValue &Offset, bool &isInc,
8405                                       SelectionDAG &DAG) {
8406   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
8407     return false;
8408 
8409   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
8410     // AddressingMode 3
8411     Base = Ptr->getOperand(0);
8412     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
8413       int RHSC = (int)RHS->getZExtValue();
8414       if (RHSC < 0 && RHSC > -256) {
8415         assert(Ptr->getOpcode() == ISD::ADD);
8416         isInc = false;
8417         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
8418         return true;
8419       }
8420     }
8421     isInc = (Ptr->getOpcode() == ISD::ADD);
8422     Offset = Ptr->getOperand(1);
8423     return true;
8424   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
8425     // AddressingMode 2
8426     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
8427       int RHSC = (int)RHS->getZExtValue();
8428       if (RHSC < 0 && RHSC > -0x1000) {
8429         assert(Ptr->getOpcode() == ISD::ADD);
8430         isInc = false;
8431         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
8432         Base = Ptr->getOperand(0);
8433         return true;
8434       }
8435     }
8436 
8437     if (Ptr->getOpcode() == ISD::ADD) {
8438       isInc = true;
8439       ARM_AM::ShiftOpc ShOpcVal=
8440         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
8441       if (ShOpcVal != ARM_AM::no_shift) {
8442         Base = Ptr->getOperand(1);
8443         Offset = Ptr->getOperand(0);
8444       } else {
8445         Base = Ptr->getOperand(0);
8446         Offset = Ptr->getOperand(1);
8447       }
8448       return true;
8449     }
8450 
8451     isInc = (Ptr->getOpcode() == ISD::ADD);
8452     Base = Ptr->getOperand(0);
8453     Offset = Ptr->getOperand(1);
8454     return true;
8455   }
8456 
8457   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
8458   return false;
8459 }
8460 
8461 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
8462                                      bool isSEXTLoad, SDValue &Base,
8463                                      SDValue &Offset, bool &isInc,
8464                                      SelectionDAG &DAG) {
8465   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
8466     return false;
8467 
8468   Base = Ptr->getOperand(0);
8469   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
8470     int RHSC = (int)RHS->getZExtValue();
8471     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
8472       assert(Ptr->getOpcode() == ISD::ADD);
8473       isInc = false;
8474       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
8475       return true;
8476     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
8477       isInc = Ptr->getOpcode() == ISD::ADD;
8478       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
8479       return true;
8480     }
8481   }
8482 
8483   return false;
8484 }
8485 
8486 /// getPreIndexedAddressParts - returns true by value, base pointer and
8487 /// offset pointer and addressing mode by reference if the node's address
8488 /// can be legally represented as pre-indexed load / store address.
8489 bool
8490 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
8491                                              SDValue &Offset,
8492                                              ISD::MemIndexedMode &AM,
8493                                              SelectionDAG &DAG) const {
8494   if (Subtarget->isThumb1Only())
8495     return false;
8496 
8497   EVT VT;
8498   SDValue Ptr;
8499   bool isSEXTLoad = false;
8500   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8501     Ptr = LD->getBasePtr();
8502     VT  = LD->getMemoryVT();
8503     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
8504   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8505     Ptr = ST->getBasePtr();
8506     VT  = ST->getMemoryVT();
8507   } else
8508     return false;
8509 
8510   bool isInc;
8511   bool isLegal = false;
8512   if (Subtarget->isThumb2())
8513     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
8514                                        Offset, isInc, DAG);
8515   else
8516     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
8517                                         Offset, isInc, DAG);
8518   if (!isLegal)
8519     return false;
8520 
8521   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
8522   return true;
8523 }
8524 
8525 /// getPostIndexedAddressParts - returns true by value, base pointer and
8526 /// offset pointer and addressing mode by reference if this node can be
8527 /// combined with a load / store to form a post-indexed load / store.
8528 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
8529                                                    SDValue &Base,
8530                                                    SDValue &Offset,
8531                                                    ISD::MemIndexedMode &AM,
8532                                                    SelectionDAG &DAG) const {
8533   if (Subtarget->isThumb1Only())
8534     return false;
8535 
8536   EVT VT;
8537   SDValue Ptr;
8538   bool isSEXTLoad = false;
8539   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8540     VT  = LD->getMemoryVT();
8541     Ptr = LD->getBasePtr();
8542     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
8543   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8544     VT  = ST->getMemoryVT();
8545     Ptr = ST->getBasePtr();
8546   } else
8547     return false;
8548 
8549   bool isInc;
8550   bool isLegal = false;
8551   if (Subtarget->isThumb2())
8552     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
8553                                        isInc, DAG);
8554   else
8555     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
8556                                         isInc, DAG);
8557   if (!isLegal)
8558     return false;
8559 
8560   if (Ptr != Base) {
8561     // Swap base ptr and offset to catch more post-index load / store when
8562     // it's legal. In Thumb2 mode, offset must be an immediate.
8563     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
8564         !Subtarget->isThumb2())
8565       std::swap(Base, Offset);
8566 
8567     // Post-indexed load / store update the base pointer.
8568     if (Ptr != Base)
8569       return false;
8570   }
8571 
8572   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
8573   return true;
8574 }
8575 
8576 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8577                                                        const APInt &Mask,
8578                                                        APInt &KnownZero,
8579                                                        APInt &KnownOne,
8580                                                        const SelectionDAG &DAG,
8581                                                        unsigned Depth) const {
8582   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);
8583   switch (Op.getOpcode()) {
8584   default: break;
8585   case ARMISD::CMOV: {
8586     // Bits are known zero/one if known on the LHS and RHS.
8587     DAG.ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
8588     if (KnownZero == 0 && KnownOne == 0) return;
8589 
8590     APInt KnownZeroRHS, KnownOneRHS;
8591     DAG.ComputeMaskedBits(Op.getOperand(1), Mask,
8592                           KnownZeroRHS, KnownOneRHS, Depth+1);
8593     KnownZero &= KnownZeroRHS;
8594     KnownOne  &= KnownOneRHS;
8595     return;
8596   }
8597   }
8598 }
8599 
8600 //===----------------------------------------------------------------------===//
8601 //                           ARM Inline Assembly Support
8602 //===----------------------------------------------------------------------===//
8603 
8604 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
8605   // Looking for "rev" which is V6+.
8606   if (!Subtarget->hasV6Ops())
8607     return false;
8608 
8609   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
8610   std::string AsmStr = IA->getAsmString();
8611   SmallVector<StringRef, 4> AsmPieces;
8612   SplitString(AsmStr, AsmPieces, ";\n");
8613 
8614   switch (AsmPieces.size()) {
8615   default: return false;
8616   case 1:
8617     AsmStr = AsmPieces[0];
8618     AsmPieces.clear();
8619     SplitString(AsmStr, AsmPieces, " \t,");
8620 
8621     // rev $0, $1
8622     if (AsmPieces.size() == 3 &&
8623         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
8624         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
8625       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
8626       if (Ty && Ty->getBitWidth() == 32)
8627         return IntrinsicLowering::LowerToByteSwap(CI);
8628     }
8629     break;
8630   }
8631 
8632   return false;
8633 }
8634 
8635 /// getConstraintType - Given a constraint letter, return the type of
8636 /// constraint it is for this target.
8637 ARMTargetLowering::ConstraintType
8638 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
8639   if (Constraint.size() == 1) {
8640     switch (Constraint[0]) {
8641     default:  break;
8642     case 'l': return C_RegisterClass;
8643     case 'w': return C_RegisterClass;
8644     case 'h': return C_RegisterClass;
8645     case 'x': return C_RegisterClass;
8646     case 't': return C_RegisterClass;
8647     case 'j': return C_Other; // Constant for movw.
8648       // An address with a single base register. Due to the way we
8649       // currently handle addresses it is the same as an 'r' memory constraint.
8650     case 'Q': return C_Memory;
8651     }
8652   } else if (Constraint.size() == 2) {
8653     switch (Constraint[0]) {
8654     default: break;
8655     // All 'U+' constraints are addresses.
8656     case 'U': return C_Memory;
8657     }
8658   }
8659   return TargetLowering::getConstraintType(Constraint);
8660 }
8661 
8662 /// Examine constraint type and operand type and determine a weight value.
8663 /// This object must already have been set up with the operand type
8664 /// and the current alternative constraint selected.
8665 TargetLowering::ConstraintWeight
8666 ARMTargetLowering::getSingleConstraintMatchWeight(
8667     AsmOperandInfo &info, const char *constraint) const {
8668   ConstraintWeight weight = CW_Invalid;
8669   Value *CallOperandVal = info.CallOperandVal;
8670     // If we don't have a value, we can't do a match,
8671     // but allow it at the lowest weight.
8672   if (CallOperandVal == NULL)
8673     return CW_Default;
8674   Type *type = CallOperandVal->getType();
8675   // Look at the constraint type.
8676   switch (*constraint) {
8677   default:
8678     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
8679     break;
8680   case 'l':
8681     if (type->isIntegerTy()) {
8682       if (Subtarget->isThumb())
8683         weight = CW_SpecificReg;
8684       else
8685         weight = CW_Register;
8686     }
8687     break;
8688   case 'w':
8689     if (type->isFloatingPointTy())
8690       weight = CW_Register;
8691     break;
8692   }
8693   return weight;
8694 }
8695 
8696 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
8697 RCPair
8698 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8699                                                 EVT VT) const {
8700   if (Constraint.size() == 1) {
8701     // GCC ARM Constraint Letters
8702     switch (Constraint[0]) {
8703     case 'l': // Low regs or general regs.
8704       if (Subtarget->isThumb())
8705         return RCPair(0U, ARM::tGPRRegisterClass);
8706       else
8707         return RCPair(0U, ARM::GPRRegisterClass);
8708     case 'h': // High regs or no regs.
8709       if (Subtarget->isThumb())
8710         return RCPair(0U, ARM::hGPRRegisterClass);
8711       break;
8712     case 'r':
8713       return RCPair(0U, ARM::GPRRegisterClass);
8714     case 'w':
8715       if (VT == MVT::f32)
8716         return RCPair(0U, ARM::SPRRegisterClass);
8717       if (VT.getSizeInBits() == 64)
8718         return RCPair(0U, ARM::DPRRegisterClass);
8719       if (VT.getSizeInBits() == 128)
8720         return RCPair(0U, ARM::QPRRegisterClass);
8721       break;
8722     case 'x':
8723       if (VT == MVT::f32)
8724         return RCPair(0U, ARM::SPR_8RegisterClass);
8725       if (VT.getSizeInBits() == 64)
8726         return RCPair(0U, ARM::DPR_8RegisterClass);
8727       if (VT.getSizeInBits() == 128)
8728         return RCPair(0U, ARM::QPR_8RegisterClass);
8729       break;
8730     case 't':
8731       if (VT == MVT::f32)
8732         return RCPair(0U, ARM::SPRRegisterClass);
8733       break;
8734     }
8735   }
8736   if (StringRef("{cc}").equals_lower(Constraint))
8737     return std::make_pair(unsigned(ARM::CPSR), ARM::CCRRegisterClass);
8738 
8739   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8740 }
8741 
8742 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8743 /// vector.  If it is invalid, don't add anything to Ops.
8744 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8745                                                      std::string &Constraint,
8746                                                      std::vector<SDValue>&Ops,
8747                                                      SelectionDAG &DAG) const {
8748   SDValue Result(0, 0);
8749 
8750   // Currently only support length 1 constraints.
8751   if (Constraint.length() != 1) return;
8752 
8753   char ConstraintLetter = Constraint[0];
8754   switch (ConstraintLetter) {
8755   default: break;
8756   case 'j':
8757   case 'I': case 'J': case 'K': case 'L':
8758   case 'M': case 'N': case 'O':
8759     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
8760     if (!C)
8761       return;
8762 
8763     int64_t CVal64 = C->getSExtValue();
8764     int CVal = (int) CVal64;
8765     // None of these constraints allow values larger than 32 bits.  Check
8766     // that the value fits in an int.
8767     if (CVal != CVal64)
8768       return;
8769 
8770     switch (ConstraintLetter) {
8771       case 'j':
8772         // Constant suitable for movw, must be between 0 and
8773         // 65535.
8774         if (Subtarget->hasV6T2Ops())
8775           if (CVal >= 0 && CVal <= 65535)
8776             break;
8777         return;
8778       case 'I':
8779         if (Subtarget->isThumb1Only()) {
8780           // This must be a constant between 0 and 255, for ADD
8781           // immediates.
8782           if (CVal >= 0 && CVal <= 255)
8783             break;
8784         } else if (Subtarget->isThumb2()) {
8785           // A constant that can be used as an immediate value in a
8786           // data-processing instruction.
8787           if (ARM_AM::getT2SOImmVal(CVal) != -1)
8788             break;
8789         } else {
8790           // A constant that can be used as an immediate value in a
8791           // data-processing instruction.
8792           if (ARM_AM::getSOImmVal(CVal) != -1)
8793             break;
8794         }
8795         return;
8796 
8797       case 'J':
8798         if (Subtarget->isThumb()) {  // FIXME thumb2
8799           // This must be a constant between -255 and -1, for negated ADD
8800           // immediates. This can be used in GCC with an "n" modifier that
8801           // prints the negated value, for use with SUB instructions. It is
8802           // not useful otherwise but is implemented for compatibility.
8803           if (CVal >= -255 && CVal <= -1)
8804             break;
8805         } else {
8806           // This must be a constant between -4095 and 4095. It is not clear
8807           // what this constraint is intended for. Implemented for
8808           // compatibility with GCC.
8809           if (CVal >= -4095 && CVal <= 4095)
8810             break;
8811         }
8812         return;
8813 
8814       case 'K':
8815         if (Subtarget->isThumb1Only()) {
8816           // A 32-bit value where only one byte has a nonzero value. Exclude
8817           // zero to match GCC. This constraint is used by GCC internally for
8818           // constants that can be loaded with a move/shift combination.
8819           // It is not useful otherwise but is implemented for compatibility.
8820           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
8821             break;
8822         } else if (Subtarget->isThumb2()) {
8823           // A constant whose bitwise inverse can be used as an immediate
8824           // value in a data-processing instruction. This can be used in GCC
8825           // with a "B" modifier that prints the inverted value, for use with
8826           // BIC and MVN instructions. It is not useful otherwise but is
8827           // implemented for compatibility.
8828           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
8829             break;
8830         } else {
8831           // A constant whose bitwise inverse can be used as an immediate
8832           // value in a data-processing instruction. This can be used in GCC
8833           // with a "B" modifier that prints the inverted value, for use with
8834           // BIC and MVN instructions. It is not useful otherwise but is
8835           // implemented for compatibility.
8836           if (ARM_AM::getSOImmVal(~CVal) != -1)
8837             break;
8838         }
8839         return;
8840 
8841       case 'L':
8842         if (Subtarget->isThumb1Only()) {
8843           // This must be a constant between -7 and 7,
8844           // for 3-operand ADD/SUB immediate instructions.
8845           if (CVal >= -7 && CVal < 7)
8846             break;
8847         } else if (Subtarget->isThumb2()) {
8848           // A constant whose negation can be used as an immediate value in a
8849           // data-processing instruction. This can be used in GCC with an "n"
8850           // modifier that prints the negated value, for use with SUB
8851           // instructions. It is not useful otherwise but is implemented for
8852           // compatibility.
8853           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
8854             break;
8855         } else {
8856           // A constant whose negation can be used as an immediate value in a
8857           // data-processing instruction. This can be used in GCC with an "n"
8858           // modifier that prints the negated value, for use with SUB
8859           // instructions. It is not useful otherwise but is implemented for
8860           // compatibility.
8861           if (ARM_AM::getSOImmVal(-CVal) != -1)
8862             break;
8863         }
8864         return;
8865 
8866       case 'M':
8867         if (Subtarget->isThumb()) { // FIXME thumb2
8868           // This must be a multiple of 4 between 0 and 1020, for
8869           // ADD sp + immediate.
8870           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
8871             break;
8872         } else {
8873           // A power of two or a constant between 0 and 32.  This is used in
8874           // GCC for the shift amount on shifted register operands, but it is
8875           // useful in general for any shift amounts.
8876           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
8877             break;
8878         }
8879         return;
8880 
8881       case 'N':
8882         if (Subtarget->isThumb()) {  // FIXME thumb2
8883           // This must be a constant between 0 and 31, for shift amounts.
8884           if (CVal >= 0 && CVal <= 31)
8885             break;
8886         }
8887         return;
8888 
8889       case 'O':
8890         if (Subtarget->isThumb()) {  // FIXME thumb2
8891           // This must be a multiple of 4 between -508 and 508, for
8892           // ADD/SUB sp = sp + immediate.
8893           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
8894             break;
8895         }
8896         return;
8897     }
8898     Result = DAG.getTargetConstant(CVal, Op.getValueType());
8899     break;
8900   }
8901 
8902   if (Result.getNode()) {
8903     Ops.push_back(Result);
8904     return;
8905   }
8906   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
8907 }
8908 
8909 bool
8910 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
8911   // The ARM target isn't yet aware of offsets.
8912   return false;
8913 }
8914 
8915 bool ARM::isBitFieldInvertedMask(unsigned v) {
8916   if (v == 0xffffffff)
8917     return 0;
8918   // there can be 1's on either or both "outsides", all the "inside"
8919   // bits must be 0's
8920   unsigned int lsb = 0, msb = 31;
8921   while (v & (1 << msb)) --msb;
8922   while (v & (1 << lsb)) ++lsb;
8923   for (unsigned int i = lsb; i <= msb; ++i) {
8924     if (v & (1 << i))
8925       return 0;
8926   }
8927   return 1;
8928 }
8929 
8930 /// isFPImmLegal - Returns true if the target can instruction select the
8931 /// specified FP immediate natively. If false, the legalizer will
8932 /// materialize the FP immediate as a load from a constant pool.
8933 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
8934   if (!Subtarget->hasVFP3())
8935     return false;
8936   if (VT == MVT::f32)
8937     return ARM_AM::getFP32Imm(Imm) != -1;
8938   if (VT == MVT::f64)
8939     return ARM_AM::getFP64Imm(Imm) != -1;
8940   return false;
8941 }
8942 
8943 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
8944 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
8945 /// specified in the intrinsic calls.
8946 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
8947                                            const CallInst &I,
8948                                            unsigned Intrinsic) const {
8949   switch (Intrinsic) {
8950   case Intrinsic::arm_neon_vld1:
8951   case Intrinsic::arm_neon_vld2:
8952   case Intrinsic::arm_neon_vld3:
8953   case Intrinsic::arm_neon_vld4:
8954   case Intrinsic::arm_neon_vld2lane:
8955   case Intrinsic::arm_neon_vld3lane:
8956   case Intrinsic::arm_neon_vld4lane: {
8957     Info.opc = ISD::INTRINSIC_W_CHAIN;
8958     // Conservatively set memVT to the entire set of vectors loaded.
8959     uint64_t NumElts = getTargetData()->getTypeAllocSize(I.getType()) / 8;
8960     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8961     Info.ptrVal = I.getArgOperand(0);
8962     Info.offset = 0;
8963     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
8964     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
8965     Info.vol = false; // volatile loads with NEON intrinsics not supported
8966     Info.readMem = true;
8967     Info.writeMem = false;
8968     return true;
8969   }
8970   case Intrinsic::arm_neon_vst1:
8971   case Intrinsic::arm_neon_vst2:
8972   case Intrinsic::arm_neon_vst3:
8973   case Intrinsic::arm_neon_vst4:
8974   case Intrinsic::arm_neon_vst2lane:
8975   case Intrinsic::arm_neon_vst3lane:
8976   case Intrinsic::arm_neon_vst4lane: {
8977     Info.opc = ISD::INTRINSIC_VOID;
8978     // Conservatively set memVT to the entire set of vectors stored.
8979     unsigned NumElts = 0;
8980     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
8981       Type *ArgTy = I.getArgOperand(ArgI)->getType();
8982       if (!ArgTy->isVectorTy())
8983         break;
8984       NumElts += getTargetData()->getTypeAllocSize(ArgTy) / 8;
8985     }
8986     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8987     Info.ptrVal = I.getArgOperand(0);
8988     Info.offset = 0;
8989     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
8990     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
8991     Info.vol = false; // volatile stores with NEON intrinsics not supported
8992     Info.readMem = false;
8993     Info.writeMem = true;
8994     return true;
8995   }
8996   case Intrinsic::arm_strexd: {
8997     Info.opc = ISD::INTRINSIC_W_CHAIN;
8998     Info.memVT = MVT::i64;
8999     Info.ptrVal = I.getArgOperand(2);
9000     Info.offset = 0;
9001     Info.align = 8;
9002     Info.vol = true;
9003     Info.readMem = false;
9004     Info.writeMem = true;
9005     return true;
9006   }
9007   case Intrinsic::arm_ldrexd: {
9008     Info.opc = ISD::INTRINSIC_W_CHAIN;
9009     Info.memVT = MVT::i64;
9010     Info.ptrVal = I.getArgOperand(0);
9011     Info.offset = 0;
9012     Info.align = 8;
9013     Info.vol = true;
9014     Info.readMem = true;
9015     Info.writeMem = false;
9016     return true;
9017   }
9018   default:
9019     break;
9020   }
9021 
9022   return false;
9023 }
9024