ef165dc06e26cb37b03dd4f67a9d1dc7dcadecb7
[oota-llvm.git] / lib / Target / ARM / ARMISelLowering.cpp
1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "arm-isel"
16 #include "ARMISelLowering.h"
17 #include "ARM.h"
18 #include "ARMCallingConv.h"
19 #include "ARMConstantPoolValue.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "ARMPerfectShuffle.h"
22 #include "ARMSubtarget.h"
23 #include "ARMTargetMachine.h"
24 #include "ARMTargetObjectFile.h"
25 #include "MCTargetDesc/ARMAddressingModes.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/IntrinsicLowering.h"
30 #include "llvm/CodeGen/MachineBasicBlock.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalValue.h"
41 #include "llvm/IR/Instruction.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/IR/LLVMContext.h"
45 #include "llvm/IR/Type.h"
46 #include "llvm/MC/MCSectionMachO.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/raw_ostream.h"
51 #include "llvm/Target/TargetOptions.h"
52 #include <utility>
53 using namespace llvm;
54
55 STATISTIC(NumTailCalls, "Number of tail calls");
56 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
57 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
58
59 // This option should go away when tail calls fully work.
60 static cl::opt<bool>
61 EnableARMTailCalls("arm-tail-calls", cl::Hidden,
62   cl::desc("Generate tail calls (TEMPORARY OPTION)."),
63   cl::init(false));
64
65 cl::opt<bool>
66 EnableARMLongCalls("arm-long-calls", cl::Hidden,
67   cl::desc("Generate calls via indirect call instructions"),
68   cl::init(false));
69
70 static cl::opt<bool>
71 ARMInterworking("arm-interworking", cl::Hidden,
72   cl::desc("Enable / disable ARM interworking (for debugging only)"),
73   cl::init(true));
74
75 namespace {
76   class ARMCCState : public CCState {
77   public:
78     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
79                const TargetMachine &TM, SmallVectorImpl<CCValAssign> &locs,
80                LLVMContext &C, ParmContext PC)
81         : CCState(CC, isVarArg, MF, TM, locs, C) {
82       assert(((PC == Call) || (PC == Prologue)) &&
83              "ARMCCState users must specify whether their context is call"
84              "or prologue generation.");
85       CallOrPrologue = PC;
86     }
87   };
88 }
89
90 // The APCS parameter registers.
91 static const uint16_t GPRArgRegs[] = {
92   ARM::R0, ARM::R1, ARM::R2, ARM::R3
93 };
94
95 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
96                                        MVT PromotedBitwiseVT) {
97   if (VT != PromotedLdStVT) {
98     setOperationAction(ISD::LOAD, VT, Promote);
99     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
100
101     setOperationAction(ISD::STORE, VT, Promote);
102     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
103   }
104
105   MVT ElemTy = VT.getVectorElementType();
106   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
107     setOperationAction(ISD::SETCC, VT, Custom);
108   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
109   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
110   if (ElemTy == MVT::i32) {
111     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
112     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
113     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
114     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
115   } else {
116     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
117     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
118     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
119     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
120   }
121   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
122   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
123   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
124   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
125   setOperationAction(ISD::SELECT,            VT, Expand);
126   setOperationAction(ISD::SELECT_CC,         VT, Expand);
127   setOperationAction(ISD::VSELECT,           VT, Expand);
128   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
129   if (VT.isInteger()) {
130     setOperationAction(ISD::SHL, VT, Custom);
131     setOperationAction(ISD::SRA, VT, Custom);
132     setOperationAction(ISD::SRL, VT, Custom);
133   }
134
135   // Promote all bit-wise operations.
136   if (VT.isInteger() && VT != PromotedBitwiseVT) {
137     setOperationAction(ISD::AND, VT, Promote);
138     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
139     setOperationAction(ISD::OR,  VT, Promote);
140     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
141     setOperationAction(ISD::XOR, VT, Promote);
142     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
143   }
144
145   // Neon does not support vector divide/remainder operations.
146   setOperationAction(ISD::SDIV, VT, Expand);
147   setOperationAction(ISD::UDIV, VT, Expand);
148   setOperationAction(ISD::FDIV, VT, Expand);
149   setOperationAction(ISD::SREM, VT, Expand);
150   setOperationAction(ISD::UREM, VT, Expand);
151   setOperationAction(ISD::FREM, VT, Expand);
152 }
153
154 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
155   addRegisterClass(VT, &ARM::DPRRegClass);
156   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
157 }
158
159 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
160   addRegisterClass(VT, &ARM::QPRRegClass);
161   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
162 }
163
164 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
165   if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
166     return new TargetLoweringObjectFileMachO();
167
168   return new ARMElfTargetObjectFile();
169 }
170
171 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
172     : TargetLowering(TM, createTLOF(TM)) {
173   Subtarget = &TM.getSubtarget<ARMSubtarget>();
174   RegInfo = TM.getRegisterInfo();
175   Itins = TM.getInstrItineraryData();
176
177   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
178
179   if (Subtarget->isTargetIOS()) {
180     // Uses VFP for Thumb libfuncs if available.
181     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
182         Subtarget->hasARMOps()) {
183       // Single-precision floating-point arithmetic.
184       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
185       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
186       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
187       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
188
189       // Double-precision floating-point arithmetic.
190       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
191       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
192       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
193       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
194
195       // Single-precision comparisons.
196       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
197       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
198       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
199       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
200       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
201       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
202       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
203       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
204
205       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
206       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
207       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
208       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
209       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
210       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
211       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
212       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
213
214       // Double-precision comparisons.
215       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
216       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
217       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
218       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
219       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
220       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
221       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
222       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
223
224       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
225       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
226       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
227       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
228       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
229       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
230       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
231       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
232
233       // Floating-point to integer conversions.
234       // i64 conversions are done via library routines even when generating VFP
235       // instructions, so use the same ones.
236       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
237       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
238       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
239       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
240
241       // Conversions between floating types.
242       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
243       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
244
245       // Integer to floating-point conversions.
246       // i64 conversions are done via library routines even when generating VFP
247       // instructions, so use the same ones.
248       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
249       // e.g., __floatunsidf vs. __floatunssidfvfp.
250       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
251       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
252       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
253       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
254     }
255   }
256
257   // These libcalls are not available in 32-bit.
258   setLibcallName(RTLIB::SHL_I128, 0);
259   setLibcallName(RTLIB::SRL_I128, 0);
260   setLibcallName(RTLIB::SRA_I128, 0);
261
262   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetDarwin()) {
263     // Double-precision floating-point arithmetic helper functions
264     // RTABI chapter 4.1.2, Table 2
265     setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
266     setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
267     setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
268     setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
269     setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
270     setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
271     setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
272     setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
273
274     // Double-precision floating-point comparison helper functions
275     // RTABI chapter 4.1.2, Table 3
276     setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
277     setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
278     setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
279     setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
280     setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
281     setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
282     setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
283     setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
284     setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
285     setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
286     setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
287     setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
288     setLibcallName(RTLIB::UO_F64,  "__aeabi_dcmpun");
289     setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
290     setLibcallName(RTLIB::O_F64,   "__aeabi_dcmpun");
291     setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
292     setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
293     setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
294     setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
295     setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
296     setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
297     setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
298     setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
299     setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
300
301     // Single-precision floating-point arithmetic helper functions
302     // RTABI chapter 4.1.2, Table 4
303     setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
304     setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
305     setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
306     setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
307     setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
308     setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
309     setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
310     setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
311
312     // Single-precision floating-point comparison helper functions
313     // RTABI chapter 4.1.2, Table 5
314     setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
315     setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
316     setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
317     setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
318     setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
319     setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
320     setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
321     setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
322     setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
323     setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
324     setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
325     setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
326     setLibcallName(RTLIB::UO_F32,  "__aeabi_fcmpun");
327     setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
328     setLibcallName(RTLIB::O_F32,   "__aeabi_fcmpun");
329     setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
330     setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
331     setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
332     setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
333     setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
334     setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
335     setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
336     setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
337     setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
338
339     // Floating-point to integer conversions.
340     // RTABI chapter 4.1.2, Table 6
341     setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
342     setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
343     setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
344     setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
345     setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
346     setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
347     setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
348     setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
349     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
350     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
351     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
352     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
353     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
354     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
355     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
356     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
357
358     // Conversions between floating types.
359     // RTABI chapter 4.1.2, Table 7
360     setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
361     setLibcallName(RTLIB::FPEXT_F32_F64,   "__aeabi_f2d");
362     setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
363     setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
364
365     // Integer to floating-point conversions.
366     // RTABI chapter 4.1.2, Table 8
367     setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
368     setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
369     setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
370     setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
371     setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
372     setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
373     setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
374     setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
375     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
376     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
377     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
378     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
379     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
380     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
381     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
382     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
383
384     // Long long helper functions
385     // RTABI chapter 4.2, Table 9
386     setLibcallName(RTLIB::MUL_I64,  "__aeabi_lmul");
387     setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
388     setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
389     setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
390     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
391     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
392     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
393     setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
394     setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
395     setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
396
397     // Integer division functions
398     // RTABI chapter 4.3.1
399     setLibcallName(RTLIB::SDIV_I8,  "__aeabi_idiv");
400     setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
401     setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
402     setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
403     setLibcallName(RTLIB::UDIV_I8,  "__aeabi_uidiv");
404     setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
405     setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
406     setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
407     setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
408     setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
409     setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
410     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
411     setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
412     setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
413     setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
414     setLibcallCallingConv(RTLIB::UDIV_I64, 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     setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
422     setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
423     setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
424   }
425
426   // Use divmod compiler-rt calls for iOS 5.0 and later.
427   if (Subtarget->getTargetTriple().isiOS() &&
428       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
429     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
430     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
431   }
432
433   if (Subtarget->isThumb1Only())
434     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
435   else
436     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
437   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
438       !Subtarget->isThumb1Only()) {
439     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
440     if (!Subtarget->isFPOnlySP())
441       addRegisterClass(MVT::f64, &ARM::DPRRegClass);
442
443     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
444   }
445
446   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
447        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
448     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
449          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
450       setTruncStoreAction((MVT::SimpleValueType)VT,
451                           (MVT::SimpleValueType)InnerVT, Expand);
452     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
453     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
454     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
455   }
456
457   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
458   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
459
460   if (Subtarget->hasNEON()) {
461     addDRTypeForNEON(MVT::v2f32);
462     addDRTypeForNEON(MVT::v8i8);
463     addDRTypeForNEON(MVT::v4i16);
464     addDRTypeForNEON(MVT::v2i32);
465     addDRTypeForNEON(MVT::v1i64);
466
467     addQRTypeForNEON(MVT::v4f32);
468     addQRTypeForNEON(MVT::v2f64);
469     addQRTypeForNEON(MVT::v16i8);
470     addQRTypeForNEON(MVT::v8i16);
471     addQRTypeForNEON(MVT::v4i32);
472     addQRTypeForNEON(MVT::v2i64);
473
474     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
475     // neither Neon nor VFP support any arithmetic operations on it.
476     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
477     // supported for v4f32.
478     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
479     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
480     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
481     // FIXME: Code duplication: FDIV and FREM are expanded always, see
482     // ARMTargetLowering::addTypeForNEON method for details.
483     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
484     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
485     // FIXME: Create unittest.
486     // In another words, find a way when "copysign" appears in DAG with vector
487     // operands.
488     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
489     // FIXME: Code duplication: SETCC has custom operation action, see
490     // ARMTargetLowering::addTypeForNEON method for details.
491     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
492     // FIXME: Create unittest for FNEG and for FABS.
493     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
494     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
495     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
496     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
497     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
498     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
499     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
500     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
501     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
502     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
503     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
504     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
505     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
506     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
507     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
508     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
509     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
510     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
511     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
512
513     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
514     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
515     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
516     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
517     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
518     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
519     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
520     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
521     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
522     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
523     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
524     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
525     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
526     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
527     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
528
529     // Mark v2f32 intrinsics.
530     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
531     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
532     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
533     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
534     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
535     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
536     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
537     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
538     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
539     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
540     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
541     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
542     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
543     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
544     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
545
546     // Neon does not support some operations on v1i64 and v2i64 types.
547     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
548     // Custom handling for some quad-vector types to detect VMULL.
549     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
550     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
551     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
552     // Custom handling for some vector types to avoid expensive expansions
553     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
554     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
555     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
556     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
557     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
558     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
559     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
560     // a destination type that is wider than the source, and nor does
561     // it have a FP_TO_[SU]INT instruction with a narrower destination than
562     // source.
563     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
564     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
565     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
566     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
567
568     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
569     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
570
571     // NEON does not have single instruction CTPOP for vectors with element
572     // types wider than 8-bits.  However, custom lowering can leverage the
573     // v8i8/v16i8 vcnt instruction.
574     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
575     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
576     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
577     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
578
579     // NEON only has FMA instructions as of VFP4.
580     if (!Subtarget->hasVFP4()) {
581       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
582       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
583     }
584
585     setTargetDAGCombine(ISD::INTRINSIC_VOID);
586     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
587     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
588     setTargetDAGCombine(ISD::SHL);
589     setTargetDAGCombine(ISD::SRL);
590     setTargetDAGCombine(ISD::SRA);
591     setTargetDAGCombine(ISD::SIGN_EXTEND);
592     setTargetDAGCombine(ISD::ZERO_EXTEND);
593     setTargetDAGCombine(ISD::ANY_EXTEND);
594     setTargetDAGCombine(ISD::SELECT_CC);
595     setTargetDAGCombine(ISD::BUILD_VECTOR);
596     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
597     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
598     setTargetDAGCombine(ISD::STORE);
599     setTargetDAGCombine(ISD::FP_TO_SINT);
600     setTargetDAGCombine(ISD::FP_TO_UINT);
601     setTargetDAGCombine(ISD::FDIV);
602
603     // It is legal to extload from v4i8 to v4i16 or v4i32.
604     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
605                   MVT::v4i16, MVT::v2i16,
606                   MVT::v2i32};
607     for (unsigned i = 0; i < 6; ++i) {
608       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
609       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
610       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
611     }
612   }
613
614   // ARM and Thumb2 support UMLAL/SMLAL.
615   if (!Subtarget->isThumb1Only())
616     setTargetDAGCombine(ISD::ADDC);
617
618
619   computeRegisterProperties();
620
621   // ARM does not have f32 extending load.
622   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
623
624   // ARM does not have i1 sign extending load.
625   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
626
627   // ARM supports all 4 flavors of integer indexed load / store.
628   if (!Subtarget->isThumb1Only()) {
629     for (unsigned im = (unsigned)ISD::PRE_INC;
630          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
631       setIndexedLoadAction(im,  MVT::i1,  Legal);
632       setIndexedLoadAction(im,  MVT::i8,  Legal);
633       setIndexedLoadAction(im,  MVT::i16, Legal);
634       setIndexedLoadAction(im,  MVT::i32, Legal);
635       setIndexedStoreAction(im, MVT::i1,  Legal);
636       setIndexedStoreAction(im, MVT::i8,  Legal);
637       setIndexedStoreAction(im, MVT::i16, Legal);
638       setIndexedStoreAction(im, MVT::i32, Legal);
639     }
640   }
641
642   // i64 operation support.
643   setOperationAction(ISD::MUL,     MVT::i64, Expand);
644   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
645   if (Subtarget->isThumb1Only()) {
646     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
647     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
648   }
649   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
650       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
651     setOperationAction(ISD::MULHS, MVT::i32, Expand);
652
653   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
654   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
655   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
656   setOperationAction(ISD::SRL,       MVT::i64, Custom);
657   setOperationAction(ISD::SRA,       MVT::i64, Custom);
658
659   if (!Subtarget->isThumb1Only()) {
660     // FIXME: We should do this for Thumb1 as well.
661     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
662     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
663     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
664     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
665   }
666
667   // ARM does not have ROTL.
668   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
669   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
670   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
671   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
672     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
673
674   // These just redirect to CTTZ and CTLZ on ARM.
675   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
676   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
677
678   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
679
680   // Only ARMv6 has BSWAP.
681   if (!Subtarget->hasV6Ops())
682     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
683
684   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
685       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
686     // These are expanded into libcalls if the cpu doesn't have HW divider.
687     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
688     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
689   }
690
691   // FIXME: Also set divmod for SREM on EABI
692   setOperationAction(ISD::SREM,  MVT::i32, Expand);
693   setOperationAction(ISD::UREM,  MVT::i32, Expand);
694   // Register based DivRem for AEABI (RTABI 4.2)
695   if (Subtarget->isTargetAEABI()) {
696     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
697     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
698     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
699     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
700     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
701     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
702     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
703     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
704
705     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
706     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
707     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
708     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
709     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
710     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
711     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
712     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
713
714     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
715     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
716   } else {
717     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
718     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
719   }
720
721   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
722   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
723   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
724   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
725   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
726
727   setOperationAction(ISD::TRAP, MVT::Other, Legal);
728
729   // Use the default implementation.
730   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
731   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
732   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
733   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
734   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
735   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
736
737   if (!Subtarget->isTargetDarwin()) {
738     // Non-Darwin platforms may return values in these registers via the
739     // personality function.
740     setExceptionPointerRegister(ARM::R0);
741     setExceptionSelectorRegister(ARM::R1);
742   }
743
744   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
745   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
746   // the default expansion.
747   if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
748     // ATOMIC_FENCE needs custom lowering; the other 32-bit ones are legal and
749     // handled normally.
750     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
751     // Custom lowering for 64-bit ops
752     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i64, Custom);
753     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i64, Custom);
754     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i64, Custom);
755     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i64, Custom);
756     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i64, Custom);
757     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i64, Custom);
758     setOperationAction(ISD::ATOMIC_LOAD_MIN,  MVT::i64, Custom);
759     setOperationAction(ISD::ATOMIC_LOAD_MAX,  MVT::i64, Custom);
760     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
761     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
762     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
763     // On v8, we have particularly efficient implementations of atomic fences
764     // if they can be combined with nearby atomic loads and stores.
765     if (!Subtarget->hasV8Ops()) {
766       // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
767       setInsertFencesForAtomic(true);
768     }
769     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
770   } else {
771     // If there's anything we can use as a barrier, go through custom lowering
772     // for ATOMIC_FENCE.
773     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
774                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
775
776     // Set them all for expansion, which will force libcalls.
777     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
778     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
779     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
780     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
781     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
782     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
783     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
784     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
785     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
786     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
787     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
788     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
789     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
790     // Unordered/Monotonic case.
791     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
792     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
793   }
794
795   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
796
797   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
798   if (!Subtarget->hasV6Ops()) {
799     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
800     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
801   }
802   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
803
804   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
805       !Subtarget->isThumb1Only()) {
806     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
807     // iff target supports vfp2.
808     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
809     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
810   }
811
812   // We want to custom lower some of our intrinsics.
813   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
814   if (Subtarget->isTargetDarwin()) {
815     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
816     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
817     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
818   }
819
820   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
821   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
822   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
823   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
824   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
825   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
826   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
827   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
828   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
829
830   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
831   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
832   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
833   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
834   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
835
836   // We don't support sin/cos/fmod/copysign/pow
837   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
838   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
839   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
840   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
841   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
842   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
843   setOperationAction(ISD::FREM,      MVT::f64, Expand);
844   setOperationAction(ISD::FREM,      MVT::f32, Expand);
845   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
846       !Subtarget->isThumb1Only()) {
847     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
848     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
849   }
850   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
851   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
852
853   if (!Subtarget->hasVFP4()) {
854     setOperationAction(ISD::FMA, MVT::f64, Expand);
855     setOperationAction(ISD::FMA, MVT::f32, Expand);
856   }
857
858   // Various VFP goodness
859   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
860     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
861     if (Subtarget->hasVFP2()) {
862       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
863       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
864       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
865       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
866     }
867     // Special handling for half-precision FP.
868     if (!Subtarget->hasFP16()) {
869       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
870       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
871     }
872   }
873       
874   // Combine sin / cos into one node or libcall if possible.
875   if (Subtarget->hasSinCos()) {
876     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
877     setLibcallName(RTLIB::SINCOS_F64, "sincos");
878     if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
879       // For iOS, we don't want to the normal expansion of a libcall to
880       // sincos. We want to issue a libcall to __sincos_stret.
881       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
882       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
883     }
884   }
885
886   // We have target-specific dag combine patterns for the following nodes:
887   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
888   setTargetDAGCombine(ISD::ADD);
889   setTargetDAGCombine(ISD::SUB);
890   setTargetDAGCombine(ISD::MUL);
891   setTargetDAGCombine(ISD::AND);
892   setTargetDAGCombine(ISD::OR);
893   setTargetDAGCombine(ISD::XOR);
894
895   if (Subtarget->hasV6Ops())
896     setTargetDAGCombine(ISD::SRL);
897
898   setStackPointerRegisterToSaveRestore(ARM::SP);
899
900   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
901       !Subtarget->hasVFP2())
902     setSchedulingPreference(Sched::RegPressure);
903   else
904     setSchedulingPreference(Sched::Hybrid);
905
906   //// temporary - rewrite interface to use type
907   MaxStoresPerMemset = 8;
908   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
909   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
910   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
911   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
912   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
913
914   // On ARM arguments smaller than 4 bytes are extended, so all arguments
915   // are at least 4 bytes aligned.
916   setMinStackArgumentAlignment(4);
917
918   // Prefer likely predicted branches to selects on out-of-order cores.
919   PredictableSelectIsExpensive = Subtarget->isLikeA9();
920
921   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
922 }
923
924 static void getExclusiveOperation(unsigned Size, AtomicOrdering Ord,
925                                   bool isThumb2, unsigned &LdrOpc,
926                                   unsigned &StrOpc) {
927   static const unsigned LoadBares[4][2] =  {{ARM::LDREXB, ARM::t2LDREXB},
928                                             {ARM::LDREXH, ARM::t2LDREXH},
929                                             {ARM::LDREX,  ARM::t2LDREX},
930                                             {ARM::LDREXD, ARM::t2LDREXD}};
931   static const unsigned LoadAcqs[4][2] =   {{ARM::LDAEXB, ARM::t2LDAEXB},
932                                             {ARM::LDAEXH, ARM::t2LDAEXH},
933                                             {ARM::LDAEX,  ARM::t2LDAEX},
934                                             {ARM::LDAEXD, ARM::t2LDAEXD}};
935   static const unsigned StoreBares[4][2] = {{ARM::STREXB, ARM::t2STREXB},
936                                             {ARM::STREXH, ARM::t2STREXH},
937                                             {ARM::STREX,  ARM::t2STREX},
938                                             {ARM::STREXD, ARM::t2STREXD}};
939   static const unsigned StoreRels[4][2] =  {{ARM::STLEXB, ARM::t2STLEXB},
940                                             {ARM::STLEXH, ARM::t2STLEXH},
941                                             {ARM::STLEX,  ARM::t2STLEX},
942                                             {ARM::STLEXD, ARM::t2STLEXD}};
943
944   const unsigned (*LoadOps)[2], (*StoreOps)[2];
945   if (Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent)
946     LoadOps = LoadAcqs;
947   else
948     LoadOps = LoadBares;
949
950   if (Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent)
951     StoreOps = StoreRels;
952   else
953     StoreOps = StoreBares;
954
955   assert(isPowerOf2_32(Size) && Size <= 8 &&
956          "unsupported size for atomic binary op!");
957
958   LdrOpc = LoadOps[Log2_32(Size)][isThumb2];
959   StrOpc = StoreOps[Log2_32(Size)][isThumb2];
960 }
961
962 // FIXME: It might make sense to define the representative register class as the
963 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
964 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
965 // SPR's representative would be DPR_VFP2. This should work well if register
966 // pressure tracking were modified such that a register use would increment the
967 // pressure of the register class's representative and all of it's super
968 // classes' representatives transitively. We have not implemented this because
969 // of the difficulty prior to coalescing of modeling operand register classes
970 // due to the common occurrence of cross class copies and subregister insertions
971 // and extractions.
972 std::pair<const TargetRegisterClass*, uint8_t>
973 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
974   const TargetRegisterClass *RRC = 0;
975   uint8_t Cost = 1;
976   switch (VT.SimpleTy) {
977   default:
978     return TargetLowering::findRepresentativeClass(VT);
979   // Use DPR as representative register class for all floating point
980   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
981   // the cost is 1 for both f32 and f64.
982   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
983   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
984     RRC = &ARM::DPRRegClass;
985     // When NEON is used for SP, only half of the register file is available
986     // because operations that define both SP and DP results will be constrained
987     // to the VFP2 class (D0-D15). We currently model this constraint prior to
988     // coalescing by double-counting the SP regs. See the FIXME above.
989     if (Subtarget->useNEONForSinglePrecisionFP())
990       Cost = 2;
991     break;
992   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
993   case MVT::v4f32: case MVT::v2f64:
994     RRC = &ARM::DPRRegClass;
995     Cost = 2;
996     break;
997   case MVT::v4i64:
998     RRC = &ARM::DPRRegClass;
999     Cost = 4;
1000     break;
1001   case MVT::v8i64:
1002     RRC = &ARM::DPRRegClass;
1003     Cost = 8;
1004     break;
1005   }
1006   return std::make_pair(RRC, Cost);
1007 }
1008
1009 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1010   switch (Opcode) {
1011   default: return 0;
1012   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1013   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1014   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1015   case ARMISD::CALL:          return "ARMISD::CALL";
1016   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1017   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1018   case ARMISD::tCALL:         return "ARMISD::tCALL";
1019   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1020   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1021   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1022   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1023   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1024   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1025   case ARMISD::CMP:           return "ARMISD::CMP";
1026   case ARMISD::CMN:           return "ARMISD::CMN";
1027   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1028   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1029   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1030   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1031   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1032
1033   case ARMISD::CMOV:          return "ARMISD::CMOV";
1034
1035   case ARMISD::RBIT:          return "ARMISD::RBIT";
1036
1037   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
1038   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
1039   case ARMISD::SITOF:         return "ARMISD::SITOF";
1040   case ARMISD::UITOF:         return "ARMISD::UITOF";
1041
1042   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1043   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1044   case ARMISD::RRX:           return "ARMISD::RRX";
1045
1046   case ARMISD::ADDC:          return "ARMISD::ADDC";
1047   case ARMISD::ADDE:          return "ARMISD::ADDE";
1048   case ARMISD::SUBC:          return "ARMISD::SUBC";
1049   case ARMISD::SUBE:          return "ARMISD::SUBE";
1050
1051   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1052   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1053
1054   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1055   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1056
1057   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1058
1059   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1060
1061   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1062
1063   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1064
1065   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1066
1067   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1068   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1069   case ARMISD::VCGE:          return "ARMISD::VCGE";
1070   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1071   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1072   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1073   case ARMISD::VCGT:          return "ARMISD::VCGT";
1074   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1075   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1076   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1077   case ARMISD::VTST:          return "ARMISD::VTST";
1078
1079   case ARMISD::VSHL:          return "ARMISD::VSHL";
1080   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1081   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1082   case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
1083   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
1084   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
1085   case ARMISD::VSHRN:         return "ARMISD::VSHRN";
1086   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1087   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1088   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1089   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1090   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1091   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1092   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1093   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1094   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1095   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1096   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1097   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1098   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1099   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1100   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1101   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1102   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1103   case ARMISD::VDUP:          return "ARMISD::VDUP";
1104   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1105   case ARMISD::VEXT:          return "ARMISD::VEXT";
1106   case ARMISD::VREV64:        return "ARMISD::VREV64";
1107   case ARMISD::VREV32:        return "ARMISD::VREV32";
1108   case ARMISD::VREV16:        return "ARMISD::VREV16";
1109   case ARMISD::VZIP:          return "ARMISD::VZIP";
1110   case ARMISD::VUZP:          return "ARMISD::VUZP";
1111   case ARMISD::VTRN:          return "ARMISD::VTRN";
1112   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1113   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1114   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1115   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1116   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1117   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1118   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1119   case ARMISD::FMAX:          return "ARMISD::FMAX";
1120   case ARMISD::FMIN:          return "ARMISD::FMIN";
1121   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1122   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1123   case ARMISD::BFI:           return "ARMISD::BFI";
1124   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1125   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1126   case ARMISD::VBSL:          return "ARMISD::VBSL";
1127   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1128   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1129   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1130   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1131   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1132   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1133   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1134   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1135   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1136   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1137   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1138   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1139   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1140   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1141   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1142   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1143   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1144   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1145   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1146   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1147   }
1148 }
1149
1150 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1151   if (!VT.isVector()) return getPointerTy();
1152   return VT.changeVectorElementTypeToInteger();
1153 }
1154
1155 /// getRegClassFor - Return the register class that should be used for the
1156 /// specified value type.
1157 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1158   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1159   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1160   // load / store 4 to 8 consecutive D registers.
1161   if (Subtarget->hasNEON()) {
1162     if (VT == MVT::v4i64)
1163       return &ARM::QQPRRegClass;
1164     if (VT == MVT::v8i64)
1165       return &ARM::QQQQPRRegClass;
1166   }
1167   return TargetLowering::getRegClassFor(VT);
1168 }
1169
1170 // Create a fast isel object.
1171 FastISel *
1172 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1173                                   const TargetLibraryInfo *libInfo) const {
1174   return ARM::createFastISel(funcInfo, libInfo);
1175 }
1176
1177 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1178 /// be used for loads / stores from the global.
1179 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1180   return (Subtarget->isThumb1Only() ? 127 : 4095);
1181 }
1182
1183 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1184   unsigned NumVals = N->getNumValues();
1185   if (!NumVals)
1186     return Sched::RegPressure;
1187
1188   for (unsigned i = 0; i != NumVals; ++i) {
1189     EVT VT = N->getValueType(i);
1190     if (VT == MVT::Glue || VT == MVT::Other)
1191       continue;
1192     if (VT.isFloatingPoint() || VT.isVector())
1193       return Sched::ILP;
1194   }
1195
1196   if (!N->isMachineOpcode())
1197     return Sched::RegPressure;
1198
1199   // Load are scheduled for latency even if there instruction itinerary
1200   // is not available.
1201   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1202   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1203
1204   if (MCID.getNumDefs() == 0)
1205     return Sched::RegPressure;
1206   if (!Itins->isEmpty() &&
1207       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1208     return Sched::ILP;
1209
1210   return Sched::RegPressure;
1211 }
1212
1213 //===----------------------------------------------------------------------===//
1214 // Lowering Code
1215 //===----------------------------------------------------------------------===//
1216
1217 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1218 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1219   switch (CC) {
1220   default: llvm_unreachable("Unknown condition code!");
1221   case ISD::SETNE:  return ARMCC::NE;
1222   case ISD::SETEQ:  return ARMCC::EQ;
1223   case ISD::SETGT:  return ARMCC::GT;
1224   case ISD::SETGE:  return ARMCC::GE;
1225   case ISD::SETLT:  return ARMCC::LT;
1226   case ISD::SETLE:  return ARMCC::LE;
1227   case ISD::SETUGT: return ARMCC::HI;
1228   case ISD::SETUGE: return ARMCC::HS;
1229   case ISD::SETULT: return ARMCC::LO;
1230   case ISD::SETULE: return ARMCC::LS;
1231   }
1232 }
1233
1234 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1235 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1236                         ARMCC::CondCodes &CondCode2) {
1237   CondCode2 = ARMCC::AL;
1238   switch (CC) {
1239   default: llvm_unreachable("Unknown FP condition!");
1240   case ISD::SETEQ:
1241   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1242   case ISD::SETGT:
1243   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1244   case ISD::SETGE:
1245   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1246   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1247   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1248   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1249   case ISD::SETO:   CondCode = ARMCC::VC; break;
1250   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1251   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1252   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1253   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1254   case ISD::SETLT:
1255   case ISD::SETULT: CondCode = ARMCC::LT; break;
1256   case ISD::SETLE:
1257   case ISD::SETULE: CondCode = ARMCC::LE; break;
1258   case ISD::SETNE:
1259   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1260   }
1261 }
1262
1263 //===----------------------------------------------------------------------===//
1264 //                      Calling Convention Implementation
1265 //===----------------------------------------------------------------------===//
1266
1267 #include "ARMGenCallingConv.inc"
1268
1269 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1270 /// given CallingConvention value.
1271 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1272                                                  bool Return,
1273                                                  bool isVarArg) const {
1274   switch (CC) {
1275   default:
1276     llvm_unreachable("Unsupported calling convention");
1277   case CallingConv::Fast:
1278     if (Subtarget->hasVFP2() && !isVarArg) {
1279       if (!Subtarget->isAAPCS_ABI())
1280         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1281       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1282       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1283     }
1284     // Fallthrough
1285   case CallingConv::C: {
1286     // Use target triple & subtarget features to do actual dispatch.
1287     if (!Subtarget->isAAPCS_ABI())
1288       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1289     else if (Subtarget->hasVFP2() &&
1290              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1291              !isVarArg)
1292       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1293     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1294   }
1295   case CallingConv::ARM_AAPCS_VFP:
1296     if (!isVarArg)
1297       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1298     // Fallthrough
1299   case CallingConv::ARM_AAPCS:
1300     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1301   case CallingConv::ARM_APCS:
1302     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1303   case CallingConv::GHC:
1304     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1305   }
1306 }
1307
1308 /// LowerCallResult - Lower the result values of a call into the
1309 /// appropriate copies out of appropriate physical registers.
1310 SDValue
1311 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1312                                    CallingConv::ID CallConv, bool isVarArg,
1313                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1314                                    SDLoc dl, SelectionDAG &DAG,
1315                                    SmallVectorImpl<SDValue> &InVals,
1316                                    bool isThisReturn, SDValue ThisVal) const {
1317
1318   // Assign locations to each value returned by this call.
1319   SmallVector<CCValAssign, 16> RVLocs;
1320   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1321                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1322   CCInfo.AnalyzeCallResult(Ins,
1323                            CCAssignFnForNode(CallConv, /* Return*/ true,
1324                                              isVarArg));
1325
1326   // Copy all of the result registers out of their specified physreg.
1327   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1328     CCValAssign VA = RVLocs[i];
1329
1330     // Pass 'this' value directly from the argument to return value, to avoid
1331     // reg unit interference
1332     if (i == 0 && isThisReturn) {
1333       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1334              "unexpected return calling convention register assignment");
1335       InVals.push_back(ThisVal);
1336       continue;
1337     }
1338
1339     SDValue Val;
1340     if (VA.needsCustom()) {
1341       // Handle f64 or half of a v2f64.
1342       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1343                                       InFlag);
1344       Chain = Lo.getValue(1);
1345       InFlag = Lo.getValue(2);
1346       VA = RVLocs[++i]; // skip ahead to next loc
1347       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1348                                       InFlag);
1349       Chain = Hi.getValue(1);
1350       InFlag = Hi.getValue(2);
1351       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1352
1353       if (VA.getLocVT() == MVT::v2f64) {
1354         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1355         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1356                           DAG.getConstant(0, MVT::i32));
1357
1358         VA = RVLocs[++i]; // skip ahead to next loc
1359         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1360         Chain = Lo.getValue(1);
1361         InFlag = Lo.getValue(2);
1362         VA = RVLocs[++i]; // skip ahead to next loc
1363         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1364         Chain = Hi.getValue(1);
1365         InFlag = Hi.getValue(2);
1366         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1367         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1368                           DAG.getConstant(1, MVT::i32));
1369       }
1370     } else {
1371       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1372                                InFlag);
1373       Chain = Val.getValue(1);
1374       InFlag = Val.getValue(2);
1375     }
1376
1377     switch (VA.getLocInfo()) {
1378     default: llvm_unreachable("Unknown loc info!");
1379     case CCValAssign::Full: break;
1380     case CCValAssign::BCvt:
1381       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1382       break;
1383     }
1384
1385     InVals.push_back(Val);
1386   }
1387
1388   return Chain;
1389 }
1390
1391 /// LowerMemOpCallTo - Store the argument to the stack.
1392 SDValue
1393 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1394                                     SDValue StackPtr, SDValue Arg,
1395                                     SDLoc dl, SelectionDAG &DAG,
1396                                     const CCValAssign &VA,
1397                                     ISD::ArgFlagsTy Flags) const {
1398   unsigned LocMemOffset = VA.getLocMemOffset();
1399   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1400   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1401   return DAG.getStore(Chain, dl, Arg, PtrOff,
1402                       MachinePointerInfo::getStack(LocMemOffset),
1403                       false, false, 0);
1404 }
1405
1406 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1407                                          SDValue Chain, SDValue &Arg,
1408                                          RegsToPassVector &RegsToPass,
1409                                          CCValAssign &VA, CCValAssign &NextVA,
1410                                          SDValue &StackPtr,
1411                                          SmallVectorImpl<SDValue> &MemOpChains,
1412                                          ISD::ArgFlagsTy Flags) const {
1413
1414   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1415                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1416   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1417
1418   if (NextVA.isRegLoc())
1419     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1420   else {
1421     assert(NextVA.isMemLoc());
1422     if (StackPtr.getNode() == 0)
1423       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1424
1425     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1426                                            dl, DAG, NextVA,
1427                                            Flags));
1428   }
1429 }
1430
1431 /// LowerCall - Lowering a call into a callseq_start <-
1432 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1433 /// nodes.
1434 SDValue
1435 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1436                              SmallVectorImpl<SDValue> &InVals) const {
1437   SelectionDAG &DAG                     = CLI.DAG;
1438   SDLoc &dl                          = CLI.DL;
1439   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1440   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1441   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1442   SDValue Chain                         = CLI.Chain;
1443   SDValue Callee                        = CLI.Callee;
1444   bool &isTailCall                      = CLI.IsTailCall;
1445   CallingConv::ID CallConv              = CLI.CallConv;
1446   bool doesNotRet                       = CLI.DoesNotReturn;
1447   bool isVarArg                         = CLI.IsVarArg;
1448
1449   MachineFunction &MF = DAG.getMachineFunction();
1450   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1451   bool isThisReturn   = false;
1452   bool isSibCall      = false;
1453   // Disable tail calls if they're not supported.
1454   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1455     isTailCall = false;
1456   if (isTailCall) {
1457     // Check if it's really possible to do a tail call.
1458     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1459                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1460                                                    Outs, OutVals, Ins, DAG);
1461     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1462     // detected sibcalls.
1463     if (isTailCall) {
1464       ++NumTailCalls;
1465       isSibCall = true;
1466     }
1467   }
1468
1469   // Analyze operands of the call, assigning locations to each operand.
1470   SmallVector<CCValAssign, 16> ArgLocs;
1471   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1472                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1473   CCInfo.AnalyzeCallOperands(Outs,
1474                              CCAssignFnForNode(CallConv, /* Return*/ false,
1475                                                isVarArg));
1476
1477   // Get a count of how many bytes are to be pushed on the stack.
1478   unsigned NumBytes = CCInfo.getNextStackOffset();
1479
1480   // For tail calls, memory operands are available in our caller's stack.
1481   if (isSibCall)
1482     NumBytes = 0;
1483
1484   // Adjust the stack pointer for the new arguments...
1485   // These operations are automatically eliminated by the prolog/epilog pass
1486   if (!isSibCall)
1487     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1488                                  dl);
1489
1490   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1491
1492   RegsToPassVector RegsToPass;
1493   SmallVector<SDValue, 8> MemOpChains;
1494
1495   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1496   // of tail call optimization, arguments are handled later.
1497   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1498        i != e;
1499        ++i, ++realArgIdx) {
1500     CCValAssign &VA = ArgLocs[i];
1501     SDValue Arg = OutVals[realArgIdx];
1502     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1503     bool isByVal = Flags.isByVal();
1504
1505     // Promote the value if needed.
1506     switch (VA.getLocInfo()) {
1507     default: llvm_unreachable("Unknown loc info!");
1508     case CCValAssign::Full: break;
1509     case CCValAssign::SExt:
1510       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1511       break;
1512     case CCValAssign::ZExt:
1513       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1514       break;
1515     case CCValAssign::AExt:
1516       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1517       break;
1518     case CCValAssign::BCvt:
1519       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1520       break;
1521     }
1522
1523     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1524     if (VA.needsCustom()) {
1525       if (VA.getLocVT() == MVT::v2f64) {
1526         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1527                                   DAG.getConstant(0, MVT::i32));
1528         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1529                                   DAG.getConstant(1, MVT::i32));
1530
1531         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1532                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1533
1534         VA = ArgLocs[++i]; // skip ahead to next loc
1535         if (VA.isRegLoc()) {
1536           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1537                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1538         } else {
1539           assert(VA.isMemLoc());
1540
1541           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1542                                                  dl, DAG, VA, Flags));
1543         }
1544       } else {
1545         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1546                          StackPtr, MemOpChains, Flags);
1547       }
1548     } else if (VA.isRegLoc()) {
1549       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1550         assert(VA.getLocVT() == MVT::i32 &&
1551                "unexpected calling convention register assignment");
1552         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1553                "unexpected use of 'returned'");
1554         isThisReturn = true;
1555       }
1556       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1557     } else if (isByVal) {
1558       assert(VA.isMemLoc());
1559       unsigned offset = 0;
1560
1561       // True if this byval aggregate will be split between registers
1562       // and memory.
1563       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1564       unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1565
1566       if (CurByValIdx < ByValArgsCount) {
1567
1568         unsigned RegBegin, RegEnd;
1569         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1570
1571         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1572         unsigned int i, j;
1573         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1574           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1575           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1576           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1577                                      MachinePointerInfo(),
1578                                      false, false, false,
1579                                      DAG.InferPtrAlignment(AddArg));
1580           MemOpChains.push_back(Load.getValue(1));
1581           RegsToPass.push_back(std::make_pair(j, Load));
1582         }
1583
1584         // If parameter size outsides register area, "offset" value
1585         // helps us to calculate stack slot for remained part properly.
1586         offset = RegEnd - RegBegin;
1587
1588         CCInfo.nextInRegsParam();
1589       }
1590
1591       if (Flags.getByValSize() > 4*offset) {
1592         unsigned LocMemOffset = VA.getLocMemOffset();
1593         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1594         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1595                                   StkPtrOff);
1596         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1597         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1598         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1599                                            MVT::i32);
1600         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1601
1602         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1603         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1604         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1605                                           Ops, array_lengthof(Ops)));
1606       }
1607     } else if (!isSibCall) {
1608       assert(VA.isMemLoc());
1609
1610       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1611                                              dl, DAG, VA, Flags));
1612     }
1613   }
1614
1615   if (!MemOpChains.empty())
1616     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1617                         &MemOpChains[0], MemOpChains.size());
1618
1619   // Build a sequence of copy-to-reg nodes chained together with token chain
1620   // and flag operands which copy the outgoing args into the appropriate regs.
1621   SDValue InFlag;
1622   // Tail call byval lowering might overwrite argument registers so in case of
1623   // tail call optimization the copies to registers are lowered later.
1624   if (!isTailCall)
1625     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1626       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1627                                RegsToPass[i].second, InFlag);
1628       InFlag = Chain.getValue(1);
1629     }
1630
1631   // For tail calls lower the arguments to the 'real' stack slot.
1632   if (isTailCall) {
1633     // Force all the incoming stack arguments to be loaded from the stack
1634     // before any new outgoing arguments are stored to the stack, because the
1635     // outgoing stack slots may alias the incoming argument stack slots, and
1636     // the alias isn't otherwise explicit. This is slightly more conservative
1637     // than necessary, because it means that each store effectively depends
1638     // on every argument instead of just those arguments it would clobber.
1639
1640     // Do not flag preceding copytoreg stuff together with the following stuff.
1641     InFlag = SDValue();
1642     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1643       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1644                                RegsToPass[i].second, InFlag);
1645       InFlag = Chain.getValue(1);
1646     }
1647     InFlag = SDValue();
1648   }
1649
1650   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1651   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1652   // node so that legalize doesn't hack it.
1653   bool isDirect = false;
1654   bool isARMFunc = false;
1655   bool isLocalARMFunc = false;
1656   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1657
1658   if (EnableARMLongCalls) {
1659     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1660             && "long-calls with non-static relocation model!");
1661     // Handle a global address or an external symbol. If it's not one of
1662     // those, the target's already in a register, so we don't need to do
1663     // anything extra.
1664     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1665       const GlobalValue *GV = G->getGlobal();
1666       // Create a constant pool entry for the callee address
1667       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1668       ARMConstantPoolValue *CPV =
1669         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1670
1671       // Get the address of the callee into a register
1672       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1673       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1674       Callee = DAG.getLoad(getPointerTy(), dl,
1675                            DAG.getEntryNode(), CPAddr,
1676                            MachinePointerInfo::getConstantPool(),
1677                            false, false, false, 0);
1678     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1679       const char *Sym = S->getSymbol();
1680
1681       // Create a constant pool entry for the callee address
1682       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1683       ARMConstantPoolValue *CPV =
1684         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1685                                       ARMPCLabelIndex, 0);
1686       // Get the address of the callee into a register
1687       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1688       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1689       Callee = DAG.getLoad(getPointerTy(), dl,
1690                            DAG.getEntryNode(), CPAddr,
1691                            MachinePointerInfo::getConstantPool(),
1692                            false, false, false, 0);
1693     }
1694   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1695     const GlobalValue *GV = G->getGlobal();
1696     isDirect = true;
1697     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1698     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1699                    getTargetMachine().getRelocationModel() != Reloc::Static;
1700     isARMFunc = !Subtarget->isThumb() || isStub;
1701     // ARM call to a local ARM function is predicable.
1702     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1703     // tBX takes a register source operand.
1704     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1705       assert(Subtarget->isTargetDarwin() && "WrapperPIC use on non-Darwin?");
1706       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1707                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy()));
1708     } else {
1709       // On ELF targets for PIC code, direct calls should go through the PLT
1710       unsigned OpFlags = 0;
1711       if (Subtarget->isTargetELF() &&
1712           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1713         OpFlags = ARMII::MO_PLT;
1714       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1715     }
1716   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1717     isDirect = true;
1718     bool isStub = Subtarget->isTargetDarwin() &&
1719                   getTargetMachine().getRelocationModel() != Reloc::Static;
1720     isARMFunc = !Subtarget->isThumb() || isStub;
1721     // tBX takes a register source operand.
1722     const char *Sym = S->getSymbol();
1723     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1724       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1725       ARMConstantPoolValue *CPV =
1726         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1727                                       ARMPCLabelIndex, 4);
1728       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1729       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1730       Callee = DAG.getLoad(getPointerTy(), dl,
1731                            DAG.getEntryNode(), CPAddr,
1732                            MachinePointerInfo::getConstantPool(),
1733                            false, false, false, 0);
1734       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1735       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1736                            getPointerTy(), Callee, PICLabel);
1737     } else {
1738       unsigned OpFlags = 0;
1739       // On ELF targets for PIC code, direct calls should go through the PLT
1740       if (Subtarget->isTargetELF() &&
1741                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1742         OpFlags = ARMII::MO_PLT;
1743       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1744     }
1745   }
1746
1747   // FIXME: handle tail calls differently.
1748   unsigned CallOpc;
1749   bool HasMinSizeAttr = Subtarget->isMinSize();
1750   if (Subtarget->isThumb()) {
1751     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1752       CallOpc = ARMISD::CALL_NOLINK;
1753     else
1754       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1755   } else {
1756     if (!isDirect && !Subtarget->hasV5TOps())
1757       CallOpc = ARMISD::CALL_NOLINK;
1758     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1759                // Emit regular call when code size is the priority
1760                !HasMinSizeAttr)
1761       // "mov lr, pc; b _foo" to avoid confusing the RSP
1762       CallOpc = ARMISD::CALL_NOLINK;
1763     else
1764       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1765   }
1766
1767   std::vector<SDValue> Ops;
1768   Ops.push_back(Chain);
1769   Ops.push_back(Callee);
1770
1771   // Add argument registers to the end of the list so that they are known live
1772   // into the call.
1773   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1774     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1775                                   RegsToPass[i].second.getValueType()));
1776
1777   // Add a register mask operand representing the call-preserved registers.
1778   if (!isTailCall) {
1779     const uint32_t *Mask;
1780     const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1781     const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1782     if (isThisReturn) {
1783       // For 'this' returns, use the R0-preserving mask if applicable
1784       Mask = ARI->getThisReturnPreservedMask(CallConv);
1785       if (!Mask) {
1786         // Set isThisReturn to false if the calling convention is not one that
1787         // allows 'returned' to be modeled in this way, so LowerCallResult does
1788         // not try to pass 'this' straight through
1789         isThisReturn = false;
1790         Mask = ARI->getCallPreservedMask(CallConv);
1791       }
1792     } else
1793       Mask = ARI->getCallPreservedMask(CallConv);
1794
1795     assert(Mask && "Missing call preserved mask for calling convention");
1796     Ops.push_back(DAG.getRegisterMask(Mask));
1797   }
1798
1799   if (InFlag.getNode())
1800     Ops.push_back(InFlag);
1801
1802   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1803   if (isTailCall)
1804     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1805
1806   // Returns a chain and a flag for retval copy to use.
1807   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1808   InFlag = Chain.getValue(1);
1809
1810   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1811                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1812   if (!Ins.empty())
1813     InFlag = Chain.getValue(1);
1814
1815   // Handle result values, copying them out of physregs into vregs that we
1816   // return.
1817   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1818                          InVals, isThisReturn,
1819                          isThisReturn ? OutVals[0] : SDValue());
1820 }
1821
1822 /// HandleByVal - Every parameter *after* a byval parameter is passed
1823 /// on the stack.  Remember the next parameter register to allocate,
1824 /// and then confiscate the rest of the parameter registers to insure
1825 /// this.
1826 void
1827 ARMTargetLowering::HandleByVal(
1828     CCState *State, unsigned &size, unsigned Align) const {
1829   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1830   assert((State->getCallOrPrologue() == Prologue ||
1831           State->getCallOrPrologue() == Call) &&
1832          "unhandled ParmContext");
1833
1834   // For in-prologue parameters handling, we also introduce stack offset
1835   // for byval registers: see CallingConvLower.cpp, CCState::HandleByVal.
1836   // This behaviour outsides AAPCS rules (5.5 Parameters Passing) of how
1837   // NSAA should be evaluted (NSAA means "next stacked argument address").
1838   // So: NextStackOffset = NSAAOffset + SizeOfByValParamsStoredInRegs.
1839   // Then: NSAAOffset = NextStackOffset - SizeOfByValParamsStoredInRegs.
1840   unsigned NSAAOffset = State->getNextStackOffset();
1841   if (State->getCallOrPrologue() != Call) {
1842     for (unsigned i = 0, e = State->getInRegsParamsCount(); i != e; ++i) {
1843       unsigned RB, RE;
1844       State->getInRegsParamInfo(i, RB, RE);
1845       assert(NSAAOffset >= (RE-RB)*4 &&
1846              "Stack offset for byval regs doesn't introduced anymore?");
1847       NSAAOffset -= (RE-RB)*4;
1848     }
1849   }
1850   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1851     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1852       unsigned AlignInRegs = Align / 4;
1853       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1854       for (unsigned i = 0; i < Waste; ++i)
1855         reg = State->AllocateReg(GPRArgRegs, 4);
1856     }
1857     if (reg != 0) {
1858       unsigned excess = 4 * (ARM::R4 - reg);
1859
1860       // Special case when NSAA != SP and parameter size greater than size of
1861       // all remained GPR regs. In that case we can't split parameter, we must
1862       // send it to stack. We also must set NCRN to R4, so waste all
1863       // remained registers.
1864       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1865         while (State->AllocateReg(GPRArgRegs, 4))
1866           ;
1867         return;
1868       }
1869
1870       // First register for byval parameter is the first register that wasn't
1871       // allocated before this method call, so it would be "reg".
1872       // If parameter is small enough to be saved in range [reg, r4), then
1873       // the end (first after last) register would be reg + param-size-in-regs,
1874       // else parameter would be splitted between registers and stack,
1875       // end register would be r4 in this case.
1876       unsigned ByValRegBegin = reg;
1877       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1878       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1879       // Note, first register is allocated in the beginning of function already,
1880       // allocate remained amount of registers we need.
1881       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1882         State->AllocateReg(GPRArgRegs, 4);
1883       // At a call site, a byval parameter that is split between
1884       // registers and memory needs its size truncated here.  In a
1885       // function prologue, such byval parameters are reassembled in
1886       // memory, and are not truncated.
1887       if (State->getCallOrPrologue() == Call) {
1888         // Make remained size equal to 0 in case, when
1889         // the whole structure may be stored into registers.
1890         if (size < excess)
1891           size = 0;
1892         else
1893           size -= excess;
1894       }
1895     }
1896   }
1897 }
1898
1899 /// MatchingStackOffset - Return true if the given stack call argument is
1900 /// already available in the same position (relatively) of the caller's
1901 /// incoming argument stack.
1902 static
1903 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1904                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1905                          const TargetInstrInfo *TII) {
1906   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1907   int FI = INT_MAX;
1908   if (Arg.getOpcode() == ISD::CopyFromReg) {
1909     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1910     if (!TargetRegisterInfo::isVirtualRegister(VR))
1911       return false;
1912     MachineInstr *Def = MRI->getVRegDef(VR);
1913     if (!Def)
1914       return false;
1915     if (!Flags.isByVal()) {
1916       if (!TII->isLoadFromStackSlot(Def, FI))
1917         return false;
1918     } else {
1919       return false;
1920     }
1921   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1922     if (Flags.isByVal())
1923       // ByVal argument is passed in as a pointer but it's now being
1924       // dereferenced. e.g.
1925       // define @foo(%struct.X* %A) {
1926       //   tail call @bar(%struct.X* byval %A)
1927       // }
1928       return false;
1929     SDValue Ptr = Ld->getBasePtr();
1930     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1931     if (!FINode)
1932       return false;
1933     FI = FINode->getIndex();
1934   } else
1935     return false;
1936
1937   assert(FI != INT_MAX);
1938   if (!MFI->isFixedObjectIndex(FI))
1939     return false;
1940   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1941 }
1942
1943 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1944 /// for tail call optimization. Targets which want to do tail call
1945 /// optimization should implement this function.
1946 bool
1947 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1948                                                      CallingConv::ID CalleeCC,
1949                                                      bool isVarArg,
1950                                                      bool isCalleeStructRet,
1951                                                      bool isCallerStructRet,
1952                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1953                                     const SmallVectorImpl<SDValue> &OutVals,
1954                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1955                                                      SelectionDAG& DAG) const {
1956   const Function *CallerF = DAG.getMachineFunction().getFunction();
1957   CallingConv::ID CallerCC = CallerF->getCallingConv();
1958   bool CCMatch = CallerCC == CalleeCC;
1959
1960   // Look for obvious safe cases to perform tail call optimization that do not
1961   // require ABI changes. This is what gcc calls sibcall.
1962
1963   // Do not sibcall optimize vararg calls unless the call site is not passing
1964   // any arguments.
1965   if (isVarArg && !Outs.empty())
1966     return false;
1967
1968   // Exception-handling functions need a special set of instructions to indicate
1969   // a return to the hardware. Tail-calling another function would probably
1970   // break this.
1971   if (CallerF->hasFnAttribute("interrupt"))
1972     return false;
1973
1974   // Also avoid sibcall optimization if either caller or callee uses struct
1975   // return semantics.
1976   if (isCalleeStructRet || isCallerStructRet)
1977     return false;
1978
1979   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1980   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1981   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1982   // support in the assembler and linker to be used. This would need to be
1983   // fixed to fully support tail calls in Thumb1.
1984   //
1985   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1986   // LR.  This means if we need to reload LR, it takes an extra instructions,
1987   // which outweighs the value of the tail call; but here we don't know yet
1988   // whether LR is going to be used.  Probably the right approach is to
1989   // generate the tail call here and turn it back into CALL/RET in
1990   // emitEpilogue if LR is used.
1991
1992   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1993   // but we need to make sure there are enough registers; the only valid
1994   // registers are the 4 used for parameters.  We don't currently do this
1995   // case.
1996   if (Subtarget->isThumb1Only())
1997     return false;
1998
1999   // If the calling conventions do not match, then we'd better make sure the
2000   // results are returned in the same way as what the caller expects.
2001   if (!CCMatch) {
2002     SmallVector<CCValAssign, 16> RVLocs1;
2003     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2004                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
2005     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2006
2007     SmallVector<CCValAssign, 16> RVLocs2;
2008     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2009                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
2010     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2011
2012     if (RVLocs1.size() != RVLocs2.size())
2013       return false;
2014     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2015       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2016         return false;
2017       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2018         return false;
2019       if (RVLocs1[i].isRegLoc()) {
2020         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2021           return false;
2022       } else {
2023         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2024           return false;
2025       }
2026     }
2027   }
2028
2029   // If Caller's vararg or byval argument has been split between registers and
2030   // stack, do not perform tail call, since part of the argument is in caller's
2031   // local frame.
2032   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2033                                       getInfo<ARMFunctionInfo>();
2034   if (AFI_Caller->getArgRegsSaveSize())
2035     return false;
2036
2037   // If the callee takes no arguments then go on to check the results of the
2038   // call.
2039   if (!Outs.empty()) {
2040     // Check if stack adjustment is needed. For now, do not do this if any
2041     // argument is passed on the stack.
2042     SmallVector<CCValAssign, 16> ArgLocs;
2043     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2044                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
2045     CCInfo.AnalyzeCallOperands(Outs,
2046                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2047     if (CCInfo.getNextStackOffset()) {
2048       MachineFunction &MF = DAG.getMachineFunction();
2049
2050       // Check if the arguments are already laid out in the right way as
2051       // the caller's fixed stack objects.
2052       MachineFrameInfo *MFI = MF.getFrameInfo();
2053       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2054       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2055       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2056            i != e;
2057            ++i, ++realArgIdx) {
2058         CCValAssign &VA = ArgLocs[i];
2059         EVT RegVT = VA.getLocVT();
2060         SDValue Arg = OutVals[realArgIdx];
2061         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2062         if (VA.getLocInfo() == CCValAssign::Indirect)
2063           return false;
2064         if (VA.needsCustom()) {
2065           // f64 and vector types are split into multiple registers or
2066           // register/stack-slot combinations.  The types will not match
2067           // the registers; give up on memory f64 refs until we figure
2068           // out what to do about this.
2069           if (!VA.isRegLoc())
2070             return false;
2071           if (!ArgLocs[++i].isRegLoc())
2072             return false;
2073           if (RegVT == MVT::v2f64) {
2074             if (!ArgLocs[++i].isRegLoc())
2075               return false;
2076             if (!ArgLocs[++i].isRegLoc())
2077               return false;
2078           }
2079         } else if (!VA.isRegLoc()) {
2080           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2081                                    MFI, MRI, TII))
2082             return false;
2083         }
2084       }
2085     }
2086   }
2087
2088   return true;
2089 }
2090
2091 bool
2092 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2093                                   MachineFunction &MF, bool isVarArg,
2094                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2095                                   LLVMContext &Context) const {
2096   SmallVector<CCValAssign, 16> RVLocs;
2097   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2098   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2099                                                     isVarArg));
2100 }
2101
2102 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2103                                     SDLoc DL, SelectionDAG &DAG) {
2104   const MachineFunction &MF = DAG.getMachineFunction();
2105   const Function *F = MF.getFunction();
2106
2107   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2108
2109   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2110   // version of the "preferred return address". These offsets affect the return
2111   // instruction if this is a return from PL1 without hypervisor extensions.
2112   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2113   //    SWI:     0      "subs pc, lr, #0"
2114   //    ABORT:   +4     "subs pc, lr, #4"
2115   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2116   // UNDEF varies depending on where the exception came from ARM or Thumb
2117   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2118
2119   int64_t LROffset;
2120   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2121       IntKind == "ABORT")
2122     LROffset = 4;
2123   else if (IntKind == "SWI" || IntKind == "UNDEF")
2124     LROffset = 0;
2125   else
2126     report_fatal_error("Unsupported interrupt attribute. If present, value "
2127                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2128
2129   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2130
2131   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other,
2132                      RetOps.data(), RetOps.size());
2133 }
2134
2135 SDValue
2136 ARMTargetLowering::LowerReturn(SDValue Chain,
2137                                CallingConv::ID CallConv, bool isVarArg,
2138                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2139                                const SmallVectorImpl<SDValue> &OutVals,
2140                                SDLoc dl, SelectionDAG &DAG) const {
2141
2142   // CCValAssign - represent the assignment of the return value to a location.
2143   SmallVector<CCValAssign, 16> RVLocs;
2144
2145   // CCState - Info about the registers and stack slots.
2146   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2147                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2148
2149   // Analyze outgoing return values.
2150   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2151                                                isVarArg));
2152
2153   SDValue Flag;
2154   SmallVector<SDValue, 4> RetOps;
2155   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2156
2157   // Copy the result values into the output registers.
2158   for (unsigned i = 0, realRVLocIdx = 0;
2159        i != RVLocs.size();
2160        ++i, ++realRVLocIdx) {
2161     CCValAssign &VA = RVLocs[i];
2162     assert(VA.isRegLoc() && "Can only return in registers!");
2163
2164     SDValue Arg = OutVals[realRVLocIdx];
2165
2166     switch (VA.getLocInfo()) {
2167     default: llvm_unreachable("Unknown loc info!");
2168     case CCValAssign::Full: break;
2169     case CCValAssign::BCvt:
2170       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2171       break;
2172     }
2173
2174     if (VA.needsCustom()) {
2175       if (VA.getLocVT() == MVT::v2f64) {
2176         // Extract the first half and return it in two registers.
2177         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2178                                    DAG.getConstant(0, MVT::i32));
2179         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2180                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2181
2182         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
2183         Flag = Chain.getValue(1);
2184         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2185         VA = RVLocs[++i]; // skip ahead to next loc
2186         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2187                                  HalfGPRs.getValue(1), Flag);
2188         Flag = Chain.getValue(1);
2189         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2190         VA = RVLocs[++i]; // skip ahead to next loc
2191
2192         // Extract the 2nd half and fall through to handle it as an f64 value.
2193         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2194                           DAG.getConstant(1, MVT::i32));
2195       }
2196       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2197       // available.
2198       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2199                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
2200       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
2201       Flag = Chain.getValue(1);
2202       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2203       VA = RVLocs[++i]; // skip ahead to next loc
2204       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
2205                                Flag);
2206     } else
2207       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2208
2209     // Guarantee that all emitted copies are
2210     // stuck together, avoiding something bad.
2211     Flag = Chain.getValue(1);
2212     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2213   }
2214
2215   // Update chain and glue.
2216   RetOps[0] = Chain;
2217   if (Flag.getNode())
2218     RetOps.push_back(Flag);
2219
2220   // CPUs which aren't M-class use a special sequence to return from
2221   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2222   // though we use "subs pc, lr, #N").
2223   //
2224   // M-class CPUs actually use a normal return sequence with a special
2225   // (hardware-provided) value in LR, so the normal code path works.
2226   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2227       !Subtarget->isMClass()) {
2228     if (Subtarget->isThumb1Only())
2229       report_fatal_error("interrupt attribute is not supported in Thumb1");
2230     return LowerInterruptReturn(RetOps, dl, DAG);
2231   }
2232
2233   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
2234                      RetOps.data(), RetOps.size());
2235 }
2236
2237 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2238   if (N->getNumValues() != 1)
2239     return false;
2240   if (!N->hasNUsesOfValue(1, 0))
2241     return false;
2242
2243   SDValue TCChain = Chain;
2244   SDNode *Copy = *N->use_begin();
2245   if (Copy->getOpcode() == ISD::CopyToReg) {
2246     // If the copy has a glue operand, we conservatively assume it isn't safe to
2247     // perform a tail call.
2248     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2249       return false;
2250     TCChain = Copy->getOperand(0);
2251   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2252     SDNode *VMov = Copy;
2253     // f64 returned in a pair of GPRs.
2254     SmallPtrSet<SDNode*, 2> Copies;
2255     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2256          UI != UE; ++UI) {
2257       if (UI->getOpcode() != ISD::CopyToReg)
2258         return false;
2259       Copies.insert(*UI);
2260     }
2261     if (Copies.size() > 2)
2262       return false;
2263
2264     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2265          UI != UE; ++UI) {
2266       SDValue UseChain = UI->getOperand(0);
2267       if (Copies.count(UseChain.getNode()))
2268         // Second CopyToReg
2269         Copy = *UI;
2270       else
2271         // First CopyToReg
2272         TCChain = UseChain;
2273     }
2274   } else if (Copy->getOpcode() == ISD::BITCAST) {
2275     // f32 returned in a single GPR.
2276     if (!Copy->hasOneUse())
2277       return false;
2278     Copy = *Copy->use_begin();
2279     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2280       return false;
2281     TCChain = Copy->getOperand(0);
2282   } else {
2283     return false;
2284   }
2285
2286   bool HasRet = false;
2287   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2288        UI != UE; ++UI) {
2289     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2290         UI->getOpcode() != ARMISD::INTRET_FLAG)
2291       return false;
2292     HasRet = true;
2293   }
2294
2295   if (!HasRet)
2296     return false;
2297
2298   Chain = TCChain;
2299   return true;
2300 }
2301
2302 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2303   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2304     return false;
2305
2306   if (!CI->isTailCall())
2307     return false;
2308
2309   return !Subtarget->isThumb1Only();
2310 }
2311
2312 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2313 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2314 // one of the above mentioned nodes. It has to be wrapped because otherwise
2315 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2316 // be used to form addressing mode. These wrapped nodes will be selected
2317 // into MOVi.
2318 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2319   EVT PtrVT = Op.getValueType();
2320   // FIXME there is no actual debug info here
2321   SDLoc dl(Op);
2322   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2323   SDValue Res;
2324   if (CP->isMachineConstantPoolEntry())
2325     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2326                                     CP->getAlignment());
2327   else
2328     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2329                                     CP->getAlignment());
2330   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2331 }
2332
2333 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2334   return MachineJumpTableInfo::EK_Inline;
2335 }
2336
2337 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2338                                              SelectionDAG &DAG) const {
2339   MachineFunction &MF = DAG.getMachineFunction();
2340   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2341   unsigned ARMPCLabelIndex = 0;
2342   SDLoc DL(Op);
2343   EVT PtrVT = getPointerTy();
2344   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2345   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2346   SDValue CPAddr;
2347   if (RelocM == Reloc::Static) {
2348     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2349   } else {
2350     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2351     ARMPCLabelIndex = AFI->createPICLabelUId();
2352     ARMConstantPoolValue *CPV =
2353       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2354                                       ARMCP::CPBlockAddress, PCAdj);
2355     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2356   }
2357   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2358   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2359                                MachinePointerInfo::getConstantPool(),
2360                                false, false, false, 0);
2361   if (RelocM == Reloc::Static)
2362     return Result;
2363   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2364   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2365 }
2366
2367 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2368 SDValue
2369 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2370                                                  SelectionDAG &DAG) const {
2371   SDLoc dl(GA);
2372   EVT PtrVT = getPointerTy();
2373   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2374   MachineFunction &MF = DAG.getMachineFunction();
2375   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2376   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2377   ARMConstantPoolValue *CPV =
2378     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2379                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2380   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2381   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2382   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2383                          MachinePointerInfo::getConstantPool(),
2384                          false, false, false, 0);
2385   SDValue Chain = Argument.getValue(1);
2386
2387   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2388   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2389
2390   // call __tls_get_addr.
2391   ArgListTy Args;
2392   ArgListEntry Entry;
2393   Entry.Node = Argument;
2394   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2395   Args.push_back(Entry);
2396   // FIXME: is there useful debug info available here?
2397   TargetLowering::CallLoweringInfo CLI(Chain,
2398                 (Type *) Type::getInt32Ty(*DAG.getContext()),
2399                 false, false, false, false,
2400                 0, CallingConv::C, /*isTailCall=*/false,
2401                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2402                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2403   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2404   return CallResult.first;
2405 }
2406
2407 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2408 // "local exec" model.
2409 SDValue
2410 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2411                                         SelectionDAG &DAG,
2412                                         TLSModel::Model model) const {
2413   const GlobalValue *GV = GA->getGlobal();
2414   SDLoc dl(GA);
2415   SDValue Offset;
2416   SDValue Chain = DAG.getEntryNode();
2417   EVT PtrVT = getPointerTy();
2418   // Get the Thread Pointer
2419   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2420
2421   if (model == TLSModel::InitialExec) {
2422     MachineFunction &MF = DAG.getMachineFunction();
2423     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2424     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2425     // Initial exec model.
2426     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2427     ARMConstantPoolValue *CPV =
2428       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2429                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2430                                       true);
2431     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2432     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2433     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2434                          MachinePointerInfo::getConstantPool(),
2435                          false, false, false, 0);
2436     Chain = Offset.getValue(1);
2437
2438     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2439     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2440
2441     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2442                          MachinePointerInfo::getConstantPool(),
2443                          false, false, false, 0);
2444   } else {
2445     // local exec model
2446     assert(model == TLSModel::LocalExec);
2447     ARMConstantPoolValue *CPV =
2448       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2449     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2450     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2451     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2452                          MachinePointerInfo::getConstantPool(),
2453                          false, false, false, 0);
2454   }
2455
2456   // The address of the thread local variable is the add of the thread
2457   // pointer with the offset of the variable.
2458   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2459 }
2460
2461 SDValue
2462 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2463   // TODO: implement the "local dynamic" model
2464   assert(Subtarget->isTargetELF() &&
2465          "TLS not implemented for non-ELF targets");
2466   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2467
2468   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2469
2470   switch (model) {
2471     case TLSModel::GeneralDynamic:
2472     case TLSModel::LocalDynamic:
2473       return LowerToTLSGeneralDynamicModel(GA, DAG);
2474     case TLSModel::InitialExec:
2475     case TLSModel::LocalExec:
2476       return LowerToTLSExecModels(GA, DAG, model);
2477   }
2478   llvm_unreachable("bogus TLS model");
2479 }
2480
2481 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2482                                                  SelectionDAG &DAG) const {
2483   EVT PtrVT = getPointerTy();
2484   SDLoc dl(Op);
2485   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2486   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2487     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2488     ARMConstantPoolValue *CPV =
2489       ARMConstantPoolConstant::Create(GV,
2490                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2491     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2492     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2493     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2494                                  CPAddr,
2495                                  MachinePointerInfo::getConstantPool(),
2496                                  false, false, false, 0);
2497     SDValue Chain = Result.getValue(1);
2498     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2499     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2500     if (!UseGOTOFF)
2501       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2502                            MachinePointerInfo::getGOT(),
2503                            false, false, false, 0);
2504     return Result;
2505   }
2506
2507   // If we have T2 ops, we can materialize the address directly via movt/movw
2508   // pair. This is always cheaper.
2509   if (Subtarget->useMovt()) {
2510     ++NumMovwMovt;
2511     // FIXME: Once remat is capable of dealing with instructions with register
2512     // operands, expand this into two nodes.
2513     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2514                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2515   } else {
2516     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2517     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2518     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2519                        MachinePointerInfo::getConstantPool(),
2520                        false, false, false, 0);
2521   }
2522 }
2523
2524 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2525                                                     SelectionDAG &DAG) const {
2526   EVT PtrVT = getPointerTy();
2527   SDLoc dl(Op);
2528   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2529   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2530
2531   if (Subtarget->useMovt())
2532     ++NumMovwMovt;
2533
2534   // FIXME: Once remat is capable of dealing with instructions with register
2535   // operands, expand this into multiple nodes
2536   unsigned Wrapper =
2537       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2538
2539   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2540   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2541
2542   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2543     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2544                          MachinePointerInfo::getGOT(), false, false, false, 0);
2545   return Result;
2546 }
2547
2548 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2549                                                     SelectionDAG &DAG) const {
2550   assert(Subtarget->isTargetELF() &&
2551          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2552   MachineFunction &MF = DAG.getMachineFunction();
2553   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2554   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2555   EVT PtrVT = getPointerTy();
2556   SDLoc dl(Op);
2557   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2558   ARMConstantPoolValue *CPV =
2559     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2560                                   ARMPCLabelIndex, PCAdj);
2561   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2562   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2563   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2564                                MachinePointerInfo::getConstantPool(),
2565                                false, false, false, 0);
2566   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2567   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2568 }
2569
2570 SDValue
2571 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2572   SDLoc dl(Op);
2573   SDValue Val = DAG.getConstant(0, MVT::i32);
2574   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2575                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2576                      Op.getOperand(1), Val);
2577 }
2578
2579 SDValue
2580 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2581   SDLoc dl(Op);
2582   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2583                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2584 }
2585
2586 SDValue
2587 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2588                                           const ARMSubtarget *Subtarget) const {
2589   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2590   SDLoc dl(Op);
2591   switch (IntNo) {
2592   default: return SDValue();    // Don't custom lower most intrinsics.
2593   case Intrinsic::arm_thread_pointer: {
2594     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2595     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2596   }
2597   case Intrinsic::eh_sjlj_lsda: {
2598     MachineFunction &MF = DAG.getMachineFunction();
2599     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2600     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2601     EVT PtrVT = getPointerTy();
2602     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2603     SDValue CPAddr;
2604     unsigned PCAdj = (RelocM != Reloc::PIC_)
2605       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2606     ARMConstantPoolValue *CPV =
2607       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2608                                       ARMCP::CPLSDA, PCAdj);
2609     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2610     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2611     SDValue Result =
2612       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2613                   MachinePointerInfo::getConstantPool(),
2614                   false, false, false, 0);
2615
2616     if (RelocM == Reloc::PIC_) {
2617       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2618       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2619     }
2620     return Result;
2621   }
2622   case Intrinsic::arm_neon_vmulls:
2623   case Intrinsic::arm_neon_vmullu: {
2624     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2625       ? ARMISD::VMULLs : ARMISD::VMULLu;
2626     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2627                        Op.getOperand(1), Op.getOperand(2));
2628   }
2629   }
2630 }
2631
2632 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2633                                  const ARMSubtarget *Subtarget) {
2634   // FIXME: handle "fence singlethread" more efficiently.
2635   SDLoc dl(Op);
2636   if (!Subtarget->hasDataBarrier()) {
2637     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2638     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2639     // here.
2640     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2641            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2642     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2643                        DAG.getConstant(0, MVT::i32));
2644   }
2645
2646   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2647   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2648   unsigned Domain = ARM_MB::ISH;
2649   if (Subtarget->isMClass()) {
2650     // Only a full system barrier exists in the M-class architectures.
2651     Domain = ARM_MB::SY;
2652   } else if (Subtarget->isSwift() && Ord == Release) {
2653     // Swift happens to implement ISHST barriers in a way that's compatible with
2654     // Release semantics but weaker than ISH so we'd be fools not to use
2655     // it. Beware: other processors probably don't!
2656     Domain = ARM_MB::ISHST;
2657   }
2658
2659   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2660                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2661                      DAG.getConstant(Domain, MVT::i32));
2662 }
2663
2664 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2665                              const ARMSubtarget *Subtarget) {
2666   // ARM pre v5TE and Thumb1 does not have preload instructions.
2667   if (!(Subtarget->isThumb2() ||
2668         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2669     // Just preserve the chain.
2670     return Op.getOperand(0);
2671
2672   SDLoc dl(Op);
2673   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2674   if (!isRead &&
2675       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2676     // ARMv7 with MP extension has PLDW.
2677     return Op.getOperand(0);
2678
2679   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2680   if (Subtarget->isThumb()) {
2681     // Invert the bits.
2682     isRead = ~isRead & 1;
2683     isData = ~isData & 1;
2684   }
2685
2686   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2687                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2688                      DAG.getConstant(isData, MVT::i32));
2689 }
2690
2691 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2692   MachineFunction &MF = DAG.getMachineFunction();
2693   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2694
2695   // vastart just stores the address of the VarArgsFrameIndex slot into the
2696   // memory location argument.
2697   SDLoc dl(Op);
2698   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2699   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2700   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2701   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2702                       MachinePointerInfo(SV), false, false, 0);
2703 }
2704
2705 SDValue
2706 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2707                                         SDValue &Root, SelectionDAG &DAG,
2708                                         SDLoc dl) const {
2709   MachineFunction &MF = DAG.getMachineFunction();
2710   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2711
2712   const TargetRegisterClass *RC;
2713   if (AFI->isThumb1OnlyFunction())
2714     RC = &ARM::tGPRRegClass;
2715   else
2716     RC = &ARM::GPRRegClass;
2717
2718   // Transform the arguments stored in physical registers into virtual ones.
2719   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2720   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2721
2722   SDValue ArgValue2;
2723   if (NextVA.isMemLoc()) {
2724     MachineFrameInfo *MFI = MF.getFrameInfo();
2725     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2726
2727     // Create load node to retrieve arguments from the stack.
2728     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2729     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2730                             MachinePointerInfo::getFixedStack(FI),
2731                             false, false, false, 0);
2732   } else {
2733     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2734     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2735   }
2736
2737   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2738 }
2739
2740 void
2741 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2742                                   unsigned InRegsParamRecordIdx,
2743                                   unsigned ArgSize,
2744                                   unsigned &ArgRegsSize,
2745                                   unsigned &ArgRegsSaveSize)
2746   const {
2747   unsigned NumGPRs;
2748   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2749     unsigned RBegin, REnd;
2750     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2751     NumGPRs = REnd - RBegin;
2752   } else {
2753     unsigned int firstUnalloced;
2754     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2755                                                 sizeof(GPRArgRegs) /
2756                                                 sizeof(GPRArgRegs[0]));
2757     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2758   }
2759
2760   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2761   ArgRegsSize = NumGPRs * 4;
2762
2763   // If parameter is split between stack and GPRs...
2764   if (NumGPRs && Align == 8 &&
2765       (ArgRegsSize < ArgSize ||
2766         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2767     // Add padding for part of param recovered from GPRs, so
2768     // its last byte must be at address K*8 - 1.
2769     // We need to do it, since remained (stack) part of parameter has
2770     // stack alignment, and we need to "attach" "GPRs head" without gaps
2771     // to it:
2772     // Stack:
2773     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2774     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2775     //
2776     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2777     unsigned Padding =
2778         ((ArgRegsSize + AFI->getArgRegsSaveSize() + Align - 1) & ~(Align-1)) -
2779         (ArgRegsSize + AFI->getArgRegsSaveSize());
2780     ArgRegsSaveSize = ArgRegsSize + Padding;
2781   } else
2782     // We don't need to extend regs save size for byval parameters if they
2783     // are passed via GPRs only.
2784     ArgRegsSaveSize = ArgRegsSize;
2785 }
2786
2787 // The remaining GPRs hold either the beginning of variable-argument
2788 // data, or the beginning of an aggregate passed by value (usually
2789 // byval).  Either way, we allocate stack slots adjacent to the data
2790 // provided by our caller, and store the unallocated registers there.
2791 // If this is a variadic function, the va_list pointer will begin with
2792 // these values; otherwise, this reassembles a (byval) structure that
2793 // was split between registers and memory.
2794 // Return: The frame index registers were stored into.
2795 int
2796 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2797                                   SDLoc dl, SDValue &Chain,
2798                                   const Value *OrigArg,
2799                                   unsigned InRegsParamRecordIdx,
2800                                   unsigned OffsetFromOrigArg,
2801                                   unsigned ArgOffset,
2802                                   unsigned ArgSize,
2803                                   bool ForceMutable) const {
2804
2805   // Currently, two use-cases possible:
2806   // Case #1. Non-var-args function, and we meet first byval parameter.
2807   //          Setup first unallocated register as first byval register;
2808   //          eat all remained registers
2809   //          (these two actions are performed by HandleByVal method).
2810   //          Then, here, we initialize stack frame with
2811   //          "store-reg" instructions.
2812   // Case #2. Var-args function, that doesn't contain byval parameters.
2813   //          The same: eat all remained unallocated registers,
2814   //          initialize stack frame.
2815
2816   MachineFunction &MF = DAG.getMachineFunction();
2817   MachineFrameInfo *MFI = MF.getFrameInfo();
2818   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2819   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2820   unsigned RBegin, REnd;
2821   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2822     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2823     firstRegToSaveIndex = RBegin - ARM::R0;
2824     lastRegToSaveIndex = REnd - ARM::R0;
2825   } else {
2826     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2827       (GPRArgRegs, array_lengthof(GPRArgRegs));
2828     lastRegToSaveIndex = 4;
2829   }
2830
2831   unsigned ArgRegsSize, ArgRegsSaveSize;
2832   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2833                  ArgRegsSize, ArgRegsSaveSize);
2834
2835   // Store any by-val regs to their spots on the stack so that they may be
2836   // loaded by deferencing the result of formal parameter pointer or va_next.
2837   // Note: once stack area for byval/varargs registers
2838   // was initialized, it can't be initialized again.
2839   if (ArgRegsSaveSize) {
2840
2841     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2842
2843     if (Padding) {
2844       assert(AFI->getStoredByValParamsPadding() == 0 &&
2845              "The only parameter may be padded.");
2846       AFI->setStoredByValParamsPadding(Padding);
2847     }
2848
2849     int FrameIndex = MFI->CreateFixedObject(
2850                       ArgRegsSaveSize,
2851                       Padding + ArgOffset,
2852                       false);
2853     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2854
2855     SmallVector<SDValue, 4> MemOps;
2856     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2857          ++firstRegToSaveIndex, ++i) {
2858       const TargetRegisterClass *RC;
2859       if (AFI->isThumb1OnlyFunction())
2860         RC = &ARM::tGPRRegClass;
2861       else
2862         RC = &ARM::GPRRegClass;
2863
2864       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2865       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2866       SDValue Store =
2867         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2868                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2869                      false, false, 0);
2870       MemOps.push_back(Store);
2871       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2872                         DAG.getConstant(4, getPointerTy()));
2873     }
2874
2875     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2876
2877     if (!MemOps.empty())
2878       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2879                           &MemOps[0], MemOps.size());
2880     return FrameIndex;
2881   } else
2882     // This will point to the next argument passed via stack.
2883     return MFI->CreateFixedObject(
2884         4, AFI->getStoredByValParamsPadding() + ArgOffset, !ForceMutable);
2885 }
2886
2887 // Setup stack frame, the va_list pointer will start from.
2888 void
2889 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2890                                         SDLoc dl, SDValue &Chain,
2891                                         unsigned ArgOffset,
2892                                         bool ForceMutable) const {
2893   MachineFunction &MF = DAG.getMachineFunction();
2894   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2895
2896   // Try to store any remaining integer argument regs
2897   // to their spots on the stack so that they may be loaded by deferencing
2898   // the result of va_next.
2899   // If there is no regs to be stored, just point address after last
2900   // argument passed via stack.
2901   int FrameIndex =
2902     StoreByValRegs(CCInfo, DAG, dl, Chain, 0, CCInfo.getInRegsParamsCount(),
2903                    0, ArgOffset, 0, ForceMutable);
2904
2905   AFI->setVarArgsFrameIndex(FrameIndex);
2906 }
2907
2908 SDValue
2909 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2910                                         CallingConv::ID CallConv, bool isVarArg,
2911                                         const SmallVectorImpl<ISD::InputArg>
2912                                           &Ins,
2913                                         SDLoc dl, SelectionDAG &DAG,
2914                                         SmallVectorImpl<SDValue> &InVals)
2915                                           const {
2916   MachineFunction &MF = DAG.getMachineFunction();
2917   MachineFrameInfo *MFI = MF.getFrameInfo();
2918
2919   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2920
2921   // Assign locations to all of the incoming arguments.
2922   SmallVector<CCValAssign, 16> ArgLocs;
2923   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2924                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2925   CCInfo.AnalyzeFormalArguments(Ins,
2926                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2927                                                   isVarArg));
2928
2929   SmallVector<SDValue, 16> ArgValues;
2930   int lastInsIndex = -1;
2931   SDValue ArgValue;
2932   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2933   unsigned CurArgIdx = 0;
2934
2935   // Initially ArgRegsSaveSize is zero.
2936   // Then we increase this value each time we meet byval parameter.
2937   // We also increase this value in case of varargs function.
2938   AFI->setArgRegsSaveSize(0);
2939
2940   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2941     CCValAssign &VA = ArgLocs[i];
2942     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2943     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2944     // Arguments stored in registers.
2945     if (VA.isRegLoc()) {
2946       EVT RegVT = VA.getLocVT();
2947
2948       if (VA.needsCustom()) {
2949         // f64 and vector types are split up into multiple registers or
2950         // combinations of registers and stack slots.
2951         if (VA.getLocVT() == MVT::v2f64) {
2952           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2953                                                    Chain, DAG, dl);
2954           VA = ArgLocs[++i]; // skip ahead to next loc
2955           SDValue ArgValue2;
2956           if (VA.isMemLoc()) {
2957             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2958             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2959             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2960                                     MachinePointerInfo::getFixedStack(FI),
2961                                     false, false, false, 0);
2962           } else {
2963             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2964                                              Chain, DAG, dl);
2965           }
2966           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2967           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2968                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2969           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2970                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2971         } else
2972           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2973
2974       } else {
2975         const TargetRegisterClass *RC;
2976
2977         if (RegVT == MVT::f32)
2978           RC = &ARM::SPRRegClass;
2979         else if (RegVT == MVT::f64)
2980           RC = &ARM::DPRRegClass;
2981         else if (RegVT == MVT::v2f64)
2982           RC = &ARM::QPRRegClass;
2983         else if (RegVT == MVT::i32)
2984           RC = AFI->isThumb1OnlyFunction() ?
2985             (const TargetRegisterClass*)&ARM::tGPRRegClass :
2986             (const TargetRegisterClass*)&ARM::GPRRegClass;
2987         else
2988           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2989
2990         // Transform the arguments in physical registers into virtual ones.
2991         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2992         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2993       }
2994
2995       // If this is an 8 or 16-bit value, it is really passed promoted
2996       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2997       // truncate to the right size.
2998       switch (VA.getLocInfo()) {
2999       default: llvm_unreachable("Unknown loc info!");
3000       case CCValAssign::Full: break;
3001       case CCValAssign::BCvt:
3002         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3003         break;
3004       case CCValAssign::SExt:
3005         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3006                                DAG.getValueType(VA.getValVT()));
3007         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3008         break;
3009       case CCValAssign::ZExt:
3010         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3011                                DAG.getValueType(VA.getValVT()));
3012         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3013         break;
3014       }
3015
3016       InVals.push_back(ArgValue);
3017
3018     } else { // VA.isRegLoc()
3019
3020       // sanity check
3021       assert(VA.isMemLoc());
3022       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3023
3024       int index = ArgLocs[i].getValNo();
3025
3026       // Some Ins[] entries become multiple ArgLoc[] entries.
3027       // Process them only once.
3028       if (index != lastInsIndex)
3029         {
3030           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3031           // FIXME: For now, all byval parameter objects are marked mutable.
3032           // This can be changed with more analysis.
3033           // In case of tail call optimization mark all arguments mutable.
3034           // Since they could be overwritten by lowering of arguments in case of
3035           // a tail call.
3036           if (Flags.isByVal()) {
3037             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3038             int FrameIndex = StoreByValRegs(
3039                 CCInfo, DAG, dl, Chain, CurOrigArg,
3040                 CurByValIndex,
3041                 Ins[VA.getValNo()].PartOffset,
3042                 VA.getLocMemOffset(),
3043                 Flags.getByValSize(),
3044                 true /*force mutable frames*/);
3045             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3046             CCInfo.nextInRegsParam();
3047           } else {
3048             unsigned FIOffset = VA.getLocMemOffset() +
3049                                 AFI->getStoredByValParamsPadding();
3050             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3051                                             FIOffset, true);
3052
3053             // Create load nodes to retrieve arguments from the stack.
3054             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3055             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3056                                          MachinePointerInfo::getFixedStack(FI),
3057                                          false, false, false, 0));
3058           }
3059           lastInsIndex = index;
3060         }
3061     }
3062   }
3063
3064   // varargs
3065   if (isVarArg)
3066     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3067                          CCInfo.getNextStackOffset());
3068
3069   return Chain;
3070 }
3071
3072 /// isFloatingPointZero - Return true if this is +0.0.
3073 static bool isFloatingPointZero(SDValue Op) {
3074   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3075     return CFP->getValueAPF().isPosZero();
3076   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3077     // Maybe this has already been legalized into the constant pool?
3078     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3079       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3080       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3081         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3082           return CFP->getValueAPF().isPosZero();
3083     }
3084   }
3085   return false;
3086 }
3087
3088 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3089 /// the given operands.
3090 SDValue
3091 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3092                              SDValue &ARMcc, SelectionDAG &DAG,
3093                              SDLoc dl) const {
3094   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3095     unsigned C = RHSC->getZExtValue();
3096     if (!isLegalICmpImmediate(C)) {
3097       // Constant does not fit, try adjusting it by one?
3098       switch (CC) {
3099       default: break;
3100       case ISD::SETLT:
3101       case ISD::SETGE:
3102         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3103           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3104           RHS = DAG.getConstant(C-1, MVT::i32);
3105         }
3106         break;
3107       case ISD::SETULT:
3108       case ISD::SETUGE:
3109         if (C != 0 && isLegalICmpImmediate(C-1)) {
3110           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3111           RHS = DAG.getConstant(C-1, MVT::i32);
3112         }
3113         break;
3114       case ISD::SETLE:
3115       case ISD::SETGT:
3116         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3117           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3118           RHS = DAG.getConstant(C+1, MVT::i32);
3119         }
3120         break;
3121       case ISD::SETULE:
3122       case ISD::SETUGT:
3123         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3124           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3125           RHS = DAG.getConstant(C+1, MVT::i32);
3126         }
3127         break;
3128       }
3129     }
3130   }
3131
3132   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3133   ARMISD::NodeType CompareType;
3134   switch (CondCode) {
3135   default:
3136     CompareType = ARMISD::CMP;
3137     break;
3138   case ARMCC::EQ:
3139   case ARMCC::NE:
3140     // Uses only Z Flag
3141     CompareType = ARMISD::CMPZ;
3142     break;
3143   }
3144   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3145   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3146 }
3147
3148 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3149 SDValue
3150 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3151                              SDLoc dl) const {
3152   SDValue Cmp;
3153   if (!isFloatingPointZero(RHS))
3154     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3155   else
3156     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3157   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3158 }
3159
3160 /// duplicateCmp - Glue values can have only one use, so this function
3161 /// duplicates a comparison node.
3162 SDValue
3163 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3164   unsigned Opc = Cmp.getOpcode();
3165   SDLoc DL(Cmp);
3166   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3167     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3168
3169   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3170   Cmp = Cmp.getOperand(0);
3171   Opc = Cmp.getOpcode();
3172   if (Opc == ARMISD::CMPFP)
3173     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3174   else {
3175     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3176     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3177   }
3178   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3179 }
3180
3181 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3182   SDValue Cond = Op.getOperand(0);
3183   SDValue SelectTrue = Op.getOperand(1);
3184   SDValue SelectFalse = Op.getOperand(2);
3185   SDLoc dl(Op);
3186
3187   // Convert:
3188   //
3189   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3190   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3191   //
3192   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3193     const ConstantSDNode *CMOVTrue =
3194       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3195     const ConstantSDNode *CMOVFalse =
3196       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3197
3198     if (CMOVTrue && CMOVFalse) {
3199       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3200       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3201
3202       SDValue True;
3203       SDValue False;
3204       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3205         True = SelectTrue;
3206         False = SelectFalse;
3207       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3208         True = SelectFalse;
3209         False = SelectTrue;
3210       }
3211
3212       if (True.getNode() && False.getNode()) {
3213         EVT VT = Op.getValueType();
3214         SDValue ARMcc = Cond.getOperand(2);
3215         SDValue CCR = Cond.getOperand(3);
3216         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3217         assert(True.getValueType() == VT);
3218         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3219       }
3220     }
3221   }
3222
3223   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3224   // undefined bits before doing a full-word comparison with zero.
3225   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3226                      DAG.getConstant(1, Cond.getValueType()));
3227
3228   return DAG.getSelectCC(dl, Cond,
3229                          DAG.getConstant(0, Cond.getValueType()),
3230                          SelectTrue, SelectFalse, ISD::SETNE);
3231 }
3232
3233 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3234   if (CC == ISD::SETNE)
3235     return ISD::SETEQ;
3236   return ISD::getSetCCInverse(CC, true);
3237 }
3238
3239 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3240                                  bool &swpCmpOps, bool &swpVselOps) {
3241   // Start by selecting the GE condition code for opcodes that return true for
3242   // 'equality'
3243   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3244       CC == ISD::SETULE)
3245     CondCode = ARMCC::GE;
3246
3247   // and GT for opcodes that return false for 'equality'.
3248   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3249            CC == ISD::SETULT)
3250     CondCode = ARMCC::GT;
3251
3252   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3253   // to swap the compare operands.
3254   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3255       CC == ISD::SETULT)
3256     swpCmpOps = true;
3257
3258   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3259   // If we have an unordered opcode, we need to swap the operands to the VSEL
3260   // instruction (effectively negating the condition).
3261   //
3262   // This also has the effect of swapping which one of 'less' or 'greater'
3263   // returns true, so we also swap the compare operands. It also switches
3264   // whether we return true for 'equality', so we compensate by picking the
3265   // opposite condition code to our original choice.
3266   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3267       CC == ISD::SETUGT) {
3268     swpCmpOps = !swpCmpOps;
3269     swpVselOps = !swpVselOps;
3270     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3271   }
3272
3273   // 'ordered' is 'anything but unordered', so use the VS condition code and
3274   // swap the VSEL operands.
3275   if (CC == ISD::SETO) {
3276     CondCode = ARMCC::VS;
3277     swpVselOps = true;
3278   }
3279
3280   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3281   // code and swap the VSEL operands.
3282   if (CC == ISD::SETUNE) {
3283     CondCode = ARMCC::EQ;
3284     swpVselOps = true;
3285   }
3286 }
3287
3288 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3289   EVT VT = Op.getValueType();
3290   SDValue LHS = Op.getOperand(0);
3291   SDValue RHS = Op.getOperand(1);
3292   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3293   SDValue TrueVal = Op.getOperand(2);
3294   SDValue FalseVal = Op.getOperand(3);
3295   SDLoc dl(Op);
3296
3297   if (LHS.getValueType() == MVT::i32) {
3298     // Try to generate VSEL on ARMv8.
3299     // The VSEL instruction can't use all the usual ARM condition
3300     // codes: it only has two bits to select the condition code, so it's
3301     // constrained to use only GE, GT, VS and EQ.
3302     //
3303     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3304     // swap the operands of the previous compare instruction (effectively
3305     // inverting the compare condition, swapping 'less' and 'greater') and
3306     // sometimes need to swap the operands to the VSEL (which inverts the
3307     // condition in the sense of firing whenever the previous condition didn't)
3308     if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3309                                       TrueVal.getValueType() == MVT::f64)) {
3310       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3311       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3312           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3313         CC = getInverseCCForVSEL(CC);
3314         std::swap(TrueVal, FalseVal);
3315       }
3316     }
3317
3318     SDValue ARMcc;
3319     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3320     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3321     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3322                        Cmp);
3323   }
3324
3325   ARMCC::CondCodes CondCode, CondCode2;
3326   FPCCToARMCC(CC, CondCode, CondCode2);
3327
3328   // Try to generate VSEL on ARMv8.
3329   if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3330                                     TrueVal.getValueType() == MVT::f64)) {
3331     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3332     // same operands, as follows:
3333     //   c = fcmp [ogt, olt, ugt, ult] a, b
3334     //   select c, a, b
3335     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3336     // handled differently than the original code sequence.
3337     if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3338         RHS == FalseVal) {
3339       if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3340         return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3341       if (CC == ISD::SETOLT || CC == ISD::SETULT)
3342         return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3343     }
3344
3345     bool swpCmpOps = false;
3346     bool swpVselOps = false;
3347     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3348
3349     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3350         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3351       if (swpCmpOps)
3352         std::swap(LHS, RHS);
3353       if (swpVselOps)
3354         std::swap(TrueVal, FalseVal);
3355     }
3356   }
3357
3358   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3359   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3360   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3361   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3362                                ARMcc, CCR, Cmp);
3363   if (CondCode2 != ARMCC::AL) {
3364     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3365     // FIXME: Needs another CMP because flag can have but one use.
3366     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3367     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3368                          Result, TrueVal, ARMcc2, CCR, Cmp2);
3369   }
3370   return Result;
3371 }
3372
3373 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3374 /// to morph to an integer compare sequence.
3375 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3376                            const ARMSubtarget *Subtarget) {
3377   SDNode *N = Op.getNode();
3378   if (!N->hasOneUse())
3379     // Otherwise it requires moving the value from fp to integer registers.
3380     return false;
3381   if (!N->getNumValues())
3382     return false;
3383   EVT VT = Op.getValueType();
3384   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3385     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3386     // vmrs are very slow, e.g. cortex-a8.
3387     return false;
3388
3389   if (isFloatingPointZero(Op)) {
3390     SeenZero = true;
3391     return true;
3392   }
3393   return ISD::isNormalLoad(N);
3394 }
3395
3396 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3397   if (isFloatingPointZero(Op))
3398     return DAG.getConstant(0, MVT::i32);
3399
3400   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3401     return DAG.getLoad(MVT::i32, SDLoc(Op),
3402                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3403                        Ld->isVolatile(), Ld->isNonTemporal(),
3404                        Ld->isInvariant(), Ld->getAlignment());
3405
3406   llvm_unreachable("Unknown VFP cmp argument!");
3407 }
3408
3409 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3410                            SDValue &RetVal1, SDValue &RetVal2) {
3411   if (isFloatingPointZero(Op)) {
3412     RetVal1 = DAG.getConstant(0, MVT::i32);
3413     RetVal2 = DAG.getConstant(0, MVT::i32);
3414     return;
3415   }
3416
3417   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3418     SDValue Ptr = Ld->getBasePtr();
3419     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3420                           Ld->getChain(), Ptr,
3421                           Ld->getPointerInfo(),
3422                           Ld->isVolatile(), Ld->isNonTemporal(),
3423                           Ld->isInvariant(), Ld->getAlignment());
3424
3425     EVT PtrType = Ptr.getValueType();
3426     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3427     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3428                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3429     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3430                           Ld->getChain(), NewPtr,
3431                           Ld->getPointerInfo().getWithOffset(4),
3432                           Ld->isVolatile(), Ld->isNonTemporal(),
3433                           Ld->isInvariant(), NewAlign);
3434     return;
3435   }
3436
3437   llvm_unreachable("Unknown VFP cmp argument!");
3438 }
3439
3440 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3441 /// f32 and even f64 comparisons to integer ones.
3442 SDValue
3443 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3444   SDValue Chain = Op.getOperand(0);
3445   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3446   SDValue LHS = Op.getOperand(2);
3447   SDValue RHS = Op.getOperand(3);
3448   SDValue Dest = Op.getOperand(4);
3449   SDLoc dl(Op);
3450
3451   bool LHSSeenZero = false;
3452   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3453   bool RHSSeenZero = false;
3454   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3455   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3456     // If unsafe fp math optimization is enabled and there are no other uses of
3457     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3458     // to an integer comparison.
3459     if (CC == ISD::SETOEQ)
3460       CC = ISD::SETEQ;
3461     else if (CC == ISD::SETUNE)
3462       CC = ISD::SETNE;
3463
3464     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3465     SDValue ARMcc;
3466     if (LHS.getValueType() == MVT::f32) {
3467       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3468                         bitcastf32Toi32(LHS, DAG), Mask);
3469       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3470                         bitcastf32Toi32(RHS, DAG), Mask);
3471       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3472       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3473       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3474                          Chain, Dest, ARMcc, CCR, Cmp);
3475     }
3476
3477     SDValue LHS1, LHS2;
3478     SDValue RHS1, RHS2;
3479     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3480     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3481     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3482     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3483     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3484     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3485     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3486     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3487     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3488   }
3489
3490   return SDValue();
3491 }
3492
3493 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3494   SDValue Chain = Op.getOperand(0);
3495   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3496   SDValue LHS = Op.getOperand(2);
3497   SDValue RHS = Op.getOperand(3);
3498   SDValue Dest = Op.getOperand(4);
3499   SDLoc dl(Op);
3500
3501   if (LHS.getValueType() == MVT::i32) {
3502     SDValue ARMcc;
3503     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3504     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3505     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3506                        Chain, Dest, ARMcc, CCR, Cmp);
3507   }
3508
3509   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3510
3511   if (getTargetMachine().Options.UnsafeFPMath &&
3512       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3513        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3514     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3515     if (Result.getNode())
3516       return Result;
3517   }
3518
3519   ARMCC::CondCodes CondCode, CondCode2;
3520   FPCCToARMCC(CC, CondCode, CondCode2);
3521
3522   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3523   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3524   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3525   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3526   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3527   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3528   if (CondCode2 != ARMCC::AL) {
3529     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3530     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3531     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3532   }
3533   return Res;
3534 }
3535
3536 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3537   SDValue Chain = Op.getOperand(0);
3538   SDValue Table = Op.getOperand(1);
3539   SDValue Index = Op.getOperand(2);
3540   SDLoc dl(Op);
3541
3542   EVT PTy = getPointerTy();
3543   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3544   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3545   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3546   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3547   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3548   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3549   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3550   if (Subtarget->isThumb2()) {
3551     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3552     // which does another jump to the destination. This also makes it easier
3553     // to translate it to TBB / TBH later.
3554     // FIXME: This might not work if the function is extremely large.
3555     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3556                        Addr, Op.getOperand(2), JTI, UId);
3557   }
3558   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3559     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3560                        MachinePointerInfo::getJumpTable(),
3561                        false, false, false, 0);
3562     Chain = Addr.getValue(1);
3563     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3564     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3565   } else {
3566     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3567                        MachinePointerInfo::getJumpTable(),
3568                        false, false, false, 0);
3569     Chain = Addr.getValue(1);
3570     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3571   }
3572 }
3573
3574 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3575   EVT VT = Op.getValueType();
3576   SDLoc dl(Op);
3577
3578   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3579     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3580       return Op;
3581     return DAG.UnrollVectorOp(Op.getNode());
3582   }
3583
3584   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3585          "Invalid type for custom lowering!");
3586   if (VT != MVT::v4i16)
3587     return DAG.UnrollVectorOp(Op.getNode());
3588
3589   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3590   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3591 }
3592
3593 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3594   EVT VT = Op.getValueType();
3595   if (VT.isVector())
3596     return LowerVectorFP_TO_INT(Op, DAG);
3597
3598   SDLoc dl(Op);
3599   unsigned Opc;
3600
3601   switch (Op.getOpcode()) {
3602   default: llvm_unreachable("Invalid opcode!");
3603   case ISD::FP_TO_SINT:
3604     Opc = ARMISD::FTOSI;
3605     break;
3606   case ISD::FP_TO_UINT:
3607     Opc = ARMISD::FTOUI;
3608     break;
3609   }
3610   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3611   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3612 }
3613
3614 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3615   EVT VT = Op.getValueType();
3616   SDLoc dl(Op);
3617
3618   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3619     if (VT.getVectorElementType() == MVT::f32)
3620       return Op;
3621     return DAG.UnrollVectorOp(Op.getNode());
3622   }
3623
3624   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3625          "Invalid type for custom lowering!");
3626   if (VT != MVT::v4f32)
3627     return DAG.UnrollVectorOp(Op.getNode());
3628
3629   unsigned CastOpc;
3630   unsigned Opc;
3631   switch (Op.getOpcode()) {
3632   default: llvm_unreachable("Invalid opcode!");
3633   case ISD::SINT_TO_FP:
3634     CastOpc = ISD::SIGN_EXTEND;
3635     Opc = ISD::SINT_TO_FP;
3636     break;
3637   case ISD::UINT_TO_FP:
3638     CastOpc = ISD::ZERO_EXTEND;
3639     Opc = ISD::UINT_TO_FP;
3640     break;
3641   }
3642
3643   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3644   return DAG.getNode(Opc, dl, VT, Op);
3645 }
3646
3647 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3648   EVT VT = Op.getValueType();
3649   if (VT.isVector())
3650     return LowerVectorINT_TO_FP(Op, DAG);
3651
3652   SDLoc dl(Op);
3653   unsigned Opc;
3654
3655   switch (Op.getOpcode()) {
3656   default: llvm_unreachable("Invalid opcode!");
3657   case ISD::SINT_TO_FP:
3658     Opc = ARMISD::SITOF;
3659     break;
3660   case ISD::UINT_TO_FP:
3661     Opc = ARMISD::UITOF;
3662     break;
3663   }
3664
3665   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3666   return DAG.getNode(Opc, dl, VT, Op);
3667 }
3668
3669 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3670   // Implement fcopysign with a fabs and a conditional fneg.
3671   SDValue Tmp0 = Op.getOperand(0);
3672   SDValue Tmp1 = Op.getOperand(1);
3673   SDLoc dl(Op);
3674   EVT VT = Op.getValueType();
3675   EVT SrcVT = Tmp1.getValueType();
3676   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3677     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3678   bool UseNEON = !InGPR && Subtarget->hasNEON();
3679
3680   if (UseNEON) {
3681     // Use VBSL to copy the sign bit.
3682     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3683     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3684                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3685     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3686     if (VT == MVT::f64)
3687       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3688                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3689                          DAG.getConstant(32, MVT::i32));
3690     else /*if (VT == MVT::f32)*/
3691       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3692     if (SrcVT == MVT::f32) {
3693       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3694       if (VT == MVT::f64)
3695         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3696                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3697                            DAG.getConstant(32, MVT::i32));
3698     } else if (VT == MVT::f32)
3699       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3700                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3701                          DAG.getConstant(32, MVT::i32));
3702     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3703     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3704
3705     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3706                                             MVT::i32);
3707     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3708     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3709                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3710
3711     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3712                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3713                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3714     if (VT == MVT::f32) {
3715       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3716       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3717                         DAG.getConstant(0, MVT::i32));
3718     } else {
3719       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3720     }
3721
3722     return Res;
3723   }
3724
3725   // Bitcast operand 1 to i32.
3726   if (SrcVT == MVT::f64)
3727     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3728                        &Tmp1, 1).getValue(1);
3729   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3730
3731   // Or in the signbit with integer operations.
3732   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3733   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3734   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3735   if (VT == MVT::f32) {
3736     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3737                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3738     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3739                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3740   }
3741
3742   // f64: Or the high part with signbit and then combine two parts.
3743   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3744                      &Tmp0, 1);
3745   SDValue Lo = Tmp0.getValue(0);
3746   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3747   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3748   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3749 }
3750
3751 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3752   MachineFunction &MF = DAG.getMachineFunction();
3753   MachineFrameInfo *MFI = MF.getFrameInfo();
3754   MFI->setReturnAddressIsTaken(true);
3755
3756   if (!isa<ConstantSDNode>(Op.getOperand(0))) {
3757     DAG.getContext()->emitError("argument to '__builtin_return_address' must "
3758                                 "be a constant integer");
3759     return SDValue();
3760   }
3761
3762   EVT VT = Op.getValueType();
3763   SDLoc dl(Op);
3764   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3765   if (Depth) {
3766     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3767     SDValue Offset = DAG.getConstant(4, MVT::i32);
3768     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3769                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3770                        MachinePointerInfo(), false, false, false, 0);
3771   }
3772
3773   // Return LR, which contains the return address. Mark it an implicit live-in.
3774   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3775   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3776 }
3777
3778 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3779   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3780   MFI->setFrameAddressIsTaken(true);
3781
3782   EVT VT = Op.getValueType();
3783   SDLoc dl(Op);  // FIXME probably not meaningful
3784   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3785   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3786     ? ARM::R7 : ARM::R11;
3787   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3788   while (Depth--)
3789     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3790                             MachinePointerInfo(),
3791                             false, false, false, 0);
3792   return FrameAddr;
3793 }
3794
3795 /// ExpandBITCAST - If the target supports VFP, this function is called to
3796 /// expand a bit convert where either the source or destination type is i64 to
3797 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3798 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3799 /// vectors), since the legalizer won't know what to do with that.
3800 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3801   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3802   SDLoc dl(N);
3803   SDValue Op = N->getOperand(0);
3804
3805   // This function is only supposed to be called for i64 types, either as the
3806   // source or destination of the bit convert.
3807   EVT SrcVT = Op.getValueType();
3808   EVT DstVT = N->getValueType(0);
3809   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3810          "ExpandBITCAST called for non-i64 type");
3811
3812   // Turn i64->f64 into VMOVDRR.
3813   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3814     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3815                              DAG.getConstant(0, MVT::i32));
3816     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3817                              DAG.getConstant(1, MVT::i32));
3818     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3819                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3820   }
3821
3822   // Turn f64->i64 into VMOVRRD.
3823   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3824     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3825                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3826     // Merge the pieces into a single i64 value.
3827     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3828   }
3829
3830   return SDValue();
3831 }
3832
3833 /// getZeroVector - Returns a vector of specified type with all zero elements.
3834 /// Zero vectors are used to represent vector negation and in those cases
3835 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3836 /// not support i64 elements, so sometimes the zero vectors will need to be
3837 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3838 /// zero vector.
3839 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3840   assert(VT.isVector() && "Expected a vector type");
3841   // The canonical modified immediate encoding of a zero vector is....0!
3842   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3843   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3844   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3845   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3846 }
3847
3848 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3849 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3850 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3851                                                 SelectionDAG &DAG) const {
3852   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3853   EVT VT = Op.getValueType();
3854   unsigned VTBits = VT.getSizeInBits();
3855   SDLoc dl(Op);
3856   SDValue ShOpLo = Op.getOperand(0);
3857   SDValue ShOpHi = Op.getOperand(1);
3858   SDValue ShAmt  = Op.getOperand(2);
3859   SDValue ARMcc;
3860   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3861
3862   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3863
3864   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3865                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3866   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3867   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3868                                    DAG.getConstant(VTBits, MVT::i32));
3869   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3870   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3871   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3872
3873   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3874   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3875                           ARMcc, DAG, dl);
3876   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3877   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3878                            CCR, Cmp);
3879
3880   SDValue Ops[2] = { Lo, Hi };
3881   return DAG.getMergeValues(Ops, 2, dl);
3882 }
3883
3884 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3885 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3886 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3887                                                SelectionDAG &DAG) const {
3888   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3889   EVT VT = Op.getValueType();
3890   unsigned VTBits = VT.getSizeInBits();
3891   SDLoc dl(Op);
3892   SDValue ShOpLo = Op.getOperand(0);
3893   SDValue ShOpHi = Op.getOperand(1);
3894   SDValue ShAmt  = Op.getOperand(2);
3895   SDValue ARMcc;
3896
3897   assert(Op.getOpcode() == ISD::SHL_PARTS);
3898   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3899                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3900   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3901   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3902                                    DAG.getConstant(VTBits, MVT::i32));
3903   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3904   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3905
3906   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3907   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3908   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3909                           ARMcc, DAG, dl);
3910   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3911   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3912                            CCR, Cmp);
3913
3914   SDValue Ops[2] = { Lo, Hi };
3915   return DAG.getMergeValues(Ops, 2, dl);
3916 }
3917
3918 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3919                                             SelectionDAG &DAG) const {
3920   // The rounding mode is in bits 23:22 of the FPSCR.
3921   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3922   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3923   // so that the shift + and get folded into a bitfield extract.
3924   SDLoc dl(Op);
3925   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3926                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3927                                               MVT::i32));
3928   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3929                                   DAG.getConstant(1U << 22, MVT::i32));
3930   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3931                               DAG.getConstant(22, MVT::i32));
3932   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3933                      DAG.getConstant(3, MVT::i32));
3934 }
3935
3936 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3937                          const ARMSubtarget *ST) {
3938   EVT VT = N->getValueType(0);
3939   SDLoc dl(N);
3940
3941   if (!ST->hasV6T2Ops())
3942     return SDValue();
3943
3944   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3945   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3946 }
3947
3948 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3949 /// for each 16-bit element from operand, repeated.  The basic idea is to
3950 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3951 ///
3952 /// Trace for v4i16:
3953 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
3954 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3955 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3956 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3957 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
3958 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
3959 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3960 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
3961 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3962   EVT VT = N->getValueType(0);
3963   SDLoc DL(N);
3964
3965   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
3966   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
3967   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
3968   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
3969   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
3970   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
3971 }
3972
3973 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
3974 /// bit-count for each 16-bit element from the operand.  We need slightly
3975 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
3976 /// 64/128-bit registers.
3977 ///
3978 /// Trace for v4i16:
3979 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
3980 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
3981 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
3982 /// v4i16:Extracted = [k0    k1    k2    k3    ]
3983 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
3984   EVT VT = N->getValueType(0);
3985   SDLoc DL(N);
3986
3987   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
3988   if (VT.is64BitVector()) {
3989     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
3990     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
3991                        DAG.getIntPtrConstant(0));
3992   } else {
3993     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
3994                                     BitCounts, DAG.getIntPtrConstant(0));
3995     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
3996   }
3997 }
3998
3999 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4000 /// bit-count for each 32-bit element from the operand.  The idea here is
4001 /// to split the vector into 16-bit elements, leverage the 16-bit count
4002 /// routine, and then combine the results.
4003 ///
4004 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4005 /// input    = [v0    v1    ] (vi: 32-bit elements)
4006 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4007 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4008 /// vrev: N0 = [k1 k0 k3 k2 ]
4009 ///            [k0 k1 k2 k3 ]
4010 ///       N1 =+[k1 k0 k3 k2 ]
4011 ///            [k0 k2 k1 k3 ]
4012 ///       N2 =+[k1 k3 k0 k2 ]
4013 ///            [k0    k2    k1    k3    ]
4014 /// Extended =+[k1    k3    k0    k2    ]
4015 ///            [k0    k2    ]
4016 /// Extracted=+[k1    k3    ]
4017 ///
4018 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4019   EVT VT = N->getValueType(0);
4020   SDLoc DL(N);
4021
4022   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4023
4024   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4025   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4026   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4027   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4028   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4029
4030   if (VT.is64BitVector()) {
4031     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4032     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4033                        DAG.getIntPtrConstant(0));
4034   } else {
4035     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4036                                     DAG.getIntPtrConstant(0));
4037     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4038   }
4039 }
4040
4041 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4042                           const ARMSubtarget *ST) {
4043   EVT VT = N->getValueType(0);
4044
4045   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4046   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4047           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4048          "Unexpected type for custom ctpop lowering");
4049
4050   if (VT.getVectorElementType() == MVT::i32)
4051     return lowerCTPOP32BitElements(N, DAG);
4052   else
4053     return lowerCTPOP16BitElements(N, DAG);
4054 }
4055
4056 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4057                           const ARMSubtarget *ST) {
4058   EVT VT = N->getValueType(0);
4059   SDLoc dl(N);
4060
4061   if (!VT.isVector())
4062     return SDValue();
4063
4064   // Lower vector shifts on NEON to use VSHL.
4065   assert(ST->hasNEON() && "unexpected vector shift");
4066
4067   // Left shifts translate directly to the vshiftu intrinsic.
4068   if (N->getOpcode() == ISD::SHL)
4069     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4070                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4071                        N->getOperand(0), N->getOperand(1));
4072
4073   assert((N->getOpcode() == ISD::SRA ||
4074           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4075
4076   // NEON uses the same intrinsics for both left and right shifts.  For
4077   // right shifts, the shift amounts are negative, so negate the vector of
4078   // shift amounts.
4079   EVT ShiftVT = N->getOperand(1).getValueType();
4080   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4081                                      getZeroVector(ShiftVT, DAG, dl),
4082                                      N->getOperand(1));
4083   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4084                              Intrinsic::arm_neon_vshifts :
4085                              Intrinsic::arm_neon_vshiftu);
4086   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4087                      DAG.getConstant(vshiftInt, MVT::i32),
4088                      N->getOperand(0), NegatedCount);
4089 }
4090
4091 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4092                                 const ARMSubtarget *ST) {
4093   EVT VT = N->getValueType(0);
4094   SDLoc dl(N);
4095
4096   // We can get here for a node like i32 = ISD::SHL i32, i64
4097   if (VT != MVT::i64)
4098     return SDValue();
4099
4100   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4101          "Unknown shift to lower!");
4102
4103   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4104   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4105       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4106     return SDValue();
4107
4108   // If we are in thumb mode, we don't have RRX.
4109   if (ST->isThumb1Only()) return SDValue();
4110
4111   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4112   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4113                            DAG.getConstant(0, MVT::i32));
4114   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4115                            DAG.getConstant(1, MVT::i32));
4116
4117   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4118   // captures the result into a carry flag.
4119   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4120   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
4121
4122   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4123   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4124
4125   // Merge the pieces into a single i64 value.
4126  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4127 }
4128
4129 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4130   SDValue TmpOp0, TmpOp1;
4131   bool Invert = false;
4132   bool Swap = false;
4133   unsigned Opc = 0;
4134
4135   SDValue Op0 = Op.getOperand(0);
4136   SDValue Op1 = Op.getOperand(1);
4137   SDValue CC = Op.getOperand(2);
4138   EVT VT = Op.getValueType();
4139   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4140   SDLoc dl(Op);
4141
4142   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4143     switch (SetCCOpcode) {
4144     default: llvm_unreachable("Illegal FP comparison");
4145     case ISD::SETUNE:
4146     case ISD::SETNE:  Invert = true; // Fallthrough
4147     case ISD::SETOEQ:
4148     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4149     case ISD::SETOLT:
4150     case ISD::SETLT: Swap = true; // Fallthrough
4151     case ISD::SETOGT:
4152     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4153     case ISD::SETOLE:
4154     case ISD::SETLE:  Swap = true; // Fallthrough
4155     case ISD::SETOGE:
4156     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4157     case ISD::SETUGE: Swap = true; // Fallthrough
4158     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4159     case ISD::SETUGT: Swap = true; // Fallthrough
4160     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4161     case ISD::SETUEQ: Invert = true; // Fallthrough
4162     case ISD::SETONE:
4163       // Expand this to (OLT | OGT).
4164       TmpOp0 = Op0;
4165       TmpOp1 = Op1;
4166       Opc = ISD::OR;
4167       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4168       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4169       break;
4170     case ISD::SETUO: Invert = true; // Fallthrough
4171     case ISD::SETO:
4172       // Expand this to (OLT | OGE).
4173       TmpOp0 = Op0;
4174       TmpOp1 = Op1;
4175       Opc = ISD::OR;
4176       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4177       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4178       break;
4179     }
4180   } else {
4181     // Integer comparisons.
4182     switch (SetCCOpcode) {
4183     default: llvm_unreachable("Illegal integer comparison");
4184     case ISD::SETNE:  Invert = true;
4185     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4186     case ISD::SETLT:  Swap = true;
4187     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4188     case ISD::SETLE:  Swap = true;
4189     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4190     case ISD::SETULT: Swap = true;
4191     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4192     case ISD::SETULE: Swap = true;
4193     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4194     }
4195
4196     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4197     if (Opc == ARMISD::VCEQ) {
4198
4199       SDValue AndOp;
4200       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4201         AndOp = Op0;
4202       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4203         AndOp = Op1;
4204
4205       // Ignore bitconvert.
4206       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4207         AndOp = AndOp.getOperand(0);
4208
4209       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4210         Opc = ARMISD::VTST;
4211         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4212         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4213         Invert = !Invert;
4214       }
4215     }
4216   }
4217
4218   if (Swap)
4219     std::swap(Op0, Op1);
4220
4221   // If one of the operands is a constant vector zero, attempt to fold the
4222   // comparison to a specialized compare-against-zero form.
4223   SDValue SingleOp;
4224   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4225     SingleOp = Op0;
4226   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4227     if (Opc == ARMISD::VCGE)
4228       Opc = ARMISD::VCLEZ;
4229     else if (Opc == ARMISD::VCGT)
4230       Opc = ARMISD::VCLTZ;
4231     SingleOp = Op1;
4232   }
4233
4234   SDValue Result;
4235   if (SingleOp.getNode()) {
4236     switch (Opc) {
4237     case ARMISD::VCEQ:
4238       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4239     case ARMISD::VCGE:
4240       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4241     case ARMISD::VCLEZ:
4242       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4243     case ARMISD::VCGT:
4244       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4245     case ARMISD::VCLTZ:
4246       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4247     default:
4248       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4249     }
4250   } else {
4251      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4252   }
4253
4254   if (Invert)
4255     Result = DAG.getNOT(dl, Result, VT);
4256
4257   return Result;
4258 }
4259
4260 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4261 /// valid vector constant for a NEON instruction with a "modified immediate"
4262 /// operand (e.g., VMOV).  If so, return the encoded value.
4263 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4264                                  unsigned SplatBitSize, SelectionDAG &DAG,
4265                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4266   unsigned OpCmode, Imm;
4267
4268   // SplatBitSize is set to the smallest size that splats the vector, so a
4269   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4270   // immediate instructions others than VMOV do not support the 8-bit encoding
4271   // of a zero vector, and the default encoding of zero is supposed to be the
4272   // 32-bit version.
4273   if (SplatBits == 0)
4274     SplatBitSize = 32;
4275
4276   switch (SplatBitSize) {
4277   case 8:
4278     if (type != VMOVModImm)
4279       return SDValue();
4280     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4281     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4282     OpCmode = 0xe;
4283     Imm = SplatBits;
4284     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4285     break;
4286
4287   case 16:
4288     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4289     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4290     if ((SplatBits & ~0xff) == 0) {
4291       // Value = 0x00nn: Op=x, Cmode=100x.
4292       OpCmode = 0x8;
4293       Imm = SplatBits;
4294       break;
4295     }
4296     if ((SplatBits & ~0xff00) == 0) {
4297       // Value = 0xnn00: Op=x, Cmode=101x.
4298       OpCmode = 0xa;
4299       Imm = SplatBits >> 8;
4300       break;
4301     }
4302     return SDValue();
4303
4304   case 32:
4305     // NEON's 32-bit VMOV supports splat values where:
4306     // * only one byte is nonzero, or
4307     // * the least significant byte is 0xff and the second byte is nonzero, or
4308     // * the least significant 2 bytes are 0xff and the third is nonzero.
4309     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4310     if ((SplatBits & ~0xff) == 0) {
4311       // Value = 0x000000nn: Op=x, Cmode=000x.
4312       OpCmode = 0;
4313       Imm = SplatBits;
4314       break;
4315     }
4316     if ((SplatBits & ~0xff00) == 0) {
4317       // Value = 0x0000nn00: Op=x, Cmode=001x.
4318       OpCmode = 0x2;
4319       Imm = SplatBits >> 8;
4320       break;
4321     }
4322     if ((SplatBits & ~0xff0000) == 0) {
4323       // Value = 0x00nn0000: Op=x, Cmode=010x.
4324       OpCmode = 0x4;
4325       Imm = SplatBits >> 16;
4326       break;
4327     }
4328     if ((SplatBits & ~0xff000000) == 0) {
4329       // Value = 0xnn000000: Op=x, Cmode=011x.
4330       OpCmode = 0x6;
4331       Imm = SplatBits >> 24;
4332       break;
4333     }
4334
4335     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4336     if (type == OtherModImm) return SDValue();
4337
4338     if ((SplatBits & ~0xffff) == 0 &&
4339         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4340       // Value = 0x0000nnff: Op=x, Cmode=1100.
4341       OpCmode = 0xc;
4342       Imm = SplatBits >> 8;
4343       SplatBits |= 0xff;
4344       break;
4345     }
4346
4347     if ((SplatBits & ~0xffffff) == 0 &&
4348         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4349       // Value = 0x00nnffff: Op=x, Cmode=1101.
4350       OpCmode = 0xd;
4351       Imm = SplatBits >> 16;
4352       SplatBits |= 0xffff;
4353       break;
4354     }
4355
4356     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4357     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4358     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4359     // and fall through here to test for a valid 64-bit splat.  But, then the
4360     // caller would also need to check and handle the change in size.
4361     return SDValue();
4362
4363   case 64: {
4364     if (type != VMOVModImm)
4365       return SDValue();
4366     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4367     uint64_t BitMask = 0xff;
4368     uint64_t Val = 0;
4369     unsigned ImmMask = 1;
4370     Imm = 0;
4371     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4372       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4373         Val |= BitMask;
4374         Imm |= ImmMask;
4375       } else if ((SplatBits & BitMask) != 0) {
4376         return SDValue();
4377       }
4378       BitMask <<= 8;
4379       ImmMask <<= 1;
4380     }
4381     // Op=1, Cmode=1110.
4382     OpCmode = 0x1e;
4383     SplatBits = Val;
4384     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4385     break;
4386   }
4387
4388   default:
4389     llvm_unreachable("unexpected size for isNEONModifiedImm");
4390   }
4391
4392   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4393   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4394 }
4395
4396 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4397                                            const ARMSubtarget *ST) const {
4398   if (!ST->hasVFP3())
4399     return SDValue();
4400
4401   bool IsDouble = Op.getValueType() == MVT::f64;
4402   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4403
4404   // Try splatting with a VMOV.f32...
4405   APFloat FPVal = CFP->getValueAPF();
4406   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4407
4408   if (ImmVal != -1) {
4409     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4410       // We have code in place to select a valid ConstantFP already, no need to
4411       // do any mangling.
4412       return Op;
4413     }
4414
4415     // It's a float and we are trying to use NEON operations where
4416     // possible. Lower it to a splat followed by an extract.
4417     SDLoc DL(Op);
4418     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4419     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4420                                       NewVal);
4421     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4422                        DAG.getConstant(0, MVT::i32));
4423   }
4424
4425   // The rest of our options are NEON only, make sure that's allowed before
4426   // proceeding..
4427   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4428     return SDValue();
4429
4430   EVT VMovVT;
4431   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4432
4433   // It wouldn't really be worth bothering for doubles except for one very
4434   // important value, which does happen to match: 0.0. So make sure we don't do
4435   // anything stupid.
4436   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4437     return SDValue();
4438
4439   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4440   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4441                                      false, VMOVModImm);
4442   if (NewVal != SDValue()) {
4443     SDLoc DL(Op);
4444     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4445                                       NewVal);
4446     if (IsDouble)
4447       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4448
4449     // It's a float: cast and extract a vector element.
4450     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4451                                        VecConstant);
4452     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4453                        DAG.getConstant(0, MVT::i32));
4454   }
4455
4456   // Finally, try a VMVN.i32
4457   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4458                              false, VMVNModImm);
4459   if (NewVal != SDValue()) {
4460     SDLoc DL(Op);
4461     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4462
4463     if (IsDouble)
4464       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4465
4466     // It's a float: cast and extract a vector element.
4467     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4468                                        VecConstant);
4469     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4470                        DAG.getConstant(0, MVT::i32));
4471   }
4472
4473   return SDValue();
4474 }
4475
4476 // check if an VEXT instruction can handle the shuffle mask when the
4477 // vector sources of the shuffle are the same.
4478 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4479   unsigned NumElts = VT.getVectorNumElements();
4480
4481   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4482   if (M[0] < 0)
4483     return false;
4484
4485   Imm = M[0];
4486
4487   // If this is a VEXT shuffle, the immediate value is the index of the first
4488   // element.  The other shuffle indices must be the successive elements after
4489   // the first one.
4490   unsigned ExpectedElt = Imm;
4491   for (unsigned i = 1; i < NumElts; ++i) {
4492     // Increment the expected index.  If it wraps around, just follow it
4493     // back to index zero and keep going.
4494     ++ExpectedElt;
4495     if (ExpectedElt == NumElts)
4496       ExpectedElt = 0;
4497
4498     if (M[i] < 0) continue; // ignore UNDEF indices
4499     if (ExpectedElt != static_cast<unsigned>(M[i]))
4500       return false;
4501   }
4502
4503   return true;
4504 }
4505
4506
4507 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4508                        bool &ReverseVEXT, unsigned &Imm) {
4509   unsigned NumElts = VT.getVectorNumElements();
4510   ReverseVEXT = false;
4511
4512   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4513   if (M[0] < 0)
4514     return false;
4515
4516   Imm = M[0];
4517
4518   // If this is a VEXT shuffle, the immediate value is the index of the first
4519   // element.  The other shuffle indices must be the successive elements after
4520   // the first one.
4521   unsigned ExpectedElt = Imm;
4522   for (unsigned i = 1; i < NumElts; ++i) {
4523     // Increment the expected index.  If it wraps around, it may still be
4524     // a VEXT but the source vectors must be swapped.
4525     ExpectedElt += 1;
4526     if (ExpectedElt == NumElts * 2) {
4527       ExpectedElt = 0;
4528       ReverseVEXT = true;
4529     }
4530
4531     if (M[i] < 0) continue; // ignore UNDEF indices
4532     if (ExpectedElt != static_cast<unsigned>(M[i]))
4533       return false;
4534   }
4535
4536   // Adjust the index value if the source operands will be swapped.
4537   if (ReverseVEXT)
4538     Imm -= NumElts;
4539
4540   return true;
4541 }
4542
4543 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4544 /// instruction with the specified blocksize.  (The order of the elements
4545 /// within each block of the vector is reversed.)
4546 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4547   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4548          "Only possible block sizes for VREV are: 16, 32, 64");
4549
4550   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4551   if (EltSz == 64)
4552     return false;
4553
4554   unsigned NumElts = VT.getVectorNumElements();
4555   unsigned BlockElts = M[0] + 1;
4556   // If the first shuffle index is UNDEF, be optimistic.
4557   if (M[0] < 0)
4558     BlockElts = BlockSize / EltSz;
4559
4560   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4561     return false;
4562
4563   for (unsigned i = 0; i < NumElts; ++i) {
4564     if (M[i] < 0) continue; // ignore UNDEF indices
4565     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4566       return false;
4567   }
4568
4569   return true;
4570 }
4571
4572 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4573   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4574   // range, then 0 is placed into the resulting vector. So pretty much any mask
4575   // of 8 elements can work here.
4576   return VT == MVT::v8i8 && M.size() == 8;
4577 }
4578
4579 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4580   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4581   if (EltSz == 64)
4582     return false;
4583
4584   unsigned NumElts = VT.getVectorNumElements();
4585   WhichResult = (M[0] == 0 ? 0 : 1);
4586   for (unsigned i = 0; i < NumElts; i += 2) {
4587     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4588         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4589       return false;
4590   }
4591   return true;
4592 }
4593
4594 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4595 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4596 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4597 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4598   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4599   if (EltSz == 64)
4600     return false;
4601
4602   unsigned NumElts = VT.getVectorNumElements();
4603   WhichResult = (M[0] == 0 ? 0 : 1);
4604   for (unsigned i = 0; i < NumElts; i += 2) {
4605     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4606         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4607       return false;
4608   }
4609   return true;
4610 }
4611
4612 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4613   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4614   if (EltSz == 64)
4615     return false;
4616
4617   unsigned NumElts = VT.getVectorNumElements();
4618   WhichResult = (M[0] == 0 ? 0 : 1);
4619   for (unsigned i = 0; i != NumElts; ++i) {
4620     if (M[i] < 0) continue; // ignore UNDEF indices
4621     if ((unsigned) M[i] != 2 * i + WhichResult)
4622       return false;
4623   }
4624
4625   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4626   if (VT.is64BitVector() && EltSz == 32)
4627     return false;
4628
4629   return true;
4630 }
4631
4632 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4633 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4634 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4635 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4636   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4637   if (EltSz == 64)
4638     return false;
4639
4640   unsigned Half = VT.getVectorNumElements() / 2;
4641   WhichResult = (M[0] == 0 ? 0 : 1);
4642   for (unsigned j = 0; j != 2; ++j) {
4643     unsigned Idx = WhichResult;
4644     for (unsigned i = 0; i != Half; ++i) {
4645       int MIdx = M[i + j * Half];
4646       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4647         return false;
4648       Idx += 2;
4649     }
4650   }
4651
4652   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4653   if (VT.is64BitVector() && EltSz == 32)
4654     return false;
4655
4656   return true;
4657 }
4658
4659 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4660   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4661   if (EltSz == 64)
4662     return false;
4663
4664   unsigned NumElts = VT.getVectorNumElements();
4665   WhichResult = (M[0] == 0 ? 0 : 1);
4666   unsigned Idx = WhichResult * NumElts / 2;
4667   for (unsigned i = 0; i != NumElts; i += 2) {
4668     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4669         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4670       return false;
4671     Idx += 1;
4672   }
4673
4674   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4675   if (VT.is64BitVector() && EltSz == 32)
4676     return false;
4677
4678   return true;
4679 }
4680
4681 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4682 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4683 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4684 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4685   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4686   if (EltSz == 64)
4687     return false;
4688
4689   unsigned NumElts = VT.getVectorNumElements();
4690   WhichResult = (M[0] == 0 ? 0 : 1);
4691   unsigned Idx = WhichResult * NumElts / 2;
4692   for (unsigned i = 0; i != NumElts; i += 2) {
4693     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4694         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4695       return false;
4696     Idx += 1;
4697   }
4698
4699   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4700   if (VT.is64BitVector() && EltSz == 32)
4701     return false;
4702
4703   return true;
4704 }
4705
4706 /// \return true if this is a reverse operation on an vector.
4707 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4708   unsigned NumElts = VT.getVectorNumElements();
4709   // Make sure the mask has the right size.
4710   if (NumElts != M.size())
4711       return false;
4712
4713   // Look for <15, ..., 3, -1, 1, 0>.
4714   for (unsigned i = 0; i != NumElts; ++i)
4715     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4716       return false;
4717
4718   return true;
4719 }
4720
4721 // If N is an integer constant that can be moved into a register in one
4722 // instruction, return an SDValue of such a constant (will become a MOV
4723 // instruction).  Otherwise return null.
4724 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4725                                      const ARMSubtarget *ST, SDLoc dl) {
4726   uint64_t Val;
4727   if (!isa<ConstantSDNode>(N))
4728     return SDValue();
4729   Val = cast<ConstantSDNode>(N)->getZExtValue();
4730
4731   if (ST->isThumb1Only()) {
4732     if (Val <= 255 || ~Val <= 255)
4733       return DAG.getConstant(Val, MVT::i32);
4734   } else {
4735     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4736       return DAG.getConstant(Val, MVT::i32);
4737   }
4738   return SDValue();
4739 }
4740
4741 // If this is a case we can't handle, return null and let the default
4742 // expansion code take care of it.
4743 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4744                                              const ARMSubtarget *ST) const {
4745   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4746   SDLoc dl(Op);
4747   EVT VT = Op.getValueType();
4748
4749   APInt SplatBits, SplatUndef;
4750   unsigned SplatBitSize;
4751   bool HasAnyUndefs;
4752   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4753     if (SplatBitSize <= 64) {
4754       // Check if an immediate VMOV works.
4755       EVT VmovVT;
4756       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4757                                       SplatUndef.getZExtValue(), SplatBitSize,
4758                                       DAG, VmovVT, VT.is128BitVector(),
4759                                       VMOVModImm);
4760       if (Val.getNode()) {
4761         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4762         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4763       }
4764
4765       // Try an immediate VMVN.
4766       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4767       Val = isNEONModifiedImm(NegatedImm,
4768                                       SplatUndef.getZExtValue(), SplatBitSize,
4769                                       DAG, VmovVT, VT.is128BitVector(),
4770                                       VMVNModImm);
4771       if (Val.getNode()) {
4772         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4773         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4774       }
4775
4776       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4777       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4778         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4779         if (ImmVal != -1) {
4780           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4781           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4782         }
4783       }
4784     }
4785   }
4786
4787   // Scan through the operands to see if only one value is used.
4788   //
4789   // As an optimisation, even if more than one value is used it may be more
4790   // profitable to splat with one value then change some lanes.
4791   //
4792   // Heuristically we decide to do this if the vector has a "dominant" value,
4793   // defined as splatted to more than half of the lanes.
4794   unsigned NumElts = VT.getVectorNumElements();
4795   bool isOnlyLowElement = true;
4796   bool usesOnlyOneValue = true;
4797   bool hasDominantValue = false;
4798   bool isConstant = true;
4799
4800   // Map of the number of times a particular SDValue appears in the
4801   // element list.
4802   DenseMap<SDValue, unsigned> ValueCounts;
4803   SDValue Value;
4804   for (unsigned i = 0; i < NumElts; ++i) {
4805     SDValue V = Op.getOperand(i);
4806     if (V.getOpcode() == ISD::UNDEF)
4807       continue;
4808     if (i > 0)
4809       isOnlyLowElement = false;
4810     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4811       isConstant = false;
4812
4813     ValueCounts.insert(std::make_pair(V, 0));
4814     unsigned &Count = ValueCounts[V];
4815
4816     // Is this value dominant? (takes up more than half of the lanes)
4817     if (++Count > (NumElts / 2)) {
4818       hasDominantValue = true;
4819       Value = V;
4820     }
4821   }
4822   if (ValueCounts.size() != 1)
4823     usesOnlyOneValue = false;
4824   if (!Value.getNode() && ValueCounts.size() > 0)
4825     Value = ValueCounts.begin()->first;
4826
4827   if (ValueCounts.size() == 0)
4828     return DAG.getUNDEF(VT);
4829
4830   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
4831   // Keep going if we are hitting this case.
4832   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
4833     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4834
4835   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4836
4837   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4838   // i32 and try again.
4839   if (hasDominantValue && EltSize <= 32) {
4840     if (!isConstant) {
4841       SDValue N;
4842
4843       // If we are VDUPing a value that comes directly from a vector, that will
4844       // cause an unnecessary move to and from a GPR, where instead we could
4845       // just use VDUPLANE. We can only do this if the lane being extracted
4846       // is at a constant index, as the VDUP from lane instructions only have
4847       // constant-index forms.
4848       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4849           isa<ConstantSDNode>(Value->getOperand(1))) {
4850         // We need to create a new undef vector to use for the VDUPLANE if the
4851         // size of the vector from which we get the value is different than the
4852         // size of the vector that we need to create. We will insert the element
4853         // such that the register coalescer will remove unnecessary copies.
4854         if (VT != Value->getOperand(0).getValueType()) {
4855           ConstantSDNode *constIndex;
4856           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4857           assert(constIndex && "The index is not a constant!");
4858           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4859                              VT.getVectorNumElements();
4860           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4861                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4862                         Value, DAG.getConstant(index, MVT::i32)),
4863                            DAG.getConstant(index, MVT::i32));
4864         } else
4865           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4866                         Value->getOperand(0), Value->getOperand(1));
4867       } else
4868         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4869
4870       if (!usesOnlyOneValue) {
4871         // The dominant value was splatted as 'N', but we now have to insert
4872         // all differing elements.
4873         for (unsigned I = 0; I < NumElts; ++I) {
4874           if (Op.getOperand(I) == Value)
4875             continue;
4876           SmallVector<SDValue, 3> Ops;
4877           Ops.push_back(N);
4878           Ops.push_back(Op.getOperand(I));
4879           Ops.push_back(DAG.getConstant(I, MVT::i32));
4880           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4881         }
4882       }
4883       return N;
4884     }
4885     if (VT.getVectorElementType().isFloatingPoint()) {
4886       SmallVector<SDValue, 8> Ops;
4887       for (unsigned i = 0; i < NumElts; ++i)
4888         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4889                                   Op.getOperand(i)));
4890       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4891       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4892       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4893       if (Val.getNode())
4894         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4895     }
4896     if (usesOnlyOneValue) {
4897       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4898       if (isConstant && Val.getNode())
4899         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4900     }
4901   }
4902
4903   // If all elements are constants and the case above didn't get hit, fall back
4904   // to the default expansion, which will generate a load from the constant
4905   // pool.
4906   if (isConstant)
4907     return SDValue();
4908
4909   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4910   if (NumElts >= 4) {
4911     SDValue shuffle = ReconstructShuffle(Op, DAG);
4912     if (shuffle != SDValue())
4913       return shuffle;
4914   }
4915
4916   // Vectors with 32- or 64-bit elements can be built by directly assigning
4917   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4918   // will be legalized.
4919   if (EltSize >= 32) {
4920     // Do the expansion with floating-point types, since that is what the VFP
4921     // registers are defined to use, and since i64 is not legal.
4922     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4923     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4924     SmallVector<SDValue, 8> Ops;
4925     for (unsigned i = 0; i < NumElts; ++i)
4926       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4927     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4928     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4929   }
4930
4931   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
4932   // know the default expansion would otherwise fall back on something even
4933   // worse. For a vector with one or two non-undef values, that's
4934   // scalar_to_vector for the elements followed by a shuffle (provided the
4935   // shuffle is valid for the target) and materialization element by element
4936   // on the stack followed by a load for everything else.
4937   if (!isConstant && !usesOnlyOneValue) {
4938     SDValue Vec = DAG.getUNDEF(VT);
4939     for (unsigned i = 0 ; i < NumElts; ++i) {
4940       SDValue V = Op.getOperand(i);
4941       if (V.getOpcode() == ISD::UNDEF)
4942         continue;
4943       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
4944       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
4945     }
4946     return Vec;
4947   }
4948
4949   return SDValue();
4950 }
4951
4952 // Gather data to see if the operation can be modelled as a
4953 // shuffle in combination with VEXTs.
4954 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4955                                               SelectionDAG &DAG) const {
4956   SDLoc dl(Op);
4957   EVT VT = Op.getValueType();
4958   unsigned NumElts = VT.getVectorNumElements();
4959
4960   SmallVector<SDValue, 2> SourceVecs;
4961   SmallVector<unsigned, 2> MinElts;
4962   SmallVector<unsigned, 2> MaxElts;
4963
4964   for (unsigned i = 0; i < NumElts; ++i) {
4965     SDValue V = Op.getOperand(i);
4966     if (V.getOpcode() == ISD::UNDEF)
4967       continue;
4968     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4969       // A shuffle can only come from building a vector from various
4970       // elements of other vectors.
4971       return SDValue();
4972     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4973                VT.getVectorElementType()) {
4974       // This code doesn't know how to handle shuffles where the vector
4975       // element types do not match (this happens because type legalization
4976       // promotes the return type of EXTRACT_VECTOR_ELT).
4977       // FIXME: It might be appropriate to extend this code to handle
4978       // mismatched types.
4979       return SDValue();
4980     }
4981
4982     // Record this extraction against the appropriate vector if possible...
4983     SDValue SourceVec = V.getOperand(0);
4984     // If the element number isn't a constant, we can't effectively
4985     // analyze what's going on.
4986     if (!isa<ConstantSDNode>(V.getOperand(1)))
4987       return SDValue();
4988     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4989     bool FoundSource = false;
4990     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4991       if (SourceVecs[j] == SourceVec) {
4992         if (MinElts[j] > EltNo)
4993           MinElts[j] = EltNo;
4994         if (MaxElts[j] < EltNo)
4995           MaxElts[j] = EltNo;
4996         FoundSource = true;
4997         break;
4998       }
4999     }
5000
5001     // Or record a new source if not...
5002     if (!FoundSource) {
5003       SourceVecs.push_back(SourceVec);
5004       MinElts.push_back(EltNo);
5005       MaxElts.push_back(EltNo);
5006     }
5007   }
5008
5009   // Currently only do something sane when at most two source vectors
5010   // involved.
5011   if (SourceVecs.size() > 2)
5012     return SDValue();
5013
5014   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5015   int VEXTOffsets[2] = {0, 0};
5016
5017   // This loop extracts the usage patterns of the source vectors
5018   // and prepares appropriate SDValues for a shuffle if possible.
5019   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5020     if (SourceVecs[i].getValueType() == VT) {
5021       // No VEXT necessary
5022       ShuffleSrcs[i] = SourceVecs[i];
5023       VEXTOffsets[i] = 0;
5024       continue;
5025     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5026       // It probably isn't worth padding out a smaller vector just to
5027       // break it down again in a shuffle.
5028       return SDValue();
5029     }
5030
5031     // Since only 64-bit and 128-bit vectors are legal on ARM and
5032     // we've eliminated the other cases...
5033     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5034            "unexpected vector sizes in ReconstructShuffle");
5035
5036     if (MaxElts[i] - MinElts[i] >= NumElts) {
5037       // Span too large for a VEXT to cope
5038       return SDValue();
5039     }
5040
5041     if (MinElts[i] >= NumElts) {
5042       // The extraction can just take the second half
5043       VEXTOffsets[i] = NumElts;
5044       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5045                                    SourceVecs[i],
5046                                    DAG.getIntPtrConstant(NumElts));
5047     } else if (MaxElts[i] < NumElts) {
5048       // The extraction can just take the first half
5049       VEXTOffsets[i] = 0;
5050       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5051                                    SourceVecs[i],
5052                                    DAG.getIntPtrConstant(0));
5053     } else {
5054       // An actual VEXT is needed
5055       VEXTOffsets[i] = MinElts[i];
5056       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5057                                      SourceVecs[i],
5058                                      DAG.getIntPtrConstant(0));
5059       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5060                                      SourceVecs[i],
5061                                      DAG.getIntPtrConstant(NumElts));
5062       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5063                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5064     }
5065   }
5066
5067   SmallVector<int, 8> Mask;
5068
5069   for (unsigned i = 0; i < NumElts; ++i) {
5070     SDValue Entry = Op.getOperand(i);
5071     if (Entry.getOpcode() == ISD::UNDEF) {
5072       Mask.push_back(-1);
5073       continue;
5074     }
5075
5076     SDValue ExtractVec = Entry.getOperand(0);
5077     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5078                                           .getOperand(1))->getSExtValue();
5079     if (ExtractVec == SourceVecs[0]) {
5080       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5081     } else {
5082       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5083     }
5084   }
5085
5086   // Final check before we try to produce nonsense...
5087   if (isShuffleMaskLegal(Mask, VT))
5088     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5089                                 &Mask[0]);
5090
5091   return SDValue();
5092 }
5093
5094 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5095 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5096 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5097 /// are assumed to be legal.
5098 bool
5099 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5100                                       EVT VT) const {
5101   if (VT.getVectorNumElements() == 4 &&
5102       (VT.is128BitVector() || VT.is64BitVector())) {
5103     unsigned PFIndexes[4];
5104     for (unsigned i = 0; i != 4; ++i) {
5105       if (M[i] < 0)
5106         PFIndexes[i] = 8;
5107       else
5108         PFIndexes[i] = M[i];
5109     }
5110
5111     // Compute the index in the perfect shuffle table.
5112     unsigned PFTableIndex =
5113       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5114     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5115     unsigned Cost = (PFEntry >> 30);
5116
5117     if (Cost <= 4)
5118       return true;
5119   }
5120
5121   bool ReverseVEXT;
5122   unsigned Imm, WhichResult;
5123
5124   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5125   return (EltSize >= 32 ||
5126           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5127           isVREVMask(M, VT, 64) ||
5128           isVREVMask(M, VT, 32) ||
5129           isVREVMask(M, VT, 16) ||
5130           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5131           isVTBLMask(M, VT) ||
5132           isVTRNMask(M, VT, WhichResult) ||
5133           isVUZPMask(M, VT, WhichResult) ||
5134           isVZIPMask(M, VT, WhichResult) ||
5135           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5136           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5137           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5138           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5139 }
5140
5141 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5142 /// the specified operations to build the shuffle.
5143 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5144                                       SDValue RHS, SelectionDAG &DAG,
5145                                       SDLoc dl) {
5146   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5147   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5148   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5149
5150   enum {
5151     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5152     OP_VREV,
5153     OP_VDUP0,
5154     OP_VDUP1,
5155     OP_VDUP2,
5156     OP_VDUP3,
5157     OP_VEXT1,
5158     OP_VEXT2,
5159     OP_VEXT3,
5160     OP_VUZPL, // VUZP, left result
5161     OP_VUZPR, // VUZP, right result
5162     OP_VZIPL, // VZIP, left result
5163     OP_VZIPR, // VZIP, right result
5164     OP_VTRNL, // VTRN, left result
5165     OP_VTRNR  // VTRN, right result
5166   };
5167
5168   if (OpNum == OP_COPY) {
5169     if (LHSID == (1*9+2)*9+3) return LHS;
5170     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5171     return RHS;
5172   }
5173
5174   SDValue OpLHS, OpRHS;
5175   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5176   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5177   EVT VT = OpLHS.getValueType();
5178
5179   switch (OpNum) {
5180   default: llvm_unreachable("Unknown shuffle opcode!");
5181   case OP_VREV:
5182     // VREV divides the vector in half and swaps within the half.
5183     if (VT.getVectorElementType() == MVT::i32 ||
5184         VT.getVectorElementType() == MVT::f32)
5185       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5186     // vrev <4 x i16> -> VREV32
5187     if (VT.getVectorElementType() == MVT::i16)
5188       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5189     // vrev <4 x i8> -> VREV16
5190     assert(VT.getVectorElementType() == MVT::i8);
5191     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5192   case OP_VDUP0:
5193   case OP_VDUP1:
5194   case OP_VDUP2:
5195   case OP_VDUP3:
5196     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5197                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5198   case OP_VEXT1:
5199   case OP_VEXT2:
5200   case OP_VEXT3:
5201     return DAG.getNode(ARMISD::VEXT, dl, VT,
5202                        OpLHS, OpRHS,
5203                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5204   case OP_VUZPL:
5205   case OP_VUZPR:
5206     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5207                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5208   case OP_VZIPL:
5209   case OP_VZIPR:
5210     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5211                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5212   case OP_VTRNL:
5213   case OP_VTRNR:
5214     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5215                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5216   }
5217 }
5218
5219 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5220                                        ArrayRef<int> ShuffleMask,
5221                                        SelectionDAG &DAG) {
5222   // Check to see if we can use the VTBL instruction.
5223   SDValue V1 = Op.getOperand(0);
5224   SDValue V2 = Op.getOperand(1);
5225   SDLoc DL(Op);
5226
5227   SmallVector<SDValue, 8> VTBLMask;
5228   for (ArrayRef<int>::iterator
5229          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5230     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5231
5232   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5233     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5234                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5235                                    &VTBLMask[0], 8));
5236
5237   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5238                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5239                                  &VTBLMask[0], 8));
5240 }
5241
5242 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5243                                                       SelectionDAG &DAG) {
5244   SDLoc DL(Op);
5245   SDValue OpLHS = Op.getOperand(0);
5246   EVT VT = OpLHS.getValueType();
5247
5248   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5249          "Expect an v8i16/v16i8 type");
5250   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5251   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5252   // extract the first 8 bytes into the top double word and the last 8 bytes
5253   // into the bottom double word. The v8i16 case is similar.
5254   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5255   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5256                      DAG.getConstant(ExtractNum, MVT::i32));
5257 }
5258
5259 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5260   SDValue V1 = Op.getOperand(0);
5261   SDValue V2 = Op.getOperand(1);
5262   SDLoc dl(Op);
5263   EVT VT = Op.getValueType();
5264   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5265
5266   // Convert shuffles that are directly supported on NEON to target-specific
5267   // DAG nodes, instead of keeping them as shuffles and matching them again
5268   // during code selection.  This is more efficient and avoids the possibility
5269   // of inconsistencies between legalization and selection.
5270   // FIXME: floating-point vectors should be canonicalized to integer vectors
5271   // of the same time so that they get CSEd properly.
5272   ArrayRef<int> ShuffleMask = SVN->getMask();
5273
5274   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5275   if (EltSize <= 32) {
5276     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5277       int Lane = SVN->getSplatIndex();
5278       // If this is undef splat, generate it via "just" vdup, if possible.
5279       if (Lane == -1) Lane = 0;
5280
5281       // Test if V1 is a SCALAR_TO_VECTOR.
5282       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5283         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5284       }
5285       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5286       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5287       // reaches it).
5288       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5289           !isa<ConstantSDNode>(V1.getOperand(0))) {
5290         bool IsScalarToVector = true;
5291         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5292           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5293             IsScalarToVector = false;
5294             break;
5295           }
5296         if (IsScalarToVector)
5297           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5298       }
5299       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5300                          DAG.getConstant(Lane, MVT::i32));
5301     }
5302
5303     bool ReverseVEXT;
5304     unsigned Imm;
5305     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5306       if (ReverseVEXT)
5307         std::swap(V1, V2);
5308       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5309                          DAG.getConstant(Imm, MVT::i32));
5310     }
5311
5312     if (isVREVMask(ShuffleMask, VT, 64))
5313       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5314     if (isVREVMask(ShuffleMask, VT, 32))
5315       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5316     if (isVREVMask(ShuffleMask, VT, 16))
5317       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5318
5319     if (V2->getOpcode() == ISD::UNDEF &&
5320         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5321       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5322                          DAG.getConstant(Imm, MVT::i32));
5323     }
5324
5325     // Check for Neon shuffles that modify both input vectors in place.
5326     // If both results are used, i.e., if there are two shuffles with the same
5327     // source operands and with masks corresponding to both results of one of
5328     // these operations, DAG memoization will ensure that a single node is
5329     // used for both shuffles.
5330     unsigned WhichResult;
5331     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5332       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5333                          V1, V2).getValue(WhichResult);
5334     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5335       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5336                          V1, V2).getValue(WhichResult);
5337     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5338       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5339                          V1, V2).getValue(WhichResult);
5340
5341     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5342       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5343                          V1, V1).getValue(WhichResult);
5344     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5345       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5346                          V1, V1).getValue(WhichResult);
5347     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5348       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5349                          V1, V1).getValue(WhichResult);
5350   }
5351
5352   // If the shuffle is not directly supported and it has 4 elements, use
5353   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5354   unsigned NumElts = VT.getVectorNumElements();
5355   if (NumElts == 4) {
5356     unsigned PFIndexes[4];
5357     for (unsigned i = 0; i != 4; ++i) {
5358       if (ShuffleMask[i] < 0)
5359         PFIndexes[i] = 8;
5360       else
5361         PFIndexes[i] = ShuffleMask[i];
5362     }
5363
5364     // Compute the index in the perfect shuffle table.
5365     unsigned PFTableIndex =
5366       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5367     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5368     unsigned Cost = (PFEntry >> 30);
5369
5370     if (Cost <= 4)
5371       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5372   }
5373
5374   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5375   if (EltSize >= 32) {
5376     // Do the expansion with floating-point types, since that is what the VFP
5377     // registers are defined to use, and since i64 is not legal.
5378     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5379     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5380     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5381     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5382     SmallVector<SDValue, 8> Ops;
5383     for (unsigned i = 0; i < NumElts; ++i) {
5384       if (ShuffleMask[i] < 0)
5385         Ops.push_back(DAG.getUNDEF(EltVT));
5386       else
5387         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5388                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5389                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5390                                                   MVT::i32)));
5391     }
5392     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5393     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5394   }
5395
5396   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5397     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5398
5399   if (VT == MVT::v8i8) {
5400     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5401     if (NewOp.getNode())
5402       return NewOp;
5403   }
5404
5405   return SDValue();
5406 }
5407
5408 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5409   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5410   SDValue Lane = Op.getOperand(2);
5411   if (!isa<ConstantSDNode>(Lane))
5412     return SDValue();
5413
5414   return Op;
5415 }
5416
5417 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5418   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5419   SDValue Lane = Op.getOperand(1);
5420   if (!isa<ConstantSDNode>(Lane))
5421     return SDValue();
5422
5423   SDValue Vec = Op.getOperand(0);
5424   if (Op.getValueType() == MVT::i32 &&
5425       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5426     SDLoc dl(Op);
5427     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5428   }
5429
5430   return Op;
5431 }
5432
5433 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5434   // The only time a CONCAT_VECTORS operation can have legal types is when
5435   // two 64-bit vectors are concatenated to a 128-bit vector.
5436   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5437          "unexpected CONCAT_VECTORS");
5438   SDLoc dl(Op);
5439   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5440   SDValue Op0 = Op.getOperand(0);
5441   SDValue Op1 = Op.getOperand(1);
5442   if (Op0.getOpcode() != ISD::UNDEF)
5443     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5444                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5445                       DAG.getIntPtrConstant(0));
5446   if (Op1.getOpcode() != ISD::UNDEF)
5447     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5448                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5449                       DAG.getIntPtrConstant(1));
5450   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5451 }
5452
5453 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5454 /// element has been zero/sign-extended, depending on the isSigned parameter,
5455 /// from an integer type half its size.
5456 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5457                                    bool isSigned) {
5458   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5459   EVT VT = N->getValueType(0);
5460   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5461     SDNode *BVN = N->getOperand(0).getNode();
5462     if (BVN->getValueType(0) != MVT::v4i32 ||
5463         BVN->getOpcode() != ISD::BUILD_VECTOR)
5464       return false;
5465     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5466     unsigned HiElt = 1 - LoElt;
5467     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5468     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5469     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5470     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5471     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5472       return false;
5473     if (isSigned) {
5474       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5475           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5476         return true;
5477     } else {
5478       if (Hi0->isNullValue() && Hi1->isNullValue())
5479         return true;
5480     }
5481     return false;
5482   }
5483
5484   if (N->getOpcode() != ISD::BUILD_VECTOR)
5485     return false;
5486
5487   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5488     SDNode *Elt = N->getOperand(i).getNode();
5489     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5490       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5491       unsigned HalfSize = EltSize / 2;
5492       if (isSigned) {
5493         if (!isIntN(HalfSize, C->getSExtValue()))
5494           return false;
5495       } else {
5496         if (!isUIntN(HalfSize, C->getZExtValue()))
5497           return false;
5498       }
5499       continue;
5500     }
5501     return false;
5502   }
5503
5504   return true;
5505 }
5506
5507 /// isSignExtended - Check if a node is a vector value that is sign-extended
5508 /// or a constant BUILD_VECTOR with sign-extended elements.
5509 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5510   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5511     return true;
5512   if (isExtendedBUILD_VECTOR(N, DAG, true))
5513     return true;
5514   return false;
5515 }
5516
5517 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5518 /// or a constant BUILD_VECTOR with zero-extended elements.
5519 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5520   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5521     return true;
5522   if (isExtendedBUILD_VECTOR(N, DAG, false))
5523     return true;
5524   return false;
5525 }
5526
5527 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5528   if (OrigVT.getSizeInBits() >= 64)
5529     return OrigVT;
5530
5531   assert(OrigVT.isSimple() && "Expecting a simple value type");
5532
5533   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5534   switch (OrigSimpleTy) {
5535   default: llvm_unreachable("Unexpected Vector Type");
5536   case MVT::v2i8:
5537   case MVT::v2i16:
5538      return MVT::v2i32;
5539   case MVT::v4i8:
5540     return  MVT::v4i16;
5541   }
5542 }
5543
5544 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5545 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5546 /// We insert the required extension here to get the vector to fill a D register.
5547 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5548                                             const EVT &OrigTy,
5549                                             const EVT &ExtTy,
5550                                             unsigned ExtOpcode) {
5551   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5552   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5553   // 64-bits we need to insert a new extension so that it will be 64-bits.
5554   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5555   if (OrigTy.getSizeInBits() >= 64)
5556     return N;
5557
5558   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5559   EVT NewVT = getExtensionTo64Bits(OrigTy);
5560
5561   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5562 }
5563
5564 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5565 /// does not do any sign/zero extension. If the original vector is less
5566 /// than 64 bits, an appropriate extension will be added after the load to
5567 /// reach a total size of 64 bits. We have to add the extension separately
5568 /// because ARM does not have a sign/zero extending load for vectors.
5569 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5570   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5571
5572   // The load already has the right type.
5573   if (ExtendedTy == LD->getMemoryVT())
5574     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5575                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5576                 LD->isNonTemporal(), LD->isInvariant(),
5577                 LD->getAlignment());
5578
5579   // We need to create a zextload/sextload. We cannot just create a load
5580   // followed by a zext/zext node because LowerMUL is also run during normal
5581   // operation legalization where we can't create illegal types.
5582   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5583                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5584                         LD->getMemoryVT(), LD->isVolatile(),
5585                         LD->isNonTemporal(), LD->getAlignment());
5586 }
5587
5588 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5589 /// extending load, or BUILD_VECTOR with extended elements, return the
5590 /// unextended value. The unextended vector should be 64 bits so that it can
5591 /// be used as an operand to a VMULL instruction. If the original vector size
5592 /// before extension is less than 64 bits we add a an extension to resize
5593 /// the vector to 64 bits.
5594 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5595   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5596     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5597                                         N->getOperand(0)->getValueType(0),
5598                                         N->getValueType(0),
5599                                         N->getOpcode());
5600
5601   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5602     return SkipLoadExtensionForVMULL(LD, DAG);
5603
5604   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5605   // have been legalized as a BITCAST from v4i32.
5606   if (N->getOpcode() == ISD::BITCAST) {
5607     SDNode *BVN = N->getOperand(0).getNode();
5608     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5609            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5610     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5611     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5612                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5613   }
5614   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5615   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5616   EVT VT = N->getValueType(0);
5617   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5618   unsigned NumElts = VT.getVectorNumElements();
5619   MVT TruncVT = MVT::getIntegerVT(EltSize);
5620   SmallVector<SDValue, 8> Ops;
5621   for (unsigned i = 0; i != NumElts; ++i) {
5622     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5623     const APInt &CInt = C->getAPIntValue();
5624     // Element types smaller than 32 bits are not legal, so use i32 elements.
5625     // The values are implicitly truncated so sext vs. zext doesn't matter.
5626     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5627   }
5628   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5629                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5630 }
5631
5632 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5633   unsigned Opcode = N->getOpcode();
5634   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5635     SDNode *N0 = N->getOperand(0).getNode();
5636     SDNode *N1 = N->getOperand(1).getNode();
5637     return N0->hasOneUse() && N1->hasOneUse() &&
5638       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5639   }
5640   return false;
5641 }
5642
5643 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5644   unsigned Opcode = N->getOpcode();
5645   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5646     SDNode *N0 = N->getOperand(0).getNode();
5647     SDNode *N1 = N->getOperand(1).getNode();
5648     return N0->hasOneUse() && N1->hasOneUse() &&
5649       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5650   }
5651   return false;
5652 }
5653
5654 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5655   // Multiplications are only custom-lowered for 128-bit vectors so that
5656   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5657   EVT VT = Op.getValueType();
5658   assert(VT.is128BitVector() && VT.isInteger() &&
5659          "unexpected type for custom-lowering ISD::MUL");
5660   SDNode *N0 = Op.getOperand(0).getNode();
5661   SDNode *N1 = Op.getOperand(1).getNode();
5662   unsigned NewOpc = 0;
5663   bool isMLA = false;
5664   bool isN0SExt = isSignExtended(N0, DAG);
5665   bool isN1SExt = isSignExtended(N1, DAG);
5666   if (isN0SExt && isN1SExt)
5667     NewOpc = ARMISD::VMULLs;
5668   else {
5669     bool isN0ZExt = isZeroExtended(N0, DAG);
5670     bool isN1ZExt = isZeroExtended(N1, DAG);
5671     if (isN0ZExt && isN1ZExt)
5672       NewOpc = ARMISD::VMULLu;
5673     else if (isN1SExt || isN1ZExt) {
5674       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5675       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5676       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5677         NewOpc = ARMISD::VMULLs;
5678         isMLA = true;
5679       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5680         NewOpc = ARMISD::VMULLu;
5681         isMLA = true;
5682       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5683         std::swap(N0, N1);
5684         NewOpc = ARMISD::VMULLu;
5685         isMLA = true;
5686       }
5687     }
5688
5689     if (!NewOpc) {
5690       if (VT == MVT::v2i64)
5691         // Fall through to expand this.  It is not legal.
5692         return SDValue();
5693       else
5694         // Other vector multiplications are legal.
5695         return Op;
5696     }
5697   }
5698
5699   // Legalize to a VMULL instruction.
5700   SDLoc DL(Op);
5701   SDValue Op0;
5702   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5703   if (!isMLA) {
5704     Op0 = SkipExtensionForVMULL(N0, DAG);
5705     assert(Op0.getValueType().is64BitVector() &&
5706            Op1.getValueType().is64BitVector() &&
5707            "unexpected types for extended operands to VMULL");
5708     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5709   }
5710
5711   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5712   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5713   //   vmull q0, d4, d6
5714   //   vmlal q0, d5, d6
5715   // is faster than
5716   //   vaddl q0, d4, d5
5717   //   vmovl q1, d6
5718   //   vmul  q0, q0, q1
5719   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5720   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5721   EVT Op1VT = Op1.getValueType();
5722   return DAG.getNode(N0->getOpcode(), DL, VT,
5723                      DAG.getNode(NewOpc, DL, VT,
5724                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5725                      DAG.getNode(NewOpc, DL, VT,
5726                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5727 }
5728
5729 static SDValue
5730 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5731   // Convert to float
5732   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5733   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5734   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5735   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5736   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5737   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5738   // Get reciprocal estimate.
5739   // float4 recip = vrecpeq_f32(yf);
5740   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5741                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5742   // Because char has a smaller range than uchar, we can actually get away
5743   // without any newton steps.  This requires that we use a weird bias
5744   // of 0xb000, however (again, this has been exhaustively tested).
5745   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5746   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5747   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5748   Y = DAG.getConstant(0xb000, MVT::i32);
5749   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5750   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5751   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5752   // Convert back to short.
5753   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5754   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5755   return X;
5756 }
5757
5758 static SDValue
5759 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5760   SDValue N2;
5761   // Convert to float.
5762   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5763   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5764   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5765   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5766   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5767   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5768
5769   // Use reciprocal estimate and one refinement step.
5770   // float4 recip = vrecpeq_f32(yf);
5771   // recip *= vrecpsq_f32(yf, recip);
5772   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5773                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5774   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5775                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5776                    N1, N2);
5777   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5778   // Because short has a smaller range than ushort, we can actually get away
5779   // with only a single newton step.  This requires that we use a weird bias
5780   // of 89, however (again, this has been exhaustively tested).
5781   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5782   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5783   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5784   N1 = DAG.getConstant(0x89, MVT::i32);
5785   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5786   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5787   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5788   // Convert back to integer and return.
5789   // return vmovn_s32(vcvt_s32_f32(result));
5790   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5791   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5792   return N0;
5793 }
5794
5795 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5796   EVT VT = Op.getValueType();
5797   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5798          "unexpected type for custom-lowering ISD::SDIV");
5799
5800   SDLoc dl(Op);
5801   SDValue N0 = Op.getOperand(0);
5802   SDValue N1 = Op.getOperand(1);
5803   SDValue N2, N3;
5804
5805   if (VT == MVT::v8i8) {
5806     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5807     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5808
5809     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5810                      DAG.getIntPtrConstant(4));
5811     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5812                      DAG.getIntPtrConstant(4));
5813     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5814                      DAG.getIntPtrConstant(0));
5815     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5816                      DAG.getIntPtrConstant(0));
5817
5818     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5819     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5820
5821     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5822     N0 = LowerCONCAT_VECTORS(N0, DAG);
5823
5824     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5825     return N0;
5826   }
5827   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5828 }
5829
5830 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5831   EVT VT = Op.getValueType();
5832   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5833          "unexpected type for custom-lowering ISD::UDIV");
5834
5835   SDLoc dl(Op);
5836   SDValue N0 = Op.getOperand(0);
5837   SDValue N1 = Op.getOperand(1);
5838   SDValue N2, N3;
5839
5840   if (VT == MVT::v8i8) {
5841     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5842     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5843
5844     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5845                      DAG.getIntPtrConstant(4));
5846     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5847                      DAG.getIntPtrConstant(4));
5848     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5849                      DAG.getIntPtrConstant(0));
5850     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5851                      DAG.getIntPtrConstant(0));
5852
5853     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5854     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5855
5856     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5857     N0 = LowerCONCAT_VECTORS(N0, DAG);
5858
5859     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5860                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5861                      N0);
5862     return N0;
5863   }
5864
5865   // v4i16 sdiv ... Convert to float.
5866   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5867   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5868   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5869   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5870   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5871   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5872
5873   // Use reciprocal estimate and two refinement steps.
5874   // float4 recip = vrecpeq_f32(yf);
5875   // recip *= vrecpsq_f32(yf, recip);
5876   // recip *= vrecpsq_f32(yf, recip);
5877   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5878                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5879   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5880                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5881                    BN1, N2);
5882   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5883   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5884                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5885                    BN1, N2);
5886   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5887   // Simply multiplying by the reciprocal estimate can leave us a few ulps
5888   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5889   // and that it will never cause us to return an answer too large).
5890   // float4 result = as_float4(as_int4(xf*recip) + 2);
5891   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5892   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5893   N1 = DAG.getConstant(2, MVT::i32);
5894   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5895   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5896   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5897   // Convert back to integer and return.
5898   // return vmovn_u32(vcvt_s32_f32(result));
5899   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5900   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5901   return N0;
5902 }
5903
5904 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5905   EVT VT = Op.getNode()->getValueType(0);
5906   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5907
5908   unsigned Opc;
5909   bool ExtraOp = false;
5910   switch (Op.getOpcode()) {
5911   default: llvm_unreachable("Invalid code");
5912   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5913   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5914   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5915   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5916   }
5917
5918   if (!ExtraOp)
5919     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5920                        Op.getOperand(1));
5921   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5922                      Op.getOperand(1), Op.getOperand(2));
5923 }
5924
5925 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
5926   assert(Subtarget->isTargetDarwin());
5927
5928   // For iOS, we want to call an alternative entry point: __sincos_stret,
5929   // return values are passed via sret.
5930   SDLoc dl(Op);
5931   SDValue Arg = Op.getOperand(0);
5932   EVT ArgVT = Arg.getValueType();
5933   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
5934
5935   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
5936   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5937
5938   // Pair of floats / doubles used to pass the result.
5939   StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
5940
5941   // Create stack object for sret.
5942   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
5943   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
5944   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
5945   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
5946
5947   ArgListTy Args;
5948   ArgListEntry Entry;
5949
5950   Entry.Node = SRet;
5951   Entry.Ty = RetTy->getPointerTo();
5952   Entry.isSExt = false;
5953   Entry.isZExt = false;
5954   Entry.isSRet = true;
5955   Args.push_back(Entry);
5956
5957   Entry.Node = Arg;
5958   Entry.Ty = ArgTy;
5959   Entry.isSExt = false;
5960   Entry.isZExt = false;
5961   Args.push_back(Entry);
5962
5963   const char *LibcallName  = (ArgVT == MVT::f64)
5964   ? "__sincos_stret" : "__sincosf_stret";
5965   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
5966
5967   TargetLowering::
5968   CallLoweringInfo CLI(DAG.getEntryNode(), Type::getVoidTy(*DAG.getContext()),
5969                        false, false, false, false, 0,
5970                        CallingConv::C, /*isTaillCall=*/false,
5971                        /*doesNotRet=*/false, /*isReturnValueUsed*/false,
5972                        Callee, Args, DAG, dl);
5973   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
5974
5975   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
5976                                 MachinePointerInfo(), false, false, false, 0);
5977
5978   // Address of cos field.
5979   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
5980                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
5981   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
5982                                 MachinePointerInfo(), false, false, false, 0);
5983
5984   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
5985   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
5986                      LoadSin.getValue(0), LoadCos.getValue(0));
5987 }
5988
5989 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5990   // Monotonic load/store is legal for all targets
5991   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5992     return Op;
5993
5994   // Aquire/Release load/store is not legal for targets without a
5995   // dmb or equivalent available.
5996   return SDValue();
5997 }
5998
5999 static void
6000 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
6001                     SelectionDAG &DAG) {
6002   SDLoc dl(Node);
6003   assert (Node->getValueType(0) == MVT::i64 &&
6004           "Only know how to expand i64 atomics");
6005   AtomicSDNode *AN = cast<AtomicSDNode>(Node);
6006
6007   SmallVector<SDValue, 6> Ops;
6008   Ops.push_back(Node->getOperand(0)); // Chain
6009   Ops.push_back(Node->getOperand(1)); // Ptr
6010   for(unsigned i=2; i<Node->getNumOperands(); i++) {
6011     // Low part
6012     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6013                               Node->getOperand(i), DAG.getIntPtrConstant(0)));
6014     // High part
6015     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6016                               Node->getOperand(i), DAG.getIntPtrConstant(1)));
6017   }
6018   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6019   SDValue Result =
6020     DAG.getAtomic(Node->getOpcode(), dl, MVT::i64, Tys, Ops.data(), Ops.size(),
6021                   cast<MemSDNode>(Node)->getMemOperand(), AN->getOrdering(),
6022                   AN->getSynchScope());
6023   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
6024   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6025   Results.push_back(Result.getValue(2));
6026 }
6027
6028 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6029                                     SmallVectorImpl<SDValue> &Results,
6030                                     SelectionDAG &DAG,
6031                                     const ARMSubtarget *Subtarget) {
6032   SDLoc DL(N);
6033   SDValue Cycles32, OutChain;
6034
6035   if (Subtarget->hasPerfMon()) {
6036     // Under Power Management extensions, the cycle-count is:
6037     //    mrc p15, #0, <Rt>, c9, c13, #0
6038     SDValue Ops[] = { N->getOperand(0), // Chain
6039                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6040                       DAG.getConstant(15, MVT::i32),
6041                       DAG.getConstant(0, MVT::i32),
6042                       DAG.getConstant(9, MVT::i32),
6043                       DAG.getConstant(13, MVT::i32),
6044                       DAG.getConstant(0, MVT::i32)
6045     };
6046
6047     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6048                            DAG.getVTList(MVT::i32, MVT::Other), &Ops[0],
6049                            array_lengthof(Ops));
6050     OutChain = Cycles32.getValue(1);
6051   } else {
6052     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6053     // there are older ARM CPUs that have implementation-specific ways of
6054     // obtaining this information (FIXME!).
6055     Cycles32 = DAG.getConstant(0, MVT::i32);
6056     OutChain = DAG.getEntryNode();
6057   }
6058
6059
6060   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6061                                  Cycles32, DAG.getConstant(0, MVT::i32));
6062   Results.push_back(Cycles64);
6063   Results.push_back(OutChain);
6064 }
6065
6066 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6067   switch (Op.getOpcode()) {
6068   default: llvm_unreachable("Don't know how to custom lower this!");
6069   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6070   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6071   case ISD::GlobalAddress:
6072     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
6073       LowerGlobalAddressELF(Op, DAG);
6074   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6075   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6076   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6077   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6078   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6079   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6080   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6081   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6082   case ISD::SINT_TO_FP:
6083   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6084   case ISD::FP_TO_SINT:
6085   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6086   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6087   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6088   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6089   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6090   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6091   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6092   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6093                                                                Subtarget);
6094   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6095   case ISD::SHL:
6096   case ISD::SRL:
6097   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6098   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6099   case ISD::SRL_PARTS:
6100   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6101   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6102   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6103   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6104   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6105   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6106   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6107   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6108   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6109   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6110   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6111   case ISD::MUL:           return LowerMUL(Op, DAG);
6112   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6113   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6114   case ISD::ADDC:
6115   case ISD::ADDE:
6116   case ISD::SUBC:
6117   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6118   case ISD::ATOMIC_LOAD:
6119   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6120   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6121   case ISD::SDIVREM:
6122   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6123   }
6124 }
6125
6126 /// ReplaceNodeResults - Replace the results of node with an illegal result
6127 /// type with new values built out of custom code.
6128 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6129                                            SmallVectorImpl<SDValue>&Results,
6130                                            SelectionDAG &DAG) const {
6131   SDValue Res;
6132   switch (N->getOpcode()) {
6133   default:
6134     llvm_unreachable("Don't know how to custom expand this!");
6135   case ISD::BITCAST:
6136     Res = ExpandBITCAST(N, DAG);
6137     break;
6138   case ISD::SRL:
6139   case ISD::SRA:
6140     Res = Expand64BitShift(N, DAG, Subtarget);
6141     break;
6142   case ISD::READCYCLECOUNTER:
6143     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6144     return;
6145   case ISD::ATOMIC_STORE:
6146   case ISD::ATOMIC_LOAD:
6147   case ISD::ATOMIC_LOAD_ADD:
6148   case ISD::ATOMIC_LOAD_AND:
6149   case ISD::ATOMIC_LOAD_NAND:
6150   case ISD::ATOMIC_LOAD_OR:
6151   case ISD::ATOMIC_LOAD_SUB:
6152   case ISD::ATOMIC_LOAD_XOR:
6153   case ISD::ATOMIC_SWAP:
6154   case ISD::ATOMIC_CMP_SWAP:
6155   case ISD::ATOMIC_LOAD_MIN:
6156   case ISD::ATOMIC_LOAD_UMIN:
6157   case ISD::ATOMIC_LOAD_MAX:
6158   case ISD::ATOMIC_LOAD_UMAX:
6159     ReplaceATOMIC_OP_64(N, Results, DAG);
6160     return;
6161   }
6162   if (Res.getNode())
6163     Results.push_back(Res);
6164 }
6165
6166 //===----------------------------------------------------------------------===//
6167 //                           ARM Scheduler Hooks
6168 //===----------------------------------------------------------------------===//
6169
6170 MachineBasicBlock *
6171 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
6172                                      MachineBasicBlock *BB,
6173                                      unsigned Size) const {
6174   unsigned dest    = MI->getOperand(0).getReg();
6175   unsigned ptr     = MI->getOperand(1).getReg();
6176   unsigned oldval  = MI->getOperand(2).getReg();
6177   unsigned newval  = MI->getOperand(3).getReg();
6178   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6179   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(4).getImm());
6180   DebugLoc dl = MI->getDebugLoc();
6181   bool isThumb2 = Subtarget->isThumb2();
6182
6183   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6184   unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
6185     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6186     (const TargetRegisterClass*)&ARM::GPRRegClass);
6187
6188   if (isThumb2) {
6189     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6190     MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
6191     MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
6192   }
6193
6194   unsigned ldrOpc, strOpc;
6195   getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6196
6197   MachineFunction *MF = BB->getParent();
6198   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6199   MachineFunction::iterator It = BB;
6200   ++It; // insert the new blocks after the current block
6201
6202   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6203   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6204   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6205   MF->insert(It, loop1MBB);
6206   MF->insert(It, loop2MBB);
6207   MF->insert(It, exitMBB);
6208
6209   // Transfer the remainder of BB and its successor edges to exitMBB.
6210   exitMBB->splice(exitMBB->begin(), BB,
6211                   llvm::next(MachineBasicBlock::iterator(MI)),
6212                   BB->end());
6213   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6214
6215   //  thisMBB:
6216   //   ...
6217   //   fallthrough --> loop1MBB
6218   BB->addSuccessor(loop1MBB);
6219
6220   // loop1MBB:
6221   //   ldrex dest, [ptr]
6222   //   cmp dest, oldval
6223   //   bne exitMBB
6224   BB = loop1MBB;
6225   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6226   if (ldrOpc == ARM::t2LDREX)
6227     MIB.addImm(0);
6228   AddDefaultPred(MIB);
6229   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6230                  .addReg(dest).addReg(oldval));
6231   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6232     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6233   BB->addSuccessor(loop2MBB);
6234   BB->addSuccessor(exitMBB);
6235
6236   // loop2MBB:
6237   //   strex scratch, newval, [ptr]
6238   //   cmp scratch, #0
6239   //   bne loop1MBB
6240   BB = loop2MBB;
6241   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
6242   if (strOpc == ARM::t2STREX)
6243     MIB.addImm(0);
6244   AddDefaultPred(MIB);
6245   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6246                  .addReg(scratch).addImm(0));
6247   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6248     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6249   BB->addSuccessor(loop1MBB);
6250   BB->addSuccessor(exitMBB);
6251
6252   //  exitMBB:
6253   //   ...
6254   BB = exitMBB;
6255
6256   MI->eraseFromParent();   // The instruction is gone now.
6257
6258   return BB;
6259 }
6260
6261 MachineBasicBlock *
6262 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6263                                     unsigned Size, unsigned BinOpcode) const {
6264   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6265   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6266
6267   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6268   MachineFunction *MF = BB->getParent();
6269   MachineFunction::iterator It = BB;
6270   ++It;
6271
6272   unsigned dest = MI->getOperand(0).getReg();
6273   unsigned ptr = MI->getOperand(1).getReg();
6274   unsigned incr = MI->getOperand(2).getReg();
6275   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6276   DebugLoc dl = MI->getDebugLoc();
6277   bool isThumb2 = Subtarget->isThumb2();
6278
6279   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6280   if (isThumb2) {
6281     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6282     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6283     MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6284   }
6285
6286   unsigned ldrOpc, strOpc;
6287   getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6288
6289   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6290   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6291   MF->insert(It, loopMBB);
6292   MF->insert(It, exitMBB);
6293
6294   // Transfer the remainder of BB and its successor edges to exitMBB.
6295   exitMBB->splice(exitMBB->begin(), BB,
6296                   llvm::next(MachineBasicBlock::iterator(MI)),
6297                   BB->end());
6298   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6299
6300   const TargetRegisterClass *TRC = isThumb2 ?
6301     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6302     (const TargetRegisterClass*)&ARM::GPRRegClass;
6303   unsigned scratch = MRI.createVirtualRegister(TRC);
6304   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
6305
6306   //  thisMBB:
6307   //   ...
6308   //   fallthrough --> loopMBB
6309   BB->addSuccessor(loopMBB);
6310
6311   //  loopMBB:
6312   //   ldrex dest, ptr
6313   //   <binop> scratch2, dest, incr
6314   //   strex scratch, scratch2, ptr
6315   //   cmp scratch, #0
6316   //   bne- loopMBB
6317   //   fallthrough --> exitMBB
6318   BB = loopMBB;
6319   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6320   if (ldrOpc == ARM::t2LDREX)
6321     MIB.addImm(0);
6322   AddDefaultPred(MIB);
6323   if (BinOpcode) {
6324     // operand order needs to go the other way for NAND
6325     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
6326       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6327                      addReg(incr).addReg(dest)).addReg(0);
6328     else
6329       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6330                      addReg(dest).addReg(incr)).addReg(0);
6331   }
6332
6333   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6334   if (strOpc == ARM::t2STREX)
6335     MIB.addImm(0);
6336   AddDefaultPred(MIB);
6337   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6338                  .addReg(scratch).addImm(0));
6339   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6340     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6341
6342   BB->addSuccessor(loopMBB);
6343   BB->addSuccessor(exitMBB);
6344
6345   //  exitMBB:
6346   //   ...
6347   BB = exitMBB;
6348
6349   MI->eraseFromParent();   // The instruction is gone now.
6350
6351   return BB;
6352 }
6353
6354 MachineBasicBlock *
6355 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
6356                                           MachineBasicBlock *BB,
6357                                           unsigned Size,
6358                                           bool signExtend,
6359                                           ARMCC::CondCodes Cond) const {
6360   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6361
6362   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6363   MachineFunction *MF = BB->getParent();
6364   MachineFunction::iterator It = BB;
6365   ++It;
6366
6367   unsigned dest = MI->getOperand(0).getReg();
6368   unsigned ptr = MI->getOperand(1).getReg();
6369   unsigned incr = MI->getOperand(2).getReg();
6370   unsigned oldval = dest;
6371   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6372   DebugLoc dl = MI->getDebugLoc();
6373   bool isThumb2 = Subtarget->isThumb2();
6374
6375   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6376   if (isThumb2) {
6377     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6378     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6379     MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6380   }
6381
6382   unsigned ldrOpc, strOpc, extendOpc;
6383   getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6384   switch (Size) {
6385   default: llvm_unreachable("unsupported size for AtomicBinaryMinMax!");
6386   case 1:
6387     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
6388     break;
6389   case 2:
6390     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
6391     break;
6392   case 4:
6393     extendOpc = 0;
6394     break;
6395   }
6396
6397   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6398   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6399   MF->insert(It, loopMBB);
6400   MF->insert(It, exitMBB);
6401
6402   // Transfer the remainder of BB and its successor edges to exitMBB.
6403   exitMBB->splice(exitMBB->begin(), BB,
6404                   llvm::next(MachineBasicBlock::iterator(MI)),
6405                   BB->end());
6406   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6407
6408   const TargetRegisterClass *TRC = isThumb2 ?
6409     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6410     (const TargetRegisterClass*)&ARM::GPRRegClass;
6411   unsigned scratch = MRI.createVirtualRegister(TRC);
6412   unsigned scratch2 = MRI.createVirtualRegister(TRC);
6413
6414   //  thisMBB:
6415   //   ...
6416   //   fallthrough --> loopMBB
6417   BB->addSuccessor(loopMBB);
6418
6419   //  loopMBB:
6420   //   ldrex dest, ptr
6421   //   (sign extend dest, if required)
6422   //   cmp dest, incr
6423   //   cmov.cond scratch2, incr, dest
6424   //   strex scratch, scratch2, ptr
6425   //   cmp scratch, #0
6426   //   bne- loopMBB
6427   //   fallthrough --> exitMBB
6428   BB = loopMBB;
6429   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6430   if (ldrOpc == ARM::t2LDREX)
6431     MIB.addImm(0);
6432   AddDefaultPred(MIB);
6433
6434   // Sign extend the value, if necessary.
6435   if (signExtend && extendOpc) {
6436     oldval = MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass
6437                                                 : &ARM::GPRnopcRegClass);
6438     if (!isThumb2)
6439       MRI.constrainRegClass(dest, &ARM::GPRnopcRegClass);
6440     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
6441                      .addReg(dest)
6442                      .addImm(0));
6443   }
6444
6445   // Build compare and cmov instructions.
6446   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6447                  .addReg(oldval).addReg(incr));
6448   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
6449          .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
6450
6451   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6452   if (strOpc == ARM::t2STREX)
6453     MIB.addImm(0);
6454   AddDefaultPred(MIB);
6455   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6456                  .addReg(scratch).addImm(0));
6457   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6458     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6459
6460   BB->addSuccessor(loopMBB);
6461   BB->addSuccessor(exitMBB);
6462
6463   //  exitMBB:
6464   //   ...
6465   BB = exitMBB;
6466
6467   MI->eraseFromParent();   // The instruction is gone now.
6468
6469   return BB;
6470 }
6471
6472 MachineBasicBlock *
6473 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
6474                                       unsigned Op1, unsigned Op2,
6475                                       bool NeedsCarry, bool IsCmpxchg,
6476                                       bool IsMinMax, ARMCC::CondCodes CC) const {
6477   // This also handles ATOMIC_SWAP and ATOMIC_STORE, indicated by Op1==0.
6478   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6479
6480   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6481   MachineFunction *MF = BB->getParent();
6482   MachineFunction::iterator It = BB;
6483   ++It;
6484
6485   bool isStore = (MI->getOpcode() == ARM::ATOMIC_STORE_I64);
6486   unsigned offset = (isStore ? -2 : 0);
6487   unsigned destlo = MI->getOperand(0).getReg();
6488   unsigned desthi = MI->getOperand(1).getReg();
6489   unsigned ptr = MI->getOperand(offset+2).getReg();
6490   unsigned vallo = MI->getOperand(offset+3).getReg();
6491   unsigned valhi = MI->getOperand(offset+4).getReg();
6492   unsigned OrdIdx = offset + (IsCmpxchg ? 7 : 5);
6493   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(OrdIdx).getImm());
6494   DebugLoc dl = MI->getDebugLoc();
6495   bool isThumb2 = Subtarget->isThumb2();
6496
6497   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6498   if (isThumb2) {
6499     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6500     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6501     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6502     MRI.constrainRegClass(vallo, &ARM::rGPRRegClass);
6503     MRI.constrainRegClass(valhi, &ARM::rGPRRegClass);
6504   }
6505
6506   unsigned ldrOpc, strOpc;
6507   getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6508
6509   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6510   MachineBasicBlock *contBB = 0, *cont2BB = 0;
6511   if (IsCmpxchg || IsMinMax)
6512     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
6513   if (IsCmpxchg)
6514     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
6515   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6516
6517   MF->insert(It, loopMBB);
6518   if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6519   if (IsCmpxchg) MF->insert(It, cont2BB);
6520   MF->insert(It, exitMBB);
6521
6522   // Transfer the remainder of BB and its successor edges to exitMBB.
6523   exitMBB->splice(exitMBB->begin(), BB,
6524                   llvm::next(MachineBasicBlock::iterator(MI)),
6525                   BB->end());
6526   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6527
6528   const TargetRegisterClass *TRC = isThumb2 ?
6529     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6530     (const TargetRegisterClass*)&ARM::GPRRegClass;
6531   unsigned storesuccess = MRI.createVirtualRegister(TRC);
6532
6533   //  thisMBB:
6534   //   ...
6535   //   fallthrough --> loopMBB
6536   BB->addSuccessor(loopMBB);
6537
6538   //  loopMBB:
6539   //   ldrexd r2, r3, ptr
6540   //   <binopa> r0, r2, incr
6541   //   <binopb> r1, r3, incr
6542   //   strexd storesuccess, r0, r1, ptr
6543   //   cmp storesuccess, #0
6544   //   bne- loopMBB
6545   //   fallthrough --> exitMBB
6546   BB = loopMBB;
6547
6548   if (!isStore) {
6549     // Load
6550     if (isThumb2) {
6551       AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6552                      .addReg(destlo, RegState::Define)
6553                      .addReg(desthi, RegState::Define)
6554                      .addReg(ptr));
6555     } else {
6556       unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6557       AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6558                      .addReg(GPRPair0, RegState::Define).addReg(ptr));
6559       // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
6560       BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6561         .addReg(GPRPair0, 0, ARM::gsub_0);
6562       BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6563         .addReg(GPRPair0, 0, ARM::gsub_1);
6564     }
6565   }
6566
6567   unsigned StoreLo, StoreHi;
6568   if (IsCmpxchg) {
6569     // Add early exit
6570     for (unsigned i = 0; i < 2; i++) {
6571       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6572                                                          ARM::CMPrr))
6573                      .addReg(i == 0 ? destlo : desthi)
6574                      .addReg(i == 0 ? vallo : valhi));
6575       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6576         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6577       BB->addSuccessor(exitMBB);
6578       BB->addSuccessor(i == 0 ? contBB : cont2BB);
6579       BB = (i == 0 ? contBB : cont2BB);
6580     }
6581
6582     // Copy to physregs for strexd
6583     StoreLo = MI->getOperand(5).getReg();
6584     StoreHi = MI->getOperand(6).getReg();
6585   } else if (Op1) {
6586     // Perform binary operation
6587     unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6588     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6589                    .addReg(destlo).addReg(vallo))
6590         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6591     unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6592     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6593                    .addReg(desthi).addReg(valhi))
6594         .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6595
6596     StoreLo = tmpRegLo;
6597     StoreHi = tmpRegHi;
6598   } else {
6599     // Copy to physregs for strexd
6600     StoreLo = vallo;
6601     StoreHi = valhi;
6602   }
6603   if (IsMinMax) {
6604     // Compare and branch to exit block.
6605     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6606       .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6607     BB->addSuccessor(exitMBB);
6608     BB->addSuccessor(contBB);
6609     BB = contBB;
6610     StoreLo = vallo;
6611     StoreHi = valhi;
6612   }
6613
6614   // Store
6615   if (isThumb2) {
6616     MRI.constrainRegClass(StoreLo, &ARM::rGPRRegClass);
6617     MRI.constrainRegClass(StoreHi, &ARM::rGPRRegClass);
6618     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6619                    .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6620   } else {
6621     // Marshal a pair...
6622     unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6623     unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6624     unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6625     BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6626     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6627       .addReg(UndefPair)
6628       .addReg(StoreLo)
6629       .addImm(ARM::gsub_0);
6630     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6631       .addReg(r1)
6632       .addReg(StoreHi)
6633       .addImm(ARM::gsub_1);
6634
6635     // ...and store it
6636     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6637                    .addReg(StorePair).addReg(ptr));
6638   }
6639   // Cmp+jump
6640   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6641                  .addReg(storesuccess).addImm(0));
6642   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6643     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6644
6645   BB->addSuccessor(loopMBB);
6646   BB->addSuccessor(exitMBB);
6647
6648   //  exitMBB:
6649   //   ...
6650   BB = exitMBB;
6651
6652   MI->eraseFromParent();   // The instruction is gone now.
6653
6654   return BB;
6655 }
6656
6657 MachineBasicBlock *
6658 ARMTargetLowering::EmitAtomicLoad64(MachineInstr *MI, MachineBasicBlock *BB) const {
6659
6660   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6661
6662   unsigned destlo = MI->getOperand(0).getReg();
6663   unsigned desthi = MI->getOperand(1).getReg();
6664   unsigned ptr = MI->getOperand(2).getReg();
6665   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6666   DebugLoc dl = MI->getDebugLoc();
6667   bool isThumb2 = Subtarget->isThumb2();
6668
6669   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6670   if (isThumb2) {
6671     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6672     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6673     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6674   }
6675   unsigned ldrOpc, strOpc;
6676   getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6677
6678   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(ldrOpc));
6679
6680   if (isThumb2) {
6681     MIB.addReg(destlo, RegState::Define)
6682        .addReg(desthi, RegState::Define)
6683        .addReg(ptr);
6684
6685   } else {
6686     unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6687     MIB.addReg(GPRPair0, RegState::Define).addReg(ptr);
6688
6689     // Copy GPRPair0 into dest.  (This copy will normally be coalesced.)
6690     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), destlo)
6691       .addReg(GPRPair0, 0, ARM::gsub_0);
6692     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), desthi)
6693       .addReg(GPRPair0, 0, ARM::gsub_1);
6694   }
6695   AddDefaultPred(MIB);
6696
6697   MI->eraseFromParent();   // The instruction is gone now.
6698
6699   return BB;
6700 }
6701
6702 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6703 /// registers the function context.
6704 void ARMTargetLowering::
6705 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6706                        MachineBasicBlock *DispatchBB, int FI) const {
6707   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6708   DebugLoc dl = MI->getDebugLoc();
6709   MachineFunction *MF = MBB->getParent();
6710   MachineRegisterInfo *MRI = &MF->getRegInfo();
6711   MachineConstantPool *MCP = MF->getConstantPool();
6712   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6713   const Function *F = MF->getFunction();
6714
6715   bool isThumb = Subtarget->isThumb();
6716   bool isThumb2 = Subtarget->isThumb2();
6717
6718   unsigned PCLabelId = AFI->createPICLabelUId();
6719   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6720   ARMConstantPoolValue *CPV =
6721     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6722   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6723
6724   const TargetRegisterClass *TRC = isThumb ?
6725     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6726     (const TargetRegisterClass*)&ARM::GPRRegClass;
6727
6728   // Grab constant pool and fixed stack memory operands.
6729   MachineMemOperand *CPMMO =
6730     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6731                              MachineMemOperand::MOLoad, 4, 4);
6732
6733   MachineMemOperand *FIMMOSt =
6734     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6735                              MachineMemOperand::MOStore, 4, 4);
6736
6737   // Load the address of the dispatch MBB into the jump buffer.
6738   if (isThumb2) {
6739     // Incoming value: jbuf
6740     //   ldr.n  r5, LCPI1_1
6741     //   orr    r5, r5, #1
6742     //   add    r5, pc
6743     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6744     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6745     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6746                    .addConstantPoolIndex(CPI)
6747                    .addMemOperand(CPMMO));
6748     // Set the low bit because of thumb mode.
6749     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6750     AddDefaultCC(
6751       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6752                      .addReg(NewVReg1, RegState::Kill)
6753                      .addImm(0x01)));
6754     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6755     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6756       .addReg(NewVReg2, RegState::Kill)
6757       .addImm(PCLabelId);
6758     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6759                    .addReg(NewVReg3, RegState::Kill)
6760                    .addFrameIndex(FI)
6761                    .addImm(36)  // &jbuf[1] :: pc
6762                    .addMemOperand(FIMMOSt));
6763   } else if (isThumb) {
6764     // Incoming value: jbuf
6765     //   ldr.n  r1, LCPI1_4
6766     //   add    r1, pc
6767     //   mov    r2, #1
6768     //   orrs   r1, r2
6769     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6770     //   str    r1, [r2]
6771     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6772     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6773                    .addConstantPoolIndex(CPI)
6774                    .addMemOperand(CPMMO));
6775     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6776     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6777       .addReg(NewVReg1, RegState::Kill)
6778       .addImm(PCLabelId);
6779     // Set the low bit because of thumb mode.
6780     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6781     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6782                    .addReg(ARM::CPSR, RegState::Define)
6783                    .addImm(1));
6784     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6785     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6786                    .addReg(ARM::CPSR, RegState::Define)
6787                    .addReg(NewVReg2, RegState::Kill)
6788                    .addReg(NewVReg3, RegState::Kill));
6789     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6790     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6791                    .addFrameIndex(FI)
6792                    .addImm(36)); // &jbuf[1] :: pc
6793     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6794                    .addReg(NewVReg4, RegState::Kill)
6795                    .addReg(NewVReg5, RegState::Kill)
6796                    .addImm(0)
6797                    .addMemOperand(FIMMOSt));
6798   } else {
6799     // Incoming value: jbuf
6800     //   ldr  r1, LCPI1_1
6801     //   add  r1, pc, r1
6802     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6803     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6804     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6805                    .addConstantPoolIndex(CPI)
6806                    .addImm(0)
6807                    .addMemOperand(CPMMO));
6808     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6809     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6810                    .addReg(NewVReg1, RegState::Kill)
6811                    .addImm(PCLabelId));
6812     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6813                    .addReg(NewVReg2, RegState::Kill)
6814                    .addFrameIndex(FI)
6815                    .addImm(36)  // &jbuf[1] :: pc
6816                    .addMemOperand(FIMMOSt));
6817   }
6818 }
6819
6820 MachineBasicBlock *ARMTargetLowering::
6821 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6822   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6823   DebugLoc dl = MI->getDebugLoc();
6824   MachineFunction *MF = MBB->getParent();
6825   MachineRegisterInfo *MRI = &MF->getRegInfo();
6826   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6827   MachineFrameInfo *MFI = MF->getFrameInfo();
6828   int FI = MFI->getFunctionContextIndex();
6829
6830   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6831     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6832     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6833
6834   // Get a mapping of the call site numbers to all of the landing pads they're
6835   // associated with.
6836   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6837   unsigned MaxCSNum = 0;
6838   MachineModuleInfo &MMI = MF->getMMI();
6839   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6840        ++BB) {
6841     if (!BB->isLandingPad()) continue;
6842
6843     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6844     // pad.
6845     for (MachineBasicBlock::iterator
6846            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6847       if (!II->isEHLabel()) continue;
6848
6849       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6850       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6851
6852       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6853       for (SmallVectorImpl<unsigned>::iterator
6854              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6855            CSI != CSE; ++CSI) {
6856         CallSiteNumToLPad[*CSI].push_back(BB);
6857         MaxCSNum = std::max(MaxCSNum, *CSI);
6858       }
6859       break;
6860     }
6861   }
6862
6863   // Get an ordered list of the machine basic blocks for the jump table.
6864   std::vector<MachineBasicBlock*> LPadList;
6865   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6866   LPadList.reserve(CallSiteNumToLPad.size());
6867   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6868     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6869     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6870            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6871       LPadList.push_back(*II);
6872       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6873     }
6874   }
6875
6876   assert(!LPadList.empty() &&
6877          "No landing pad destinations for the dispatch jump table!");
6878
6879   // Create the jump table and associated information.
6880   MachineJumpTableInfo *JTI =
6881     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6882   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6883   unsigned UId = AFI->createJumpTableUId();
6884   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6885
6886   // Create the MBBs for the dispatch code.
6887
6888   // Shove the dispatch's address into the return slot in the function context.
6889   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6890   DispatchBB->setIsLandingPad();
6891
6892   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6893   unsigned trap_opcode;
6894   if (Subtarget->isThumb())
6895     trap_opcode = ARM::tTRAP;
6896   else
6897     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6898
6899   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6900   DispatchBB->addSuccessor(TrapBB);
6901
6902   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6903   DispatchBB->addSuccessor(DispContBB);
6904
6905   // Insert and MBBs.
6906   MF->insert(MF->end(), DispatchBB);
6907   MF->insert(MF->end(), DispContBB);
6908   MF->insert(MF->end(), TrapBB);
6909
6910   // Insert code into the entry block that creates and registers the function
6911   // context.
6912   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6913
6914   MachineMemOperand *FIMMOLd =
6915     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6916                              MachineMemOperand::MOLoad |
6917                              MachineMemOperand::MOVolatile, 4, 4);
6918
6919   MachineInstrBuilder MIB;
6920   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6921
6922   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6923   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6924
6925   // Add a register mask with no preserved registers.  This results in all
6926   // registers being marked as clobbered.
6927   MIB.addRegMask(RI.getNoPreservedMask());
6928
6929   unsigned NumLPads = LPadList.size();
6930   if (Subtarget->isThumb2()) {
6931     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6932     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6933                    .addFrameIndex(FI)
6934                    .addImm(4)
6935                    .addMemOperand(FIMMOLd));
6936
6937     if (NumLPads < 256) {
6938       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6939                      .addReg(NewVReg1)
6940                      .addImm(LPadList.size()));
6941     } else {
6942       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6943       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6944                      .addImm(NumLPads & 0xFFFF));
6945
6946       unsigned VReg2 = VReg1;
6947       if ((NumLPads & 0xFFFF0000) != 0) {
6948         VReg2 = MRI->createVirtualRegister(TRC);
6949         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6950                        .addReg(VReg1)
6951                        .addImm(NumLPads >> 16));
6952       }
6953
6954       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6955                      .addReg(NewVReg1)
6956                      .addReg(VReg2));
6957     }
6958
6959     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6960       .addMBB(TrapBB)
6961       .addImm(ARMCC::HI)
6962       .addReg(ARM::CPSR);
6963
6964     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6965     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6966                    .addJumpTableIndex(MJTI)
6967                    .addImm(UId));
6968
6969     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6970     AddDefaultCC(
6971       AddDefaultPred(
6972         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6973         .addReg(NewVReg3, RegState::Kill)
6974         .addReg(NewVReg1)
6975         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6976
6977     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6978       .addReg(NewVReg4, RegState::Kill)
6979       .addReg(NewVReg1)
6980       .addJumpTableIndex(MJTI)
6981       .addImm(UId);
6982   } else if (Subtarget->isThumb()) {
6983     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6984     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6985                    .addFrameIndex(FI)
6986                    .addImm(1)
6987                    .addMemOperand(FIMMOLd));
6988
6989     if (NumLPads < 256) {
6990       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6991                      .addReg(NewVReg1)
6992                      .addImm(NumLPads));
6993     } else {
6994       MachineConstantPool *ConstantPool = MF->getConstantPool();
6995       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6996       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6997
6998       // MachineConstantPool wants an explicit alignment.
6999       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7000       if (Align == 0)
7001         Align = getDataLayout()->getTypeAllocSize(C->getType());
7002       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7003
7004       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7005       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7006                      .addReg(VReg1, RegState::Define)
7007                      .addConstantPoolIndex(Idx));
7008       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7009                      .addReg(NewVReg1)
7010                      .addReg(VReg1));
7011     }
7012
7013     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7014       .addMBB(TrapBB)
7015       .addImm(ARMCC::HI)
7016       .addReg(ARM::CPSR);
7017
7018     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7019     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7020                    .addReg(ARM::CPSR, RegState::Define)
7021                    .addReg(NewVReg1)
7022                    .addImm(2));
7023
7024     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7025     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7026                    .addJumpTableIndex(MJTI)
7027                    .addImm(UId));
7028
7029     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7030     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7031                    .addReg(ARM::CPSR, RegState::Define)
7032                    .addReg(NewVReg2, RegState::Kill)
7033                    .addReg(NewVReg3));
7034
7035     MachineMemOperand *JTMMOLd =
7036       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7037                                MachineMemOperand::MOLoad, 4, 4);
7038
7039     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7040     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7041                    .addReg(NewVReg4, RegState::Kill)
7042                    .addImm(0)
7043                    .addMemOperand(JTMMOLd));
7044
7045     unsigned NewVReg6 = NewVReg5;
7046     if (RelocM == Reloc::PIC_) {
7047       NewVReg6 = MRI->createVirtualRegister(TRC);
7048       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7049                      .addReg(ARM::CPSR, RegState::Define)
7050                      .addReg(NewVReg5, RegState::Kill)
7051                      .addReg(NewVReg3));
7052     }
7053
7054     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7055       .addReg(NewVReg6, RegState::Kill)
7056       .addJumpTableIndex(MJTI)
7057       .addImm(UId);
7058   } else {
7059     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7060     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7061                    .addFrameIndex(FI)
7062                    .addImm(4)
7063                    .addMemOperand(FIMMOLd));
7064
7065     if (NumLPads < 256) {
7066       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7067                      .addReg(NewVReg1)
7068                      .addImm(NumLPads));
7069     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7070       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7071       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7072                      .addImm(NumLPads & 0xFFFF));
7073
7074       unsigned VReg2 = VReg1;
7075       if ((NumLPads & 0xFFFF0000) != 0) {
7076         VReg2 = MRI->createVirtualRegister(TRC);
7077         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7078                        .addReg(VReg1)
7079                        .addImm(NumLPads >> 16));
7080       }
7081
7082       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7083                      .addReg(NewVReg1)
7084                      .addReg(VReg2));
7085     } else {
7086       MachineConstantPool *ConstantPool = MF->getConstantPool();
7087       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7088       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7089
7090       // MachineConstantPool wants an explicit alignment.
7091       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7092       if (Align == 0)
7093         Align = getDataLayout()->getTypeAllocSize(C->getType());
7094       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7095
7096       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7097       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7098                      .addReg(VReg1, RegState::Define)
7099                      .addConstantPoolIndex(Idx)
7100                      .addImm(0));
7101       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7102                      .addReg(NewVReg1)
7103                      .addReg(VReg1, RegState::Kill));
7104     }
7105
7106     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7107       .addMBB(TrapBB)
7108       .addImm(ARMCC::HI)
7109       .addReg(ARM::CPSR);
7110
7111     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7112     AddDefaultCC(
7113       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7114                      .addReg(NewVReg1)
7115                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7116     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7117     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7118                    .addJumpTableIndex(MJTI)
7119                    .addImm(UId));
7120
7121     MachineMemOperand *JTMMOLd =
7122       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7123                                MachineMemOperand::MOLoad, 4, 4);
7124     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7125     AddDefaultPred(
7126       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7127       .addReg(NewVReg3, RegState::Kill)
7128       .addReg(NewVReg4)
7129       .addImm(0)
7130       .addMemOperand(JTMMOLd));
7131
7132     if (RelocM == Reloc::PIC_) {
7133       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7134         .addReg(NewVReg5, RegState::Kill)
7135         .addReg(NewVReg4)
7136         .addJumpTableIndex(MJTI)
7137         .addImm(UId);
7138     } else {
7139       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7140         .addReg(NewVReg5, RegState::Kill)
7141         .addJumpTableIndex(MJTI)
7142         .addImm(UId);
7143     }
7144   }
7145
7146   // Add the jump table entries as successors to the MBB.
7147   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7148   for (std::vector<MachineBasicBlock*>::iterator
7149          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7150     MachineBasicBlock *CurMBB = *I;
7151     if (SeenMBBs.insert(CurMBB))
7152       DispContBB->addSuccessor(CurMBB);
7153   }
7154
7155   // N.B. the order the invoke BBs are processed in doesn't matter here.
7156   const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
7157   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7158   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
7159          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
7160     MachineBasicBlock *BB = *I;
7161
7162     // Remove the landing pad successor from the invoke block and replace it
7163     // with the new dispatch block.
7164     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7165                                                   BB->succ_end());
7166     while (!Successors.empty()) {
7167       MachineBasicBlock *SMBB = Successors.pop_back_val();
7168       if (SMBB->isLandingPad()) {
7169         BB->removeSuccessor(SMBB);
7170         MBBLPads.push_back(SMBB);
7171       }
7172     }
7173
7174     BB->addSuccessor(DispatchBB);
7175
7176     // Find the invoke call and mark all of the callee-saved registers as
7177     // 'implicit defined' so that they're spilled. This prevents code from
7178     // moving instructions to before the EH block, where they will never be
7179     // executed.
7180     for (MachineBasicBlock::reverse_iterator
7181            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7182       if (!II->isCall()) continue;
7183
7184       DenseMap<unsigned, bool> DefRegs;
7185       for (MachineInstr::mop_iterator
7186              OI = II->operands_begin(), OE = II->operands_end();
7187            OI != OE; ++OI) {
7188         if (!OI->isReg()) continue;
7189         DefRegs[OI->getReg()] = true;
7190       }
7191
7192       MachineInstrBuilder MIB(*MF, &*II);
7193
7194       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7195         unsigned Reg = SavedRegs[i];
7196         if (Subtarget->isThumb2() &&
7197             !ARM::tGPRRegClass.contains(Reg) &&
7198             !ARM::hGPRRegClass.contains(Reg))
7199           continue;
7200         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7201           continue;
7202         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7203           continue;
7204         if (!DefRegs[Reg])
7205           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7206       }
7207
7208       break;
7209     }
7210   }
7211
7212   // Mark all former landing pads as non-landing pads. The dispatch is the only
7213   // landing pad now.
7214   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7215          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7216     (*I)->setIsLandingPad(false);
7217
7218   // The instruction is gone now.
7219   MI->eraseFromParent();
7220
7221   return MBB;
7222 }
7223
7224 static
7225 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7226   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7227        E = MBB->succ_end(); I != E; ++I)
7228     if (*I != Succ)
7229       return *I;
7230   llvm_unreachable("Expecting a BB with two successors!");
7231 }
7232
7233 /// Return the load opcode for a given load size. If load size >= 8,
7234 /// neon opcode will be returned.
7235 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7236   if (LdSize >= 8)
7237     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7238                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7239   if (IsThumb1)
7240     return LdSize == 4 ? ARM::tLDRi
7241                        : LdSize == 2 ? ARM::tLDRHi
7242                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7243   if (IsThumb2)
7244     return LdSize == 4 ? ARM::t2LDR_POST
7245                        : LdSize == 2 ? ARM::t2LDRH_POST
7246                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7247   return LdSize == 4 ? ARM::LDR_POST_IMM
7248                      : LdSize == 2 ? ARM::LDRH_POST
7249                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7250 }
7251
7252 /// Return the store opcode for a given store size. If store size >= 8,
7253 /// neon opcode will be returned.
7254 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7255   if (StSize >= 8)
7256     return StSize == 16 ? ARM::VST1q32wb_fixed
7257                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7258   if (IsThumb1)
7259     return StSize == 4 ? ARM::tSTRi
7260                        : StSize == 2 ? ARM::tSTRHi
7261                                      : StSize == 1 ? ARM::tSTRBi : 0;
7262   if (IsThumb2)
7263     return StSize == 4 ? ARM::t2STR_POST
7264                        : StSize == 2 ? ARM::t2STRH_POST
7265                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7266   return StSize == 4 ? ARM::STR_POST_IMM
7267                      : StSize == 2 ? ARM::STRH_POST
7268                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7269 }
7270
7271 /// Emit a post-increment load operation with given size. The instructions
7272 /// will be added to BB at Pos.
7273 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7274                        const TargetInstrInfo *TII, DebugLoc dl,
7275                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7276                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7277   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7278   assert(LdOpc != 0 && "Should have a load opcode");
7279   if (LdSize >= 8) {
7280     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7281                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7282                        .addImm(0));
7283   } else if (IsThumb1) {
7284     // load + update AddrIn
7285     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7286                        .addReg(AddrIn).addImm(0));
7287     MachineInstrBuilder MIB =
7288         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7289     MIB = AddDefaultT1CC(MIB);
7290     MIB.addReg(AddrIn).addImm(LdSize);
7291     AddDefaultPred(MIB);
7292   } else if (IsThumb2) {
7293     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7294                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7295                        .addImm(LdSize));
7296   } else { // arm
7297     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7298                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7299                        .addReg(0).addImm(LdSize));
7300   }
7301 }
7302
7303 /// Emit a post-increment store operation with given size. The instructions
7304 /// will be added to BB at Pos.
7305 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7306                        const TargetInstrInfo *TII, DebugLoc dl,
7307                        unsigned StSize, unsigned Data, unsigned AddrIn,
7308                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7309   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7310   assert(StOpc != 0 && "Should have a store opcode");
7311   if (StSize >= 8) {
7312     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7313                        .addReg(AddrIn).addImm(0).addReg(Data));
7314   } else if (IsThumb1) {
7315     // store + update AddrIn
7316     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7317                        .addReg(AddrIn).addImm(0));
7318     MachineInstrBuilder MIB =
7319         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7320     MIB = AddDefaultT1CC(MIB);
7321     MIB.addReg(AddrIn).addImm(StSize);
7322     AddDefaultPred(MIB);
7323   } else if (IsThumb2) {
7324     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7325                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7326   } else { // arm
7327     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7328                        .addReg(Data).addReg(AddrIn).addReg(0)
7329                        .addImm(StSize));
7330   }
7331 }
7332
7333 MachineBasicBlock *
7334 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7335                                    MachineBasicBlock *BB) const {
7336   // This pseudo instruction has 3 operands: dst, src, size
7337   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7338   // Otherwise, we will generate unrolled scalar copies.
7339   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7340   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7341   MachineFunction::iterator It = BB;
7342   ++It;
7343
7344   unsigned dest = MI->getOperand(0).getReg();
7345   unsigned src = MI->getOperand(1).getReg();
7346   unsigned SizeVal = MI->getOperand(2).getImm();
7347   unsigned Align = MI->getOperand(3).getImm();
7348   DebugLoc dl = MI->getDebugLoc();
7349
7350   MachineFunction *MF = BB->getParent();
7351   MachineRegisterInfo &MRI = MF->getRegInfo();
7352   unsigned UnitSize = 0;
7353   const TargetRegisterClass *TRC = 0;
7354   const TargetRegisterClass *VecTRC = 0;
7355
7356   bool IsThumb1 = Subtarget->isThumb1Only();
7357   bool IsThumb2 = Subtarget->isThumb2();
7358
7359   if (Align & 1) {
7360     UnitSize = 1;
7361   } else if (Align & 2) {
7362     UnitSize = 2;
7363   } else {
7364     // Check whether we can use NEON instructions.
7365     if (!MF->getFunction()->getAttributes().
7366           hasAttribute(AttributeSet::FunctionIndex,
7367                        Attribute::NoImplicitFloat) &&
7368         Subtarget->hasNEON()) {
7369       if ((Align % 16 == 0) && SizeVal >= 16)
7370         UnitSize = 16;
7371       else if ((Align % 8 == 0) && SizeVal >= 8)
7372         UnitSize = 8;
7373     }
7374     // Can't use NEON instructions.
7375     if (UnitSize == 0)
7376       UnitSize = 4;
7377   }
7378
7379   // Select the correct opcode and register class for unit size load/store
7380   bool IsNeon = UnitSize >= 8;
7381   TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
7382                                : (const TargetRegisterClass *)&ARM::GPRRegClass;
7383   if (IsNeon)
7384     VecTRC = UnitSize == 16
7385                  ? (const TargetRegisterClass *)&ARM::DPairRegClass
7386                  : UnitSize == 8
7387                        ? (const TargetRegisterClass *)&ARM::DPRRegClass
7388                        : 0;
7389
7390   unsigned BytesLeft = SizeVal % UnitSize;
7391   unsigned LoopSize = SizeVal - BytesLeft;
7392
7393   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7394     // Use LDR and STR to copy.
7395     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7396     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7397     unsigned srcIn = src;
7398     unsigned destIn = dest;
7399     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7400       unsigned srcOut = MRI.createVirtualRegister(TRC);
7401       unsigned destOut = MRI.createVirtualRegister(TRC);
7402       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7403       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7404                  IsThumb1, IsThumb2);
7405       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7406                  IsThumb1, IsThumb2);
7407       srcIn = srcOut;
7408       destIn = destOut;
7409     }
7410
7411     // Handle the leftover bytes with LDRB and STRB.
7412     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7413     // [destOut] = STRB_POST(scratch, destIn, 1)
7414     for (unsigned i = 0; i < BytesLeft; i++) {
7415       unsigned srcOut = MRI.createVirtualRegister(TRC);
7416       unsigned destOut = MRI.createVirtualRegister(TRC);
7417       unsigned scratch = MRI.createVirtualRegister(TRC);
7418       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7419                  IsThumb1, IsThumb2);
7420       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7421                  IsThumb1, IsThumb2);
7422       srcIn = srcOut;
7423       destIn = destOut;
7424     }
7425     MI->eraseFromParent();   // The instruction is gone now.
7426     return BB;
7427   }
7428
7429   // Expand the pseudo op to a loop.
7430   // thisMBB:
7431   //   ...
7432   //   movw varEnd, # --> with thumb2
7433   //   movt varEnd, #
7434   //   ldrcp varEnd, idx --> without thumb2
7435   //   fallthrough --> loopMBB
7436   // loopMBB:
7437   //   PHI varPhi, varEnd, varLoop
7438   //   PHI srcPhi, src, srcLoop
7439   //   PHI destPhi, dst, destLoop
7440   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7441   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7442   //   subs varLoop, varPhi, #UnitSize
7443   //   bne loopMBB
7444   //   fallthrough --> exitMBB
7445   // exitMBB:
7446   //   epilogue to handle left-over bytes
7447   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7448   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7449   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7450   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7451   MF->insert(It, loopMBB);
7452   MF->insert(It, exitMBB);
7453
7454   // Transfer the remainder of BB and its successor edges to exitMBB.
7455   exitMBB->splice(exitMBB->begin(), BB,
7456                   llvm::next(MachineBasicBlock::iterator(MI)),
7457                   BB->end());
7458   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7459
7460   // Load an immediate to varEnd.
7461   unsigned varEnd = MRI.createVirtualRegister(TRC);
7462   if (IsThumb2) {
7463     unsigned Vtmp = varEnd;
7464     if ((LoopSize & 0xFFFF0000) != 0)
7465       Vtmp = MRI.createVirtualRegister(TRC);
7466     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7467                        .addImm(LoopSize & 0xFFFF));
7468
7469     if ((LoopSize & 0xFFFF0000) != 0)
7470       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7471                          .addReg(Vtmp).addImm(LoopSize >> 16));
7472   } else {
7473     MachineConstantPool *ConstantPool = MF->getConstantPool();
7474     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7475     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7476
7477     // MachineConstantPool wants an explicit alignment.
7478     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7479     if (Align == 0)
7480       Align = getDataLayout()->getTypeAllocSize(C->getType());
7481     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7482
7483     if (IsThumb1)
7484       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7485           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7486     else
7487       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7488           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7489   }
7490   BB->addSuccessor(loopMBB);
7491
7492   // Generate the loop body:
7493   //   varPhi = PHI(varLoop, varEnd)
7494   //   srcPhi = PHI(srcLoop, src)
7495   //   destPhi = PHI(destLoop, dst)
7496   MachineBasicBlock *entryBB = BB;
7497   BB = loopMBB;
7498   unsigned varLoop = MRI.createVirtualRegister(TRC);
7499   unsigned varPhi = MRI.createVirtualRegister(TRC);
7500   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7501   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7502   unsigned destLoop = MRI.createVirtualRegister(TRC);
7503   unsigned destPhi = MRI.createVirtualRegister(TRC);
7504
7505   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7506     .addReg(varLoop).addMBB(loopMBB)
7507     .addReg(varEnd).addMBB(entryBB);
7508   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7509     .addReg(srcLoop).addMBB(loopMBB)
7510     .addReg(src).addMBB(entryBB);
7511   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7512     .addReg(destLoop).addMBB(loopMBB)
7513     .addReg(dest).addMBB(entryBB);
7514
7515   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7516   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7517   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7518   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7519              IsThumb1, IsThumb2);
7520   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7521              IsThumb1, IsThumb2);
7522
7523   // Decrement loop variable by UnitSize.
7524   if (IsThumb1) {
7525     MachineInstrBuilder MIB =
7526         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7527     MIB = AddDefaultT1CC(MIB);
7528     MIB.addReg(varPhi).addImm(UnitSize);
7529     AddDefaultPred(MIB);
7530   } else {
7531     MachineInstrBuilder MIB =
7532         BuildMI(*BB, BB->end(), dl,
7533                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7534     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7535     MIB->getOperand(5).setReg(ARM::CPSR);
7536     MIB->getOperand(5).setIsDef(true);
7537   }
7538   BuildMI(*BB, BB->end(), dl,
7539           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7540       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7541
7542   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7543   BB->addSuccessor(loopMBB);
7544   BB->addSuccessor(exitMBB);
7545
7546   // Add epilogue to handle BytesLeft.
7547   BB = exitMBB;
7548   MachineInstr *StartOfExit = exitMBB->begin();
7549
7550   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7551   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7552   unsigned srcIn = srcLoop;
7553   unsigned destIn = destLoop;
7554   for (unsigned i = 0; i < BytesLeft; i++) {
7555     unsigned srcOut = MRI.createVirtualRegister(TRC);
7556     unsigned destOut = MRI.createVirtualRegister(TRC);
7557     unsigned scratch = MRI.createVirtualRegister(TRC);
7558     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7559                IsThumb1, IsThumb2);
7560     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7561                IsThumb1, IsThumb2);
7562     srcIn = srcOut;
7563     destIn = destOut;
7564   }
7565
7566   MI->eraseFromParent();   // The instruction is gone now.
7567   return BB;
7568 }
7569
7570 MachineBasicBlock *
7571 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7572                                                MachineBasicBlock *BB) const {
7573   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7574   DebugLoc dl = MI->getDebugLoc();
7575   bool isThumb2 = Subtarget->isThumb2();
7576   switch (MI->getOpcode()) {
7577   default: {
7578     MI->dump();
7579     llvm_unreachable("Unexpected instr type to insert");
7580   }
7581   // The Thumb2 pre-indexed stores have the same MI operands, they just
7582   // define them differently in the .td files from the isel patterns, so
7583   // they need pseudos.
7584   case ARM::t2STR_preidx:
7585     MI->setDesc(TII->get(ARM::t2STR_PRE));
7586     return BB;
7587   case ARM::t2STRB_preidx:
7588     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7589     return BB;
7590   case ARM::t2STRH_preidx:
7591     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7592     return BB;
7593
7594   case ARM::STRi_preidx:
7595   case ARM::STRBi_preidx: {
7596     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7597       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7598     // Decode the offset.
7599     unsigned Offset = MI->getOperand(4).getImm();
7600     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7601     Offset = ARM_AM::getAM2Offset(Offset);
7602     if (isSub)
7603       Offset = -Offset;
7604
7605     MachineMemOperand *MMO = *MI->memoperands_begin();
7606     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7607       .addOperand(MI->getOperand(0))  // Rn_wb
7608       .addOperand(MI->getOperand(1))  // Rt
7609       .addOperand(MI->getOperand(2))  // Rn
7610       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7611       .addOperand(MI->getOperand(5))  // pred
7612       .addOperand(MI->getOperand(6))
7613       .addMemOperand(MMO);
7614     MI->eraseFromParent();
7615     return BB;
7616   }
7617   case ARM::STRr_preidx:
7618   case ARM::STRBr_preidx:
7619   case ARM::STRH_preidx: {
7620     unsigned NewOpc;
7621     switch (MI->getOpcode()) {
7622     default: llvm_unreachable("unexpected opcode!");
7623     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7624     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7625     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7626     }
7627     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7628     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7629       MIB.addOperand(MI->getOperand(i));
7630     MI->eraseFromParent();
7631     return BB;
7632   }
7633   case ARM::ATOMIC_LOAD_ADD_I8:
7634      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7635   case ARM::ATOMIC_LOAD_ADD_I16:
7636      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7637   case ARM::ATOMIC_LOAD_ADD_I32:
7638      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7639
7640   case ARM::ATOMIC_LOAD_AND_I8:
7641      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7642   case ARM::ATOMIC_LOAD_AND_I16:
7643      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7644   case ARM::ATOMIC_LOAD_AND_I32:
7645      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7646
7647   case ARM::ATOMIC_LOAD_OR_I8:
7648      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7649   case ARM::ATOMIC_LOAD_OR_I16:
7650      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7651   case ARM::ATOMIC_LOAD_OR_I32:
7652      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7653
7654   case ARM::ATOMIC_LOAD_XOR_I8:
7655      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7656   case ARM::ATOMIC_LOAD_XOR_I16:
7657      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7658   case ARM::ATOMIC_LOAD_XOR_I32:
7659      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7660
7661   case ARM::ATOMIC_LOAD_NAND_I8:
7662      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7663   case ARM::ATOMIC_LOAD_NAND_I16:
7664      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7665   case ARM::ATOMIC_LOAD_NAND_I32:
7666      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7667
7668   case ARM::ATOMIC_LOAD_SUB_I8:
7669      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7670   case ARM::ATOMIC_LOAD_SUB_I16:
7671      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7672   case ARM::ATOMIC_LOAD_SUB_I32:
7673      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7674
7675   case ARM::ATOMIC_LOAD_MIN_I8:
7676      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7677   case ARM::ATOMIC_LOAD_MIN_I16:
7678      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7679   case ARM::ATOMIC_LOAD_MIN_I32:
7680      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7681
7682   case ARM::ATOMIC_LOAD_MAX_I8:
7683      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7684   case ARM::ATOMIC_LOAD_MAX_I16:
7685      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7686   case ARM::ATOMIC_LOAD_MAX_I32:
7687      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7688
7689   case ARM::ATOMIC_LOAD_UMIN_I8:
7690      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7691   case ARM::ATOMIC_LOAD_UMIN_I16:
7692      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7693   case ARM::ATOMIC_LOAD_UMIN_I32:
7694      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7695
7696   case ARM::ATOMIC_LOAD_UMAX_I8:
7697      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7698   case ARM::ATOMIC_LOAD_UMAX_I16:
7699      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7700   case ARM::ATOMIC_LOAD_UMAX_I32:
7701      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7702
7703   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
7704   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7705   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7706
7707   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
7708   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7709   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7710
7711   case ARM::ATOMIC_LOAD_I64:
7712     return EmitAtomicLoad64(MI, BB);
7713
7714   case ARM::ATOMIC_LOAD_ADD_I64:
7715     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7716                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7717                               /*NeedsCarry*/ true);
7718   case ARM::ATOMIC_LOAD_SUB_I64:
7719     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7720                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7721                               /*NeedsCarry*/ true);
7722   case ARM::ATOMIC_LOAD_OR_I64:
7723     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7724                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7725   case ARM::ATOMIC_LOAD_XOR_I64:
7726     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7727                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7728   case ARM::ATOMIC_LOAD_AND_I64:
7729     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7730                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7731   case ARM::ATOMIC_STORE_I64:
7732   case ARM::ATOMIC_SWAP_I64:
7733     return EmitAtomicBinary64(MI, BB, 0, 0, false);
7734   case ARM::ATOMIC_CMP_SWAP_I64:
7735     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7736                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7737                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7738   case ARM::ATOMIC_LOAD_MIN_I64:
7739     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7740                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7741                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7742                               /*IsMinMax*/ true, ARMCC::LT);
7743   case ARM::ATOMIC_LOAD_MAX_I64:
7744     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7745                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7746                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7747                               /*IsMinMax*/ true, ARMCC::GE);
7748   case ARM::ATOMIC_LOAD_UMIN_I64:
7749     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7750                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7751                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7752                               /*IsMinMax*/ true, ARMCC::LO);
7753   case ARM::ATOMIC_LOAD_UMAX_I64:
7754     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7755                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7756                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7757                               /*IsMinMax*/ true, ARMCC::HS);
7758
7759   case ARM::tMOVCCr_pseudo: {
7760     // To "insert" a SELECT_CC instruction, we actually have to insert the
7761     // diamond control-flow pattern.  The incoming instruction knows the
7762     // destination vreg to set, the condition code register to branch on, the
7763     // true/false values to select between, and a branch opcode to use.
7764     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7765     MachineFunction::iterator It = BB;
7766     ++It;
7767
7768     //  thisMBB:
7769     //  ...
7770     //   TrueVal = ...
7771     //   cmpTY ccX, r1, r2
7772     //   bCC copy1MBB
7773     //   fallthrough --> copy0MBB
7774     MachineBasicBlock *thisMBB  = BB;
7775     MachineFunction *F = BB->getParent();
7776     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7777     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7778     F->insert(It, copy0MBB);
7779     F->insert(It, sinkMBB);
7780
7781     // Transfer the remainder of BB and its successor edges to sinkMBB.
7782     sinkMBB->splice(sinkMBB->begin(), BB,
7783                     llvm::next(MachineBasicBlock::iterator(MI)),
7784                     BB->end());
7785     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7786
7787     BB->addSuccessor(copy0MBB);
7788     BB->addSuccessor(sinkMBB);
7789
7790     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7791       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7792
7793     //  copy0MBB:
7794     //   %FalseValue = ...
7795     //   # fallthrough to sinkMBB
7796     BB = copy0MBB;
7797
7798     // Update machine-CFG edges
7799     BB->addSuccessor(sinkMBB);
7800
7801     //  sinkMBB:
7802     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7803     //  ...
7804     BB = sinkMBB;
7805     BuildMI(*BB, BB->begin(), dl,
7806             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7807       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7808       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7809
7810     MI->eraseFromParent();   // The pseudo instruction is gone now.
7811     return BB;
7812   }
7813
7814   case ARM::BCCi64:
7815   case ARM::BCCZi64: {
7816     // If there is an unconditional branch to the other successor, remove it.
7817     BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
7818
7819     // Compare both parts that make up the double comparison separately for
7820     // equality.
7821     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7822
7823     unsigned LHS1 = MI->getOperand(1).getReg();
7824     unsigned LHS2 = MI->getOperand(2).getReg();
7825     if (RHSisZero) {
7826       AddDefaultPred(BuildMI(BB, dl,
7827                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7828                      .addReg(LHS1).addImm(0));
7829       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7830         .addReg(LHS2).addImm(0)
7831         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7832     } else {
7833       unsigned RHS1 = MI->getOperand(3).getReg();
7834       unsigned RHS2 = MI->getOperand(4).getReg();
7835       AddDefaultPred(BuildMI(BB, dl,
7836                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7837                      .addReg(LHS1).addReg(RHS1));
7838       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7839         .addReg(LHS2).addReg(RHS2)
7840         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7841     }
7842
7843     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7844     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7845     if (MI->getOperand(0).getImm() == ARMCC::NE)
7846       std::swap(destMBB, exitMBB);
7847
7848     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7849       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7850     if (isThumb2)
7851       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7852     else
7853       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7854
7855     MI->eraseFromParent();   // The pseudo instruction is gone now.
7856     return BB;
7857   }
7858
7859   case ARM::Int_eh_sjlj_setjmp:
7860   case ARM::Int_eh_sjlj_setjmp_nofp:
7861   case ARM::tInt_eh_sjlj_setjmp:
7862   case ARM::t2Int_eh_sjlj_setjmp:
7863   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7864     EmitSjLjDispatchBlock(MI, BB);
7865     return BB;
7866
7867   case ARM::ABS:
7868   case ARM::t2ABS: {
7869     // To insert an ABS instruction, we have to insert the
7870     // diamond control-flow pattern.  The incoming instruction knows the
7871     // source vreg to test against 0, the destination vreg to set,
7872     // the condition code register to branch on, the
7873     // true/false values to select between, and a branch opcode to use.
7874     // It transforms
7875     //     V1 = ABS V0
7876     // into
7877     //     V2 = MOVS V0
7878     //     BCC                      (branch to SinkBB if V0 >= 0)
7879     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7880     //     SinkBB: V1 = PHI(V2, V3)
7881     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7882     MachineFunction::iterator BBI = BB;
7883     ++BBI;
7884     MachineFunction *Fn = BB->getParent();
7885     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7886     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7887     Fn->insert(BBI, RSBBB);
7888     Fn->insert(BBI, SinkBB);
7889
7890     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7891     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7892     bool isThumb2 = Subtarget->isThumb2();
7893     MachineRegisterInfo &MRI = Fn->getRegInfo();
7894     // In Thumb mode S must not be specified if source register is the SP or
7895     // PC and if destination register is the SP, so restrict register class
7896     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7897       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7898       (const TargetRegisterClass*)&ARM::GPRRegClass);
7899
7900     // Transfer the remainder of BB and its successor edges to sinkMBB.
7901     SinkBB->splice(SinkBB->begin(), BB,
7902       llvm::next(MachineBasicBlock::iterator(MI)),
7903       BB->end());
7904     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7905
7906     BB->addSuccessor(RSBBB);
7907     BB->addSuccessor(SinkBB);
7908
7909     // fall through to SinkMBB
7910     RSBBB->addSuccessor(SinkBB);
7911
7912     // insert a cmp at the end of BB
7913     AddDefaultPred(BuildMI(BB, dl,
7914                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7915                    .addReg(ABSSrcReg).addImm(0));
7916
7917     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7918     BuildMI(BB, dl,
7919       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7920       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7921
7922     // insert rsbri in RSBBB
7923     // Note: BCC and rsbri will be converted into predicated rsbmi
7924     // by if-conversion pass
7925     BuildMI(*RSBBB, RSBBB->begin(), dl,
7926       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7927       .addReg(ABSSrcReg, RegState::Kill)
7928       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7929
7930     // insert PHI in SinkBB,
7931     // reuse ABSDstReg to not change uses of ABS instruction
7932     BuildMI(*SinkBB, SinkBB->begin(), dl,
7933       TII->get(ARM::PHI), ABSDstReg)
7934       .addReg(NewRsbDstReg).addMBB(RSBBB)
7935       .addReg(ABSSrcReg).addMBB(BB);
7936
7937     // remove ABS instruction
7938     MI->eraseFromParent();
7939
7940     // return last added BB
7941     return SinkBB;
7942   }
7943   case ARM::COPY_STRUCT_BYVAL_I32:
7944     ++NumLoopByVals;
7945     return EmitStructByval(MI, BB);
7946   }
7947 }
7948
7949 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7950                                                       SDNode *Node) const {
7951   if (!MI->hasPostISelHook()) {
7952     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7953            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7954     return;
7955   }
7956
7957   const MCInstrDesc *MCID = &MI->getDesc();
7958   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7959   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7960   // operand is still set to noreg. If needed, set the optional operand's
7961   // register to CPSR, and remove the redundant implicit def.
7962   //
7963   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7964
7965   // Rename pseudo opcodes.
7966   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7967   if (NewOpc) {
7968     const ARMBaseInstrInfo *TII =
7969       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7970     MCID = &TII->get(NewOpc);
7971
7972     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7973            "converted opcode should be the same except for cc_out");
7974
7975     MI->setDesc(*MCID);
7976
7977     // Add the optional cc_out operand
7978     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7979   }
7980   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7981
7982   // Any ARM instruction that sets the 's' bit should specify an optional
7983   // "cc_out" operand in the last operand position.
7984   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7985     assert(!NewOpc && "Optional cc_out operand required");
7986     return;
7987   }
7988   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7989   // since we already have an optional CPSR def.
7990   bool definesCPSR = false;
7991   bool deadCPSR = false;
7992   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7993        i != e; ++i) {
7994     const MachineOperand &MO = MI->getOperand(i);
7995     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7996       definesCPSR = true;
7997       if (MO.isDead())
7998         deadCPSR = true;
7999       MI->RemoveOperand(i);
8000       break;
8001     }
8002   }
8003   if (!definesCPSR) {
8004     assert(!NewOpc && "Optional cc_out operand required");
8005     return;
8006   }
8007   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8008   if (deadCPSR) {
8009     assert(!MI->getOperand(ccOutIdx).getReg() &&
8010            "expect uninitialized optional cc_out operand");
8011     return;
8012   }
8013
8014   // If this instruction was defined with an optional CPSR def and its dag node
8015   // had a live implicit CPSR def, then activate the optional CPSR def.
8016   MachineOperand &MO = MI->getOperand(ccOutIdx);
8017   MO.setReg(ARM::CPSR);
8018   MO.setIsDef(true);
8019 }
8020
8021 //===----------------------------------------------------------------------===//
8022 //                           ARM Optimization Hooks
8023 //===----------------------------------------------------------------------===//
8024
8025 // Helper function that checks if N is a null or all ones constant.
8026 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8027   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8028   if (!C)
8029     return false;
8030   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8031 }
8032
8033 // Return true if N is conditionally 0 or all ones.
8034 // Detects these expressions where cc is an i1 value:
8035 //
8036 //   (select cc 0, y)   [AllOnes=0]
8037 //   (select cc y, 0)   [AllOnes=0]
8038 //   (zext cc)          [AllOnes=0]
8039 //   (sext cc)          [AllOnes=0/1]
8040 //   (select cc -1, y)  [AllOnes=1]
8041 //   (select cc y, -1)  [AllOnes=1]
8042 //
8043 // Invert is set when N is the null/all ones constant when CC is false.
8044 // OtherOp is set to the alternative value of N.
8045 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8046                                        SDValue &CC, bool &Invert,
8047                                        SDValue &OtherOp,
8048                                        SelectionDAG &DAG) {
8049   switch (N->getOpcode()) {
8050   default: return false;
8051   case ISD::SELECT: {
8052     CC = N->getOperand(0);
8053     SDValue N1 = N->getOperand(1);
8054     SDValue N2 = N->getOperand(2);
8055     if (isZeroOrAllOnes(N1, AllOnes)) {
8056       Invert = false;
8057       OtherOp = N2;
8058       return true;
8059     }
8060     if (isZeroOrAllOnes(N2, AllOnes)) {
8061       Invert = true;
8062       OtherOp = N1;
8063       return true;
8064     }
8065     return false;
8066   }
8067   case ISD::ZERO_EXTEND:
8068     // (zext cc) can never be the all ones value.
8069     if (AllOnes)
8070       return false;
8071     // Fall through.
8072   case ISD::SIGN_EXTEND: {
8073     EVT VT = N->getValueType(0);
8074     CC = N->getOperand(0);
8075     if (CC.getValueType() != MVT::i1)
8076       return false;
8077     Invert = !AllOnes;
8078     if (AllOnes)
8079       // When looking for an AllOnes constant, N is an sext, and the 'other'
8080       // value is 0.
8081       OtherOp = DAG.getConstant(0, VT);
8082     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8083       // When looking for a 0 constant, N can be zext or sext.
8084       OtherOp = DAG.getConstant(1, VT);
8085     else
8086       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
8087     return true;
8088   }
8089   }
8090 }
8091
8092 // Combine a constant select operand into its use:
8093 //
8094 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
8095 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
8096 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
8097 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
8098 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
8099 //
8100 // The transform is rejected if the select doesn't have a constant operand that
8101 // is null, or all ones when AllOnes is set.
8102 //
8103 // Also recognize sext/zext from i1:
8104 //
8105 //   (add (zext cc), x) -> (select cc (add x, 1), x)
8106 //   (add (sext cc), x) -> (select cc (add x, -1), x)
8107 //
8108 // These transformations eventually create predicated instructions.
8109 //
8110 // @param N       The node to transform.
8111 // @param Slct    The N operand that is a select.
8112 // @param OtherOp The other N operand (x above).
8113 // @param DCI     Context.
8114 // @param AllOnes Require the select constant to be all ones instead of null.
8115 // @returns The new node, or SDValue() on failure.
8116 static
8117 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8118                             TargetLowering::DAGCombinerInfo &DCI,
8119                             bool AllOnes = false) {
8120   SelectionDAG &DAG = DCI.DAG;
8121   EVT VT = N->getValueType(0);
8122   SDValue NonConstantVal;
8123   SDValue CCOp;
8124   bool SwapSelectOps;
8125   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8126                                   NonConstantVal, DAG))
8127     return SDValue();
8128
8129   // Slct is now know to be the desired identity constant when CC is true.
8130   SDValue TrueVal = OtherOp;
8131   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8132                                  OtherOp, NonConstantVal);
8133   // Unless SwapSelectOps says CC should be false.
8134   if (SwapSelectOps)
8135     std::swap(TrueVal, FalseVal);
8136
8137   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8138                      CCOp, TrueVal, FalseVal);
8139 }
8140
8141 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8142 static
8143 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8144                                        TargetLowering::DAGCombinerInfo &DCI) {
8145   SDValue N0 = N->getOperand(0);
8146   SDValue N1 = N->getOperand(1);
8147   if (N0.getNode()->hasOneUse()) {
8148     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8149     if (Result.getNode())
8150       return Result;
8151   }
8152   if (N1.getNode()->hasOneUse()) {
8153     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8154     if (Result.getNode())
8155       return Result;
8156   }
8157   return SDValue();
8158 }
8159
8160 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8161 // (only after legalization).
8162 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8163                                  TargetLowering::DAGCombinerInfo &DCI,
8164                                  const ARMSubtarget *Subtarget) {
8165
8166   // Only perform optimization if after legalize, and if NEON is available. We
8167   // also expected both operands to be BUILD_VECTORs.
8168   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8169       || N0.getOpcode() != ISD::BUILD_VECTOR
8170       || N1.getOpcode() != ISD::BUILD_VECTOR)
8171     return SDValue();
8172
8173   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8174   EVT VT = N->getValueType(0);
8175   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8176     return SDValue();
8177
8178   // Check that the vector operands are of the right form.
8179   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8180   // operands, where N is the size of the formed vector.
8181   // Each EXTRACT_VECTOR should have the same input vector and odd or even
8182   // index such that we have a pair wise add pattern.
8183
8184   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8185   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8186     return SDValue();
8187   SDValue Vec = N0->getOperand(0)->getOperand(0);
8188   SDNode *V = Vec.getNode();
8189   unsigned nextIndex = 0;
8190
8191   // For each operands to the ADD which are BUILD_VECTORs,
8192   // check to see if each of their operands are an EXTRACT_VECTOR with
8193   // the same vector and appropriate index.
8194   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8195     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8196         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8197
8198       SDValue ExtVec0 = N0->getOperand(i);
8199       SDValue ExtVec1 = N1->getOperand(i);
8200
8201       // First operand is the vector, verify its the same.
8202       if (V != ExtVec0->getOperand(0).getNode() ||
8203           V != ExtVec1->getOperand(0).getNode())
8204         return SDValue();
8205
8206       // Second is the constant, verify its correct.
8207       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8208       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8209
8210       // For the constant, we want to see all the even or all the odd.
8211       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8212           || C1->getZExtValue() != nextIndex+1)
8213         return SDValue();
8214
8215       // Increment index.
8216       nextIndex+=2;
8217     } else
8218       return SDValue();
8219   }
8220
8221   // Create VPADDL node.
8222   SelectionDAG &DAG = DCI.DAG;
8223   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8224
8225   // Build operand list.
8226   SmallVector<SDValue, 8> Ops;
8227   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
8228                                 TLI.getPointerTy()));
8229
8230   // Input is the vector.
8231   Ops.push_back(Vec);
8232
8233   // Get widened type and narrowed type.
8234   MVT widenType;
8235   unsigned numElem = VT.getVectorNumElements();
8236   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8237     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8238     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8239     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8240     default:
8241       llvm_unreachable("Invalid vector element type for padd optimization.");
8242   }
8243
8244   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
8245                             widenType, &Ops[0], Ops.size());
8246   return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, tmp);
8247 }
8248
8249 static SDValue findMUL_LOHI(SDValue V) {
8250   if (V->getOpcode() == ISD::UMUL_LOHI ||
8251       V->getOpcode() == ISD::SMUL_LOHI)
8252     return V;
8253   return SDValue();
8254 }
8255
8256 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8257                                      TargetLowering::DAGCombinerInfo &DCI,
8258                                      const ARMSubtarget *Subtarget) {
8259
8260   if (Subtarget->isThumb1Only()) return SDValue();
8261
8262   // Only perform the checks after legalize when the pattern is available.
8263   if (DCI.isBeforeLegalize()) return SDValue();
8264
8265   // Look for multiply add opportunities.
8266   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8267   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8268   // a glue link from the first add to the second add.
8269   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8270   // a S/UMLAL instruction.
8271   //          loAdd   UMUL_LOHI
8272   //            \    / :lo    \ :hi
8273   //             \  /          \          [no multiline comment]
8274   //              ADDC         |  hiAdd
8275   //                 \ :glue  /  /
8276   //                  \      /  /
8277   //                    ADDE
8278   //
8279   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8280   SDValue AddcOp0 = AddcNode->getOperand(0);
8281   SDValue AddcOp1 = AddcNode->getOperand(1);
8282
8283   // Check if the two operands are from the same mul_lohi node.
8284   if (AddcOp0.getNode() == AddcOp1.getNode())
8285     return SDValue();
8286
8287   assert(AddcNode->getNumValues() == 2 &&
8288          AddcNode->getValueType(0) == MVT::i32 &&
8289          "Expect ADDC with two result values. First: i32");
8290
8291   // Check that we have a glued ADDC node.
8292   if (AddcNode->getValueType(1) != MVT::Glue)
8293     return SDValue();
8294
8295   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8296   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8297       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8298       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8299       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8300     return SDValue();
8301
8302   // Look for the glued ADDE.
8303   SDNode* AddeNode = AddcNode->getGluedUser();
8304   if (AddeNode == NULL)
8305     return SDValue();
8306
8307   // Make sure it is really an ADDE.
8308   if (AddeNode->getOpcode() != ISD::ADDE)
8309     return SDValue();
8310
8311   assert(AddeNode->getNumOperands() == 3 &&
8312          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8313          "ADDE node has the wrong inputs");
8314
8315   // Check for the triangle shape.
8316   SDValue AddeOp0 = AddeNode->getOperand(0);
8317   SDValue AddeOp1 = AddeNode->getOperand(1);
8318
8319   // Make sure that the ADDE operands are not coming from the same node.
8320   if (AddeOp0.getNode() == AddeOp1.getNode())
8321     return SDValue();
8322
8323   // Find the MUL_LOHI node walking up ADDE's operands.
8324   bool IsLeftOperandMUL = false;
8325   SDValue MULOp = findMUL_LOHI(AddeOp0);
8326   if (MULOp == SDValue())
8327    MULOp = findMUL_LOHI(AddeOp1);
8328   else
8329     IsLeftOperandMUL = true;
8330   if (MULOp == SDValue())
8331      return SDValue();
8332
8333   // Figure out the right opcode.
8334   unsigned Opc = MULOp->getOpcode();
8335   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8336
8337   // Figure out the high and low input values to the MLAL node.
8338   SDValue* HiMul = &MULOp;
8339   SDValue* HiAdd = NULL;
8340   SDValue* LoMul = NULL;
8341   SDValue* LowAdd = NULL;
8342
8343   if (IsLeftOperandMUL)
8344     HiAdd = &AddeOp1;
8345   else
8346     HiAdd = &AddeOp0;
8347
8348
8349   if (AddcOp0->getOpcode() == Opc) {
8350     LoMul = &AddcOp0;
8351     LowAdd = &AddcOp1;
8352   }
8353   if (AddcOp1->getOpcode() == Opc) {
8354     LoMul = &AddcOp1;
8355     LowAdd = &AddcOp0;
8356   }
8357
8358   if (LoMul == NULL)
8359     return SDValue();
8360
8361   if (LoMul->getNode() != HiMul->getNode())
8362     return SDValue();
8363
8364   // Create the merged node.
8365   SelectionDAG &DAG = DCI.DAG;
8366
8367   // Build operand list.
8368   SmallVector<SDValue, 8> Ops;
8369   Ops.push_back(LoMul->getOperand(0));
8370   Ops.push_back(LoMul->getOperand(1));
8371   Ops.push_back(*LowAdd);
8372   Ops.push_back(*HiAdd);
8373
8374   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8375                                  DAG.getVTList(MVT::i32, MVT::i32),
8376                                  &Ops[0], Ops.size());
8377
8378   // Replace the ADDs' nodes uses by the MLA node's values.
8379   SDValue HiMLALResult(MLALNode.getNode(), 1);
8380   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8381
8382   SDValue LoMLALResult(MLALNode.getNode(), 0);
8383   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8384
8385   // Return original node to notify the driver to stop replacing.
8386   SDValue resNode(AddcNode, 0);
8387   return resNode;
8388 }
8389
8390 /// PerformADDCCombine - Target-specific dag combine transform from
8391 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8392 static SDValue PerformADDCCombine(SDNode *N,
8393                                  TargetLowering::DAGCombinerInfo &DCI,
8394                                  const ARMSubtarget *Subtarget) {
8395
8396   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8397
8398 }
8399
8400 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8401 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8402 /// called with the default operands, and if that fails, with commuted
8403 /// operands.
8404 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8405                                           TargetLowering::DAGCombinerInfo &DCI,
8406                                           const ARMSubtarget *Subtarget){
8407
8408   // Attempt to create vpaddl for this add.
8409   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8410   if (Result.getNode())
8411     return Result;
8412
8413   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8414   if (N0.getNode()->hasOneUse()) {
8415     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8416     if (Result.getNode()) return Result;
8417   }
8418   return SDValue();
8419 }
8420
8421 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8422 ///
8423 static SDValue PerformADDCombine(SDNode *N,
8424                                  TargetLowering::DAGCombinerInfo &DCI,
8425                                  const ARMSubtarget *Subtarget) {
8426   SDValue N0 = N->getOperand(0);
8427   SDValue N1 = N->getOperand(1);
8428
8429   // First try with the default operand order.
8430   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8431   if (Result.getNode())
8432     return Result;
8433
8434   // If that didn't work, try again with the operands commuted.
8435   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8436 }
8437
8438 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8439 ///
8440 static SDValue PerformSUBCombine(SDNode *N,
8441                                  TargetLowering::DAGCombinerInfo &DCI) {
8442   SDValue N0 = N->getOperand(0);
8443   SDValue N1 = N->getOperand(1);
8444
8445   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8446   if (N1.getNode()->hasOneUse()) {
8447     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8448     if (Result.getNode()) return Result;
8449   }
8450
8451   return SDValue();
8452 }
8453
8454 /// PerformVMULCombine
8455 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8456 /// special multiplier accumulator forwarding.
8457 ///   vmul d3, d0, d2
8458 ///   vmla d3, d1, d2
8459 /// is faster than
8460 ///   vadd d3, d0, d1
8461 ///   vmul d3, d3, d2
8462 //  However, for (A + B) * (A + B),
8463 //    vadd d2, d0, d1
8464 //    vmul d3, d0, d2
8465 //    vmla d3, d1, d2
8466 //  is slower than
8467 //    vadd d2, d0, d1
8468 //    vmul d3, d2, d2
8469 static SDValue PerformVMULCombine(SDNode *N,
8470                                   TargetLowering::DAGCombinerInfo &DCI,
8471                                   const ARMSubtarget *Subtarget) {
8472   if (!Subtarget->hasVMLxForwarding())
8473     return SDValue();
8474
8475   SelectionDAG &DAG = DCI.DAG;
8476   SDValue N0 = N->getOperand(0);
8477   SDValue N1 = N->getOperand(1);
8478   unsigned Opcode = N0.getOpcode();
8479   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8480       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8481     Opcode = N1.getOpcode();
8482     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8483         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8484       return SDValue();
8485     std::swap(N0, N1);
8486   }
8487
8488   if (N0 == N1)
8489     return SDValue();
8490
8491   EVT VT = N->getValueType(0);
8492   SDLoc DL(N);
8493   SDValue N00 = N0->getOperand(0);
8494   SDValue N01 = N0->getOperand(1);
8495   return DAG.getNode(Opcode, DL, VT,
8496                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8497                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8498 }
8499
8500 static SDValue PerformMULCombine(SDNode *N,
8501                                  TargetLowering::DAGCombinerInfo &DCI,
8502                                  const ARMSubtarget *Subtarget) {
8503   SelectionDAG &DAG = DCI.DAG;
8504
8505   if (Subtarget->isThumb1Only())
8506     return SDValue();
8507
8508   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8509     return SDValue();
8510
8511   EVT VT = N->getValueType(0);
8512   if (VT.is64BitVector() || VT.is128BitVector())
8513     return PerformVMULCombine(N, DCI, Subtarget);
8514   if (VT != MVT::i32)
8515     return SDValue();
8516
8517   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8518   if (!C)
8519     return SDValue();
8520
8521   int64_t MulAmt = C->getSExtValue();
8522   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8523
8524   ShiftAmt = ShiftAmt & (32 - 1);
8525   SDValue V = N->getOperand(0);
8526   SDLoc DL(N);
8527
8528   SDValue Res;
8529   MulAmt >>= ShiftAmt;
8530
8531   if (MulAmt >= 0) {
8532     if (isPowerOf2_32(MulAmt - 1)) {
8533       // (mul x, 2^N + 1) => (add (shl x, N), x)
8534       Res = DAG.getNode(ISD::ADD, DL, VT,
8535                         V,
8536                         DAG.getNode(ISD::SHL, DL, VT,
8537                                     V,
8538                                     DAG.getConstant(Log2_32(MulAmt - 1),
8539                                                     MVT::i32)));
8540     } else if (isPowerOf2_32(MulAmt + 1)) {
8541       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8542       Res = DAG.getNode(ISD::SUB, DL, VT,
8543                         DAG.getNode(ISD::SHL, DL, VT,
8544                                     V,
8545                                     DAG.getConstant(Log2_32(MulAmt + 1),
8546                                                     MVT::i32)),
8547                         V);
8548     } else
8549       return SDValue();
8550   } else {
8551     uint64_t MulAmtAbs = -MulAmt;
8552     if (isPowerOf2_32(MulAmtAbs + 1)) {
8553       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8554       Res = DAG.getNode(ISD::SUB, DL, VT,
8555                         V,
8556                         DAG.getNode(ISD::SHL, DL, VT,
8557                                     V,
8558                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8559                                                     MVT::i32)));
8560     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8561       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8562       Res = DAG.getNode(ISD::ADD, DL, VT,
8563                         V,
8564                         DAG.getNode(ISD::SHL, DL, VT,
8565                                     V,
8566                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8567                                                     MVT::i32)));
8568       Res = DAG.getNode(ISD::SUB, DL, VT,
8569                         DAG.getConstant(0, MVT::i32),Res);
8570
8571     } else
8572       return SDValue();
8573   }
8574
8575   if (ShiftAmt != 0)
8576     Res = DAG.getNode(ISD::SHL, DL, VT,
8577                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8578
8579   // Do not add new nodes to DAG combiner worklist.
8580   DCI.CombineTo(N, Res, false);
8581   return SDValue();
8582 }
8583
8584 static SDValue PerformANDCombine(SDNode *N,
8585                                  TargetLowering::DAGCombinerInfo &DCI,
8586                                  const ARMSubtarget *Subtarget) {
8587
8588   // Attempt to use immediate-form VBIC
8589   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8590   SDLoc dl(N);
8591   EVT VT = N->getValueType(0);
8592   SelectionDAG &DAG = DCI.DAG;
8593
8594   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8595     return SDValue();
8596
8597   APInt SplatBits, SplatUndef;
8598   unsigned SplatBitSize;
8599   bool HasAnyUndefs;
8600   if (BVN &&
8601       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8602     if (SplatBitSize <= 64) {
8603       EVT VbicVT;
8604       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8605                                       SplatUndef.getZExtValue(), SplatBitSize,
8606                                       DAG, VbicVT, VT.is128BitVector(),
8607                                       OtherModImm);
8608       if (Val.getNode()) {
8609         SDValue Input =
8610           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8611         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8612         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8613       }
8614     }
8615   }
8616
8617   if (!Subtarget->isThumb1Only()) {
8618     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8619     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8620     if (Result.getNode())
8621       return Result;
8622   }
8623
8624   return SDValue();
8625 }
8626
8627 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8628 static SDValue PerformORCombine(SDNode *N,
8629                                 TargetLowering::DAGCombinerInfo &DCI,
8630                                 const ARMSubtarget *Subtarget) {
8631   // Attempt to use immediate-form VORR
8632   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8633   SDLoc dl(N);
8634   EVT VT = N->getValueType(0);
8635   SelectionDAG &DAG = DCI.DAG;
8636
8637   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8638     return SDValue();
8639
8640   APInt SplatBits, SplatUndef;
8641   unsigned SplatBitSize;
8642   bool HasAnyUndefs;
8643   if (BVN && Subtarget->hasNEON() &&
8644       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8645     if (SplatBitSize <= 64) {
8646       EVT VorrVT;
8647       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8648                                       SplatUndef.getZExtValue(), SplatBitSize,
8649                                       DAG, VorrVT, VT.is128BitVector(),
8650                                       OtherModImm);
8651       if (Val.getNode()) {
8652         SDValue Input =
8653           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8654         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8655         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8656       }
8657     }
8658   }
8659
8660   if (!Subtarget->isThumb1Only()) {
8661     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8662     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8663     if (Result.getNode())
8664       return Result;
8665   }
8666
8667   // The code below optimizes (or (and X, Y), Z).
8668   // The AND operand needs to have a single user to make these optimizations
8669   // profitable.
8670   SDValue N0 = N->getOperand(0);
8671   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8672     return SDValue();
8673   SDValue N1 = N->getOperand(1);
8674
8675   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8676   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8677       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8678     APInt SplatUndef;
8679     unsigned SplatBitSize;
8680     bool HasAnyUndefs;
8681
8682     APInt SplatBits0, SplatBits1;
8683     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8684     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8685     // Ensure that the second operand of both ands are constants
8686     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8687                                       HasAnyUndefs) && !HasAnyUndefs) {
8688         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8689                                           HasAnyUndefs) && !HasAnyUndefs) {
8690             // Ensure that the bit width of the constants are the same and that
8691             // the splat arguments are logical inverses as per the pattern we
8692             // are trying to simplify.
8693             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8694                 SplatBits0 == ~SplatBits1) {
8695                 // Canonicalize the vector type to make instruction selection
8696                 // simpler.
8697                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8698                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8699                                              N0->getOperand(1),
8700                                              N0->getOperand(0),
8701                                              N1->getOperand(0));
8702                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8703             }
8704         }
8705     }
8706   }
8707
8708   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8709   // reasonable.
8710
8711   // BFI is only available on V6T2+
8712   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8713     return SDValue();
8714
8715   SDLoc DL(N);
8716   // 1) or (and A, mask), val => ARMbfi A, val, mask
8717   //      iff (val & mask) == val
8718   //
8719   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8720   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8721   //          && mask == ~mask2
8722   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8723   //          && ~mask == mask2
8724   //  (i.e., copy a bitfield value into another bitfield of the same width)
8725
8726   if (VT != MVT::i32)
8727     return SDValue();
8728
8729   SDValue N00 = N0.getOperand(0);
8730
8731   // The value and the mask need to be constants so we can verify this is
8732   // actually a bitfield set. If the mask is 0xffff, we can do better
8733   // via a movt instruction, so don't use BFI in that case.
8734   SDValue MaskOp = N0.getOperand(1);
8735   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8736   if (!MaskC)
8737     return SDValue();
8738   unsigned Mask = MaskC->getZExtValue();
8739   if (Mask == 0xffff)
8740     return SDValue();
8741   SDValue Res;
8742   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8743   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8744   if (N1C) {
8745     unsigned Val = N1C->getZExtValue();
8746     if ((Val & ~Mask) != Val)
8747       return SDValue();
8748
8749     if (ARM::isBitFieldInvertedMask(Mask)) {
8750       Val >>= countTrailingZeros(~Mask);
8751
8752       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8753                         DAG.getConstant(Val, MVT::i32),
8754                         DAG.getConstant(Mask, MVT::i32));
8755
8756       // Do not add new nodes to DAG combiner worklist.
8757       DCI.CombineTo(N, Res, false);
8758       return SDValue();
8759     }
8760   } else if (N1.getOpcode() == ISD::AND) {
8761     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8762     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8763     if (!N11C)
8764       return SDValue();
8765     unsigned Mask2 = N11C->getZExtValue();
8766
8767     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8768     // as is to match.
8769     if (ARM::isBitFieldInvertedMask(Mask) &&
8770         (Mask == ~Mask2)) {
8771       // The pack halfword instruction works better for masks that fit it,
8772       // so use that when it's available.
8773       if (Subtarget->hasT2ExtractPack() &&
8774           (Mask == 0xffff || Mask == 0xffff0000))
8775         return SDValue();
8776       // 2a
8777       unsigned amt = countTrailingZeros(Mask2);
8778       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8779                         DAG.getConstant(amt, MVT::i32));
8780       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8781                         DAG.getConstant(Mask, MVT::i32));
8782       // Do not add new nodes to DAG combiner worklist.
8783       DCI.CombineTo(N, Res, false);
8784       return SDValue();
8785     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8786                (~Mask == Mask2)) {
8787       // The pack halfword instruction works better for masks that fit it,
8788       // so use that when it's available.
8789       if (Subtarget->hasT2ExtractPack() &&
8790           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8791         return SDValue();
8792       // 2b
8793       unsigned lsb = countTrailingZeros(Mask);
8794       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8795                         DAG.getConstant(lsb, MVT::i32));
8796       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8797                         DAG.getConstant(Mask2, MVT::i32));
8798       // Do not add new nodes to DAG combiner worklist.
8799       DCI.CombineTo(N, Res, false);
8800       return SDValue();
8801     }
8802   }
8803
8804   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8805       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8806       ARM::isBitFieldInvertedMask(~Mask)) {
8807     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8808     // where lsb(mask) == #shamt and masked bits of B are known zero.
8809     SDValue ShAmt = N00.getOperand(1);
8810     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8811     unsigned LSB = countTrailingZeros(Mask);
8812     if (ShAmtC != LSB)
8813       return SDValue();
8814
8815     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8816                       DAG.getConstant(~Mask, MVT::i32));
8817
8818     // Do not add new nodes to DAG combiner worklist.
8819     DCI.CombineTo(N, Res, false);
8820   }
8821
8822   return SDValue();
8823 }
8824
8825 static SDValue PerformXORCombine(SDNode *N,
8826                                  TargetLowering::DAGCombinerInfo &DCI,
8827                                  const ARMSubtarget *Subtarget) {
8828   EVT VT = N->getValueType(0);
8829   SelectionDAG &DAG = DCI.DAG;
8830
8831   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8832     return SDValue();
8833
8834   if (!Subtarget->isThumb1Only()) {
8835     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8836     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8837     if (Result.getNode())
8838       return Result;
8839   }
8840
8841   return SDValue();
8842 }
8843
8844 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8845 /// the bits being cleared by the AND are not demanded by the BFI.
8846 static SDValue PerformBFICombine(SDNode *N,
8847                                  TargetLowering::DAGCombinerInfo &DCI) {
8848   SDValue N1 = N->getOperand(1);
8849   if (N1.getOpcode() == ISD::AND) {
8850     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8851     if (!N11C)
8852       return SDValue();
8853     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8854     unsigned LSB = countTrailingZeros(~InvMask);
8855     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8856     unsigned Mask = (1 << Width)-1;
8857     unsigned Mask2 = N11C->getZExtValue();
8858     if ((Mask & (~Mask2)) == 0)
8859       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8860                              N->getOperand(0), N1.getOperand(0),
8861                              N->getOperand(2));
8862   }
8863   return SDValue();
8864 }
8865
8866 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8867 /// ARMISD::VMOVRRD.
8868 static SDValue PerformVMOVRRDCombine(SDNode *N,
8869                                      TargetLowering::DAGCombinerInfo &DCI) {
8870   // vmovrrd(vmovdrr x, y) -> x,y
8871   SDValue InDouble = N->getOperand(0);
8872   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8873     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8874
8875   // vmovrrd(load f64) -> (load i32), (load i32)
8876   SDNode *InNode = InDouble.getNode();
8877   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8878       InNode->getValueType(0) == MVT::f64 &&
8879       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8880       !cast<LoadSDNode>(InNode)->isVolatile()) {
8881     // TODO: Should this be done for non-FrameIndex operands?
8882     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8883
8884     SelectionDAG &DAG = DCI.DAG;
8885     SDLoc DL(LD);
8886     SDValue BasePtr = LD->getBasePtr();
8887     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8888                                  LD->getPointerInfo(), LD->isVolatile(),
8889                                  LD->isNonTemporal(), LD->isInvariant(),
8890                                  LD->getAlignment());
8891
8892     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8893                                     DAG.getConstant(4, MVT::i32));
8894     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8895                                  LD->getPointerInfo(), LD->isVolatile(),
8896                                  LD->isNonTemporal(), LD->isInvariant(),
8897                                  std::min(4U, LD->getAlignment() / 2));
8898
8899     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8900     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8901     DCI.RemoveFromWorklist(LD);
8902     DAG.DeleteNode(LD);
8903     return Result;
8904   }
8905
8906   return SDValue();
8907 }
8908
8909 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8910 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8911 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8912   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8913   SDValue Op0 = N->getOperand(0);
8914   SDValue Op1 = N->getOperand(1);
8915   if (Op0.getOpcode() == ISD::BITCAST)
8916     Op0 = Op0.getOperand(0);
8917   if (Op1.getOpcode() == ISD::BITCAST)
8918     Op1 = Op1.getOperand(0);
8919   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8920       Op0.getNode() == Op1.getNode() &&
8921       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8922     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8923                        N->getValueType(0), Op0.getOperand(0));
8924   return SDValue();
8925 }
8926
8927 /// PerformSTORECombine - Target-specific dag combine xforms for
8928 /// ISD::STORE.
8929 static SDValue PerformSTORECombine(SDNode *N,
8930                                    TargetLowering::DAGCombinerInfo &DCI) {
8931   StoreSDNode *St = cast<StoreSDNode>(N);
8932   if (St->isVolatile())
8933     return SDValue();
8934
8935   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8936   // pack all of the elements in one place.  Next, store to memory in fewer
8937   // chunks.
8938   SDValue StVal = St->getValue();
8939   EVT VT = StVal.getValueType();
8940   if (St->isTruncatingStore() && VT.isVector()) {
8941     SelectionDAG &DAG = DCI.DAG;
8942     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8943     EVT StVT = St->getMemoryVT();
8944     unsigned NumElems = VT.getVectorNumElements();
8945     assert(StVT != VT && "Cannot truncate to the same type");
8946     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8947     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8948
8949     // From, To sizes and ElemCount must be pow of two
8950     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8951
8952     // We are going to use the original vector elt for storing.
8953     // Accumulated smaller vector elements must be a multiple of the store size.
8954     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8955
8956     unsigned SizeRatio  = FromEltSz / ToEltSz;
8957     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8958
8959     // Create a type on which we perform the shuffle.
8960     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8961                                      NumElems*SizeRatio);
8962     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8963
8964     SDLoc DL(St);
8965     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8966     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8967     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8968
8969     // Can't shuffle using an illegal type.
8970     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8971
8972     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8973                                 DAG.getUNDEF(WideVec.getValueType()),
8974                                 ShuffleVec.data());
8975     // At this point all of the data is stored at the bottom of the
8976     // register. We now need to save it to mem.
8977
8978     // Find the largest store unit
8979     MVT StoreType = MVT::i8;
8980     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8981          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8982       MVT Tp = (MVT::SimpleValueType)tp;
8983       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8984         StoreType = Tp;
8985     }
8986     // Didn't find a legal store type.
8987     if (!TLI.isTypeLegal(StoreType))
8988       return SDValue();
8989
8990     // Bitcast the original vector into a vector of store-size units
8991     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8992             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8993     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8994     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8995     SmallVector<SDValue, 8> Chains;
8996     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8997                                         TLI.getPointerTy());
8998     SDValue BasePtr = St->getBasePtr();
8999
9000     // Perform one or more big stores into memory.
9001     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9002     for (unsigned I = 0; I < E; I++) {
9003       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9004                                    StoreType, ShuffWide,
9005                                    DAG.getIntPtrConstant(I));
9006       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9007                                 St->getPointerInfo(), St->isVolatile(),
9008                                 St->isNonTemporal(), St->getAlignment());
9009       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9010                             Increment);
9011       Chains.push_back(Ch);
9012     }
9013     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
9014                        Chains.size());
9015   }
9016
9017   if (!ISD::isNormalStore(St))
9018     return SDValue();
9019
9020   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9021   // ARM stores of arguments in the same cache line.
9022   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9023       StVal.getNode()->hasOneUse()) {
9024     SelectionDAG  &DAG = DCI.DAG;
9025     SDLoc DL(St);
9026     SDValue BasePtr = St->getBasePtr();
9027     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9028                                   StVal.getNode()->getOperand(0), BasePtr,
9029                                   St->getPointerInfo(), St->isVolatile(),
9030                                   St->isNonTemporal(), St->getAlignment());
9031
9032     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9033                                     DAG.getConstant(4, MVT::i32));
9034     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
9035                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9036                         St->isNonTemporal(),
9037                         std::min(4U, St->getAlignment() / 2));
9038   }
9039
9040   if (StVal.getValueType() != MVT::i64 ||
9041       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9042     return SDValue();
9043
9044   // Bitcast an i64 store extracted from a vector to f64.
9045   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9046   SelectionDAG &DAG = DCI.DAG;
9047   SDLoc dl(StVal);
9048   SDValue IntVec = StVal.getOperand(0);
9049   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9050                                  IntVec.getValueType().getVectorNumElements());
9051   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9052   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9053                                Vec, StVal.getOperand(1));
9054   dl = SDLoc(N);
9055   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9056   // Make the DAGCombiner fold the bitcasts.
9057   DCI.AddToWorklist(Vec.getNode());
9058   DCI.AddToWorklist(ExtElt.getNode());
9059   DCI.AddToWorklist(V.getNode());
9060   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9061                       St->getPointerInfo(), St->isVolatile(),
9062                       St->isNonTemporal(), St->getAlignment(),
9063                       St->getTBAAInfo());
9064 }
9065
9066 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9067 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
9068 /// i64 vector to have f64 elements, since the value can then be loaded
9069 /// directly into a VFP register.
9070 static bool hasNormalLoadOperand(SDNode *N) {
9071   unsigned NumElts = N->getValueType(0).getVectorNumElements();
9072   for (unsigned i = 0; i < NumElts; ++i) {
9073     SDNode *Elt = N->getOperand(i).getNode();
9074     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9075       return true;
9076   }
9077   return false;
9078 }
9079
9080 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9081 /// ISD::BUILD_VECTOR.
9082 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9083                                           TargetLowering::DAGCombinerInfo &DCI){
9084   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9085   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
9086   // into a pair of GPRs, which is fine when the value is used as a scalar,
9087   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9088   SelectionDAG &DAG = DCI.DAG;
9089   if (N->getNumOperands() == 2) {
9090     SDValue RV = PerformVMOVDRRCombine(N, DAG);
9091     if (RV.getNode())
9092       return RV;
9093   }
9094
9095   // Load i64 elements as f64 values so that type legalization does not split
9096   // them up into i32 values.
9097   EVT VT = N->getValueType(0);
9098   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9099     return SDValue();
9100   SDLoc dl(N);
9101   SmallVector<SDValue, 8> Ops;
9102   unsigned NumElts = VT.getVectorNumElements();
9103   for (unsigned i = 0; i < NumElts; ++i) {
9104     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9105     Ops.push_back(V);
9106     // Make the DAGCombiner fold the bitcast.
9107     DCI.AddToWorklist(V.getNode());
9108   }
9109   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9110   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
9111   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9112 }
9113
9114 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9115 static SDValue
9116 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9117   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9118   // At that time, we may have inserted bitcasts from integer to float.
9119   // If these bitcasts have survived DAGCombine, change the lowering of this
9120   // BUILD_VECTOR in something more vector friendly, i.e., that does not
9121   // force to use floating point types.
9122
9123   // Make sure we can change the type of the vector.
9124   // This is possible iff:
9125   // 1. The vector is only used in a bitcast to a integer type. I.e.,
9126   //    1.1. Vector is used only once.
9127   //    1.2. Use is a bit convert to an integer type.
9128   // 2. The size of its operands are 32-bits (64-bits are not legal).
9129   EVT VT = N->getValueType(0);
9130   EVT EltVT = VT.getVectorElementType();
9131
9132   // Check 1.1. and 2.
9133   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9134     return SDValue();
9135
9136   // By construction, the input type must be float.
9137   assert(EltVT == MVT::f32 && "Unexpected type!");
9138
9139   // Check 1.2.
9140   SDNode *Use = *N->use_begin();
9141   if (Use->getOpcode() != ISD::BITCAST ||
9142       Use->getValueType(0).isFloatingPoint())
9143     return SDValue();
9144
9145   // Check profitability.
9146   // Model is, if more than half of the relevant operands are bitcast from
9147   // i32, turn the build_vector into a sequence of insert_vector_elt.
9148   // Relevant operands are everything that is not statically
9149   // (i.e., at compile time) bitcasted.
9150   unsigned NumOfBitCastedElts = 0;
9151   unsigned NumElts = VT.getVectorNumElements();
9152   unsigned NumOfRelevantElts = NumElts;
9153   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9154     SDValue Elt = N->getOperand(Idx);
9155     if (Elt->getOpcode() == ISD::BITCAST) {
9156       // Assume only bit cast to i32 will go away.
9157       if (Elt->getOperand(0).getValueType() == MVT::i32)
9158         ++NumOfBitCastedElts;
9159     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9160       // Constants are statically casted, thus do not count them as
9161       // relevant operands.
9162       --NumOfRelevantElts;
9163   }
9164
9165   // Check if more than half of the elements require a non-free bitcast.
9166   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9167     return SDValue();
9168
9169   SelectionDAG &DAG = DCI.DAG;
9170   // Create the new vector type.
9171   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9172   // Check if the type is legal.
9173   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9174   if (!TLI.isTypeLegal(VecVT))
9175     return SDValue();
9176
9177   // Combine:
9178   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9179   // => BITCAST INSERT_VECTOR_ELT
9180   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9181   //                      (BITCAST EN), N.
9182   SDValue Vec = DAG.getUNDEF(VecVT);
9183   SDLoc dl(N);
9184   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9185     SDValue V = N->getOperand(Idx);
9186     if (V.getOpcode() == ISD::UNDEF)
9187       continue;
9188     if (V.getOpcode() == ISD::BITCAST &&
9189         V->getOperand(0).getValueType() == MVT::i32)
9190       // Fold obvious case.
9191       V = V.getOperand(0);
9192     else {
9193       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 
9194       // Make the DAGCombiner fold the bitcasts.
9195       DCI.AddToWorklist(V.getNode());
9196     }
9197     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
9198     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9199   }
9200   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9201   // Make the DAGCombiner fold the bitcasts.
9202   DCI.AddToWorklist(Vec.getNode());
9203   return Vec;
9204 }
9205
9206 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9207 /// ISD::INSERT_VECTOR_ELT.
9208 static SDValue PerformInsertEltCombine(SDNode *N,
9209                                        TargetLowering::DAGCombinerInfo &DCI) {
9210   // Bitcast an i64 load inserted into a vector to f64.
9211   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9212   EVT VT = N->getValueType(0);
9213   SDNode *Elt = N->getOperand(1).getNode();
9214   if (VT.getVectorElementType() != MVT::i64 ||
9215       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9216     return SDValue();
9217
9218   SelectionDAG &DAG = DCI.DAG;
9219   SDLoc dl(N);
9220   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9221                                  VT.getVectorNumElements());
9222   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9223   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9224   // Make the DAGCombiner fold the bitcasts.
9225   DCI.AddToWorklist(Vec.getNode());
9226   DCI.AddToWorklist(V.getNode());
9227   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9228                                Vec, V, N->getOperand(2));
9229   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9230 }
9231
9232 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9233 /// ISD::VECTOR_SHUFFLE.
9234 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9235   // The LLVM shufflevector instruction does not require the shuffle mask
9236   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9237   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
9238   // operands do not match the mask length, they are extended by concatenating
9239   // them with undef vectors.  That is probably the right thing for other
9240   // targets, but for NEON it is better to concatenate two double-register
9241   // size vector operands into a single quad-register size vector.  Do that
9242   // transformation here:
9243   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
9244   //   shuffle(concat(v1, v2), undef)
9245   SDValue Op0 = N->getOperand(0);
9246   SDValue Op1 = N->getOperand(1);
9247   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9248       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9249       Op0.getNumOperands() != 2 ||
9250       Op1.getNumOperands() != 2)
9251     return SDValue();
9252   SDValue Concat0Op1 = Op0.getOperand(1);
9253   SDValue Concat1Op1 = Op1.getOperand(1);
9254   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9255       Concat1Op1.getOpcode() != ISD::UNDEF)
9256     return SDValue();
9257   // Skip the transformation if any of the types are illegal.
9258   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9259   EVT VT = N->getValueType(0);
9260   if (!TLI.isTypeLegal(VT) ||
9261       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9262       !TLI.isTypeLegal(Concat1Op1.getValueType()))
9263     return SDValue();
9264
9265   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9266                                   Op0.getOperand(0), Op1.getOperand(0));
9267   // Translate the shuffle mask.
9268   SmallVector<int, 16> NewMask;
9269   unsigned NumElts = VT.getVectorNumElements();
9270   unsigned HalfElts = NumElts/2;
9271   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9272   for (unsigned n = 0; n < NumElts; ++n) {
9273     int MaskElt = SVN->getMaskElt(n);
9274     int NewElt = -1;
9275     if (MaskElt < (int)HalfElts)
9276       NewElt = MaskElt;
9277     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9278       NewElt = HalfElts + MaskElt - NumElts;
9279     NewMask.push_back(NewElt);
9280   }
9281   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9282                               DAG.getUNDEF(VT), NewMask.data());
9283 }
9284
9285 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
9286 /// NEON load/store intrinsics to merge base address updates.
9287 static SDValue CombineBaseUpdate(SDNode *N,
9288                                  TargetLowering::DAGCombinerInfo &DCI) {
9289   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9290     return SDValue();
9291
9292   SelectionDAG &DAG = DCI.DAG;
9293   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9294                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9295   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
9296   SDValue Addr = N->getOperand(AddrOpIdx);
9297
9298   // Search for a use of the address operand that is an increment.
9299   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9300          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9301     SDNode *User = *UI;
9302     if (User->getOpcode() != ISD::ADD ||
9303         UI.getUse().getResNo() != Addr.getResNo())
9304       continue;
9305
9306     // Check that the add is independent of the load/store.  Otherwise, folding
9307     // it would create a cycle.
9308     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9309       continue;
9310
9311     // Find the new opcode for the updating load/store.
9312     bool isLoad = true;
9313     bool isLaneOp = false;
9314     unsigned NewOpc = 0;
9315     unsigned NumVecs = 0;
9316     if (isIntrinsic) {
9317       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9318       switch (IntNo) {
9319       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9320       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9321         NumVecs = 1; break;
9322       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9323         NumVecs = 2; break;
9324       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9325         NumVecs = 3; break;
9326       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9327         NumVecs = 4; break;
9328       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9329         NumVecs = 2; isLaneOp = true; break;
9330       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9331         NumVecs = 3; isLaneOp = true; break;
9332       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9333         NumVecs = 4; isLaneOp = true; break;
9334       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9335         NumVecs = 1; isLoad = false; break;
9336       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9337         NumVecs = 2; isLoad = false; break;
9338       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9339         NumVecs = 3; isLoad = false; break;
9340       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9341         NumVecs = 4; isLoad = false; break;
9342       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9343         NumVecs = 2; isLoad = false; isLaneOp = true; break;
9344       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9345         NumVecs = 3; isLoad = false; isLaneOp = true; break;
9346       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9347         NumVecs = 4; isLoad = false; isLaneOp = true; break;
9348       }
9349     } else {
9350       isLaneOp = true;
9351       switch (N->getOpcode()) {
9352       default: llvm_unreachable("unexpected opcode for Neon base update");
9353       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9354       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9355       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9356       }
9357     }
9358
9359     // Find the size of memory referenced by the load/store.
9360     EVT VecTy;
9361     if (isLoad)
9362       VecTy = N->getValueType(0);
9363     else
9364       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9365     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9366     if (isLaneOp)
9367       NumBytes /= VecTy.getVectorNumElements();
9368
9369     // If the increment is a constant, it must match the memory ref size.
9370     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9371     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9372       uint64_t IncVal = CInc->getZExtValue();
9373       if (IncVal != NumBytes)
9374         continue;
9375     } else if (NumBytes >= 3 * 16) {
9376       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9377       // separate instructions that make it harder to use a non-constant update.
9378       continue;
9379     }
9380
9381     // Create the new updating load/store node.
9382     EVT Tys[6];
9383     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
9384     unsigned n;
9385     for (n = 0; n < NumResultVecs; ++n)
9386       Tys[n] = VecTy;
9387     Tys[n++] = MVT::i32;
9388     Tys[n] = MVT::Other;
9389     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
9390     SmallVector<SDValue, 8> Ops;
9391     Ops.push_back(N->getOperand(0)); // incoming chain
9392     Ops.push_back(N->getOperand(AddrOpIdx));
9393     Ops.push_back(Inc);
9394     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
9395       Ops.push_back(N->getOperand(i));
9396     }
9397     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9398     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9399                                            Ops.data(), Ops.size(),
9400                                            MemInt->getMemoryVT(),
9401                                            MemInt->getMemOperand());
9402
9403     // Update the uses.
9404     std::vector<SDValue> NewResults;
9405     for (unsigned i = 0; i < NumResultVecs; ++i) {
9406       NewResults.push_back(SDValue(UpdN.getNode(), i));
9407     }
9408     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9409     DCI.CombineTo(N, NewResults);
9410     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9411
9412     break;
9413   }
9414   return SDValue();
9415 }
9416
9417 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9418 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9419 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9420 /// return true.
9421 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9422   SelectionDAG &DAG = DCI.DAG;
9423   EVT VT = N->getValueType(0);
9424   // vldN-dup instructions only support 64-bit vectors for N > 1.
9425   if (!VT.is64BitVector())
9426     return false;
9427
9428   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9429   SDNode *VLD = N->getOperand(0).getNode();
9430   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9431     return false;
9432   unsigned NumVecs = 0;
9433   unsigned NewOpc = 0;
9434   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9435   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9436     NumVecs = 2;
9437     NewOpc = ARMISD::VLD2DUP;
9438   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9439     NumVecs = 3;
9440     NewOpc = ARMISD::VLD3DUP;
9441   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9442     NumVecs = 4;
9443     NewOpc = ARMISD::VLD4DUP;
9444   } else {
9445     return false;
9446   }
9447
9448   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9449   // numbers match the load.
9450   unsigned VLDLaneNo =
9451     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9452   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9453        UI != UE; ++UI) {
9454     // Ignore uses of the chain result.
9455     if (UI.getUse().getResNo() == NumVecs)
9456       continue;
9457     SDNode *User = *UI;
9458     if (User->getOpcode() != ARMISD::VDUPLANE ||
9459         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9460       return false;
9461   }
9462
9463   // Create the vldN-dup node.
9464   EVT Tys[5];
9465   unsigned n;
9466   for (n = 0; n < NumVecs; ++n)
9467     Tys[n] = VT;
9468   Tys[n] = MVT::Other;
9469   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
9470   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9471   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9472   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9473                                            Ops, 2, VLDMemInt->getMemoryVT(),
9474                                            VLDMemInt->getMemOperand());
9475
9476   // Update the uses.
9477   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9478        UI != UE; ++UI) {
9479     unsigned ResNo = UI.getUse().getResNo();
9480     // Ignore uses of the chain result.
9481     if (ResNo == NumVecs)
9482       continue;
9483     SDNode *User = *UI;
9484     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9485   }
9486
9487   // Now the vldN-lane intrinsic is dead except for its chain result.
9488   // Update uses of the chain.
9489   std::vector<SDValue> VLDDupResults;
9490   for (unsigned n = 0; n < NumVecs; ++n)
9491     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9492   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9493   DCI.CombineTo(VLD, VLDDupResults);
9494
9495   return true;
9496 }
9497
9498 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9499 /// ARMISD::VDUPLANE.
9500 static SDValue PerformVDUPLANECombine(SDNode *N,
9501                                       TargetLowering::DAGCombinerInfo &DCI) {
9502   SDValue Op = N->getOperand(0);
9503
9504   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9505   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9506   if (CombineVLDDUP(N, DCI))
9507     return SDValue(N, 0);
9508
9509   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9510   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9511   while (Op.getOpcode() == ISD::BITCAST)
9512     Op = Op.getOperand(0);
9513   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9514     return SDValue();
9515
9516   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9517   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9518   // The canonical VMOV for a zero vector uses a 32-bit element size.
9519   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9520   unsigned EltBits;
9521   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9522     EltSize = 8;
9523   EVT VT = N->getValueType(0);
9524   if (EltSize > VT.getVectorElementType().getSizeInBits())
9525     return SDValue();
9526
9527   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9528 }
9529
9530 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9531 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9532 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9533 {
9534   integerPart cN;
9535   integerPart c0 = 0;
9536   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9537        I != E; I++) {
9538     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9539     if (!C)
9540       return false;
9541
9542     bool isExact;
9543     APFloat APF = C->getValueAPF();
9544     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9545         != APFloat::opOK || !isExact)
9546       return false;
9547
9548     c0 = (I == 0) ? cN : c0;
9549     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9550       return false;
9551   }
9552   C = c0;
9553   return true;
9554 }
9555
9556 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9557 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9558 /// when the VMUL has a constant operand that is a power of 2.
9559 ///
9560 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9561 ///  vmul.f32        d16, d17, d16
9562 ///  vcvt.s32.f32    d16, d16
9563 /// becomes:
9564 ///  vcvt.s32.f32    d16, d16, #3
9565 static SDValue PerformVCVTCombine(SDNode *N,
9566                                   TargetLowering::DAGCombinerInfo &DCI,
9567                                   const ARMSubtarget *Subtarget) {
9568   SelectionDAG &DAG = DCI.DAG;
9569   SDValue Op = N->getOperand(0);
9570
9571   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9572       Op.getOpcode() != ISD::FMUL)
9573     return SDValue();
9574
9575   uint64_t C;
9576   SDValue N0 = Op->getOperand(0);
9577   SDValue ConstVec = Op->getOperand(1);
9578   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9579
9580   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9581       !isConstVecPow2(ConstVec, isSigned, C))
9582     return SDValue();
9583
9584   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9585   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9586   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9587     // These instructions only exist converting from f32 to i32. We can handle
9588     // smaller integers by generating an extra truncate, but larger ones would
9589     // be lossy.
9590     return SDValue();
9591   }
9592
9593   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9594     Intrinsic::arm_neon_vcvtfp2fxu;
9595   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9596   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9597                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9598                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9599                                  DAG.getConstant(Log2_64(C), MVT::i32));
9600
9601   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9602     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9603
9604   return FixConv;
9605 }
9606
9607 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9608 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9609 /// when the VDIV has a constant operand that is a power of 2.
9610 ///
9611 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9612 ///  vcvt.f32.s32    d16, d16
9613 ///  vdiv.f32        d16, d17, d16
9614 /// becomes:
9615 ///  vcvt.f32.s32    d16, d16, #3
9616 static SDValue PerformVDIVCombine(SDNode *N,
9617                                   TargetLowering::DAGCombinerInfo &DCI,
9618                                   const ARMSubtarget *Subtarget) {
9619   SelectionDAG &DAG = DCI.DAG;
9620   SDValue Op = N->getOperand(0);
9621   unsigned OpOpcode = Op.getNode()->getOpcode();
9622
9623   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9624       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9625     return SDValue();
9626
9627   uint64_t C;
9628   SDValue ConstVec = N->getOperand(1);
9629   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9630
9631   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9632       !isConstVecPow2(ConstVec, isSigned, C))
9633     return SDValue();
9634
9635   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9636   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9637   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9638     // These instructions only exist converting from i32 to f32. We can handle
9639     // smaller integers by generating an extra extend, but larger ones would
9640     // be lossy.
9641     return SDValue();
9642   }
9643
9644   SDValue ConvInput = Op.getOperand(0);
9645   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9646   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9647     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9648                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9649                             ConvInput);
9650
9651   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9652     Intrinsic::arm_neon_vcvtfxu2fp;
9653   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9654                      Op.getValueType(),
9655                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9656                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9657 }
9658
9659 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9660 /// operand of a vector shift operation, where all the elements of the
9661 /// build_vector must have the same constant integer value.
9662 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9663   // Ignore bit_converts.
9664   while (Op.getOpcode() == ISD::BITCAST)
9665     Op = Op.getOperand(0);
9666   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9667   APInt SplatBits, SplatUndef;
9668   unsigned SplatBitSize;
9669   bool HasAnyUndefs;
9670   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9671                                       HasAnyUndefs, ElementBits) ||
9672       SplatBitSize > ElementBits)
9673     return false;
9674   Cnt = SplatBits.getSExtValue();
9675   return true;
9676 }
9677
9678 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9679 /// operand of a vector shift left operation.  That value must be in the range:
9680 ///   0 <= Value < ElementBits for a left shift; or
9681 ///   0 <= Value <= ElementBits for a long left shift.
9682 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9683   assert(VT.isVector() && "vector shift count is not a vector type");
9684   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9685   if (! getVShiftImm(Op, ElementBits, Cnt))
9686     return false;
9687   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9688 }
9689
9690 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9691 /// operand of a vector shift right operation.  For a shift opcode, the value
9692 /// is positive, but for an intrinsic the value count must be negative. The
9693 /// absolute value must be in the range:
9694 ///   1 <= |Value| <= ElementBits for a right shift; or
9695 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9696 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9697                          int64_t &Cnt) {
9698   assert(VT.isVector() && "vector shift count is not a vector type");
9699   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9700   if (! getVShiftImm(Op, ElementBits, Cnt))
9701     return false;
9702   if (isIntrinsic)
9703     Cnt = -Cnt;
9704   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9705 }
9706
9707 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9708 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9709   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9710   switch (IntNo) {
9711   default:
9712     // Don't do anything for most intrinsics.
9713     break;
9714
9715   // Vector shifts: check for immediate versions and lower them.
9716   // Note: This is done during DAG combining instead of DAG legalizing because
9717   // the build_vectors for 64-bit vector element shift counts are generally
9718   // not legal, and it is hard to see their values after they get legalized to
9719   // loads from a constant pool.
9720   case Intrinsic::arm_neon_vshifts:
9721   case Intrinsic::arm_neon_vshiftu:
9722   case Intrinsic::arm_neon_vshiftls:
9723   case Intrinsic::arm_neon_vshiftlu:
9724   case Intrinsic::arm_neon_vshiftn:
9725   case Intrinsic::arm_neon_vrshifts:
9726   case Intrinsic::arm_neon_vrshiftu:
9727   case Intrinsic::arm_neon_vrshiftn:
9728   case Intrinsic::arm_neon_vqshifts:
9729   case Intrinsic::arm_neon_vqshiftu:
9730   case Intrinsic::arm_neon_vqshiftsu:
9731   case Intrinsic::arm_neon_vqshiftns:
9732   case Intrinsic::arm_neon_vqshiftnu:
9733   case Intrinsic::arm_neon_vqshiftnsu:
9734   case Intrinsic::arm_neon_vqrshiftns:
9735   case Intrinsic::arm_neon_vqrshiftnu:
9736   case Intrinsic::arm_neon_vqrshiftnsu: {
9737     EVT VT = N->getOperand(1).getValueType();
9738     int64_t Cnt;
9739     unsigned VShiftOpc = 0;
9740
9741     switch (IntNo) {
9742     case Intrinsic::arm_neon_vshifts:
9743     case Intrinsic::arm_neon_vshiftu:
9744       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9745         VShiftOpc = ARMISD::VSHL;
9746         break;
9747       }
9748       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9749         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9750                      ARMISD::VSHRs : ARMISD::VSHRu);
9751         break;
9752       }
9753       return SDValue();
9754
9755     case Intrinsic::arm_neon_vshiftls:
9756     case Intrinsic::arm_neon_vshiftlu:
9757       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
9758         break;
9759       llvm_unreachable("invalid shift count for vshll intrinsic");
9760
9761     case Intrinsic::arm_neon_vrshifts:
9762     case Intrinsic::arm_neon_vrshiftu:
9763       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9764         break;
9765       return SDValue();
9766
9767     case Intrinsic::arm_neon_vqshifts:
9768     case Intrinsic::arm_neon_vqshiftu:
9769       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9770         break;
9771       return SDValue();
9772
9773     case Intrinsic::arm_neon_vqshiftsu:
9774       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9775         break;
9776       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9777
9778     case Intrinsic::arm_neon_vshiftn:
9779     case Intrinsic::arm_neon_vrshiftn:
9780     case Intrinsic::arm_neon_vqshiftns:
9781     case Intrinsic::arm_neon_vqshiftnu:
9782     case Intrinsic::arm_neon_vqshiftnsu:
9783     case Intrinsic::arm_neon_vqrshiftns:
9784     case Intrinsic::arm_neon_vqrshiftnu:
9785     case Intrinsic::arm_neon_vqrshiftnsu:
9786       // Narrowing shifts require an immediate right shift.
9787       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9788         break;
9789       llvm_unreachable("invalid shift count for narrowing vector shift "
9790                        "intrinsic");
9791
9792     default:
9793       llvm_unreachable("unhandled vector shift");
9794     }
9795
9796     switch (IntNo) {
9797     case Intrinsic::arm_neon_vshifts:
9798     case Intrinsic::arm_neon_vshiftu:
9799       // Opcode already set above.
9800       break;
9801     case Intrinsic::arm_neon_vshiftls:
9802     case Intrinsic::arm_neon_vshiftlu:
9803       if (Cnt == VT.getVectorElementType().getSizeInBits())
9804         VShiftOpc = ARMISD::VSHLLi;
9805       else
9806         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
9807                      ARMISD::VSHLLs : ARMISD::VSHLLu);
9808       break;
9809     case Intrinsic::arm_neon_vshiftn:
9810       VShiftOpc = ARMISD::VSHRN; break;
9811     case Intrinsic::arm_neon_vrshifts:
9812       VShiftOpc = ARMISD::VRSHRs; break;
9813     case Intrinsic::arm_neon_vrshiftu:
9814       VShiftOpc = ARMISD::VRSHRu; break;
9815     case Intrinsic::arm_neon_vrshiftn:
9816       VShiftOpc = ARMISD::VRSHRN; break;
9817     case Intrinsic::arm_neon_vqshifts:
9818       VShiftOpc = ARMISD::VQSHLs; break;
9819     case Intrinsic::arm_neon_vqshiftu:
9820       VShiftOpc = ARMISD::VQSHLu; break;
9821     case Intrinsic::arm_neon_vqshiftsu:
9822       VShiftOpc = ARMISD::VQSHLsu; break;
9823     case Intrinsic::arm_neon_vqshiftns:
9824       VShiftOpc = ARMISD::VQSHRNs; break;
9825     case Intrinsic::arm_neon_vqshiftnu:
9826       VShiftOpc = ARMISD::VQSHRNu; break;
9827     case Intrinsic::arm_neon_vqshiftnsu:
9828       VShiftOpc = ARMISD::VQSHRNsu; break;
9829     case Intrinsic::arm_neon_vqrshiftns:
9830       VShiftOpc = ARMISD::VQRSHRNs; break;
9831     case Intrinsic::arm_neon_vqrshiftnu:
9832       VShiftOpc = ARMISD::VQRSHRNu; break;
9833     case Intrinsic::arm_neon_vqrshiftnsu:
9834       VShiftOpc = ARMISD::VQRSHRNsu; break;
9835     }
9836
9837     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9838                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9839   }
9840
9841   case Intrinsic::arm_neon_vshiftins: {
9842     EVT VT = N->getOperand(1).getValueType();
9843     int64_t Cnt;
9844     unsigned VShiftOpc = 0;
9845
9846     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9847       VShiftOpc = ARMISD::VSLI;
9848     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9849       VShiftOpc = ARMISD::VSRI;
9850     else {
9851       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9852     }
9853
9854     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9855                        N->getOperand(1), N->getOperand(2),
9856                        DAG.getConstant(Cnt, MVT::i32));
9857   }
9858
9859   case Intrinsic::arm_neon_vqrshifts:
9860   case Intrinsic::arm_neon_vqrshiftu:
9861     // No immediate versions of these to check for.
9862     break;
9863   }
9864
9865   return SDValue();
9866 }
9867
9868 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9869 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9870 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9871 /// vector element shift counts are generally not legal, and it is hard to see
9872 /// their values after they get legalized to loads from a constant pool.
9873 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9874                                    const ARMSubtarget *ST) {
9875   EVT VT = N->getValueType(0);
9876   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9877     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9878     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9879     SDValue N1 = N->getOperand(1);
9880     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9881       SDValue N0 = N->getOperand(0);
9882       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9883           DAG.MaskedValueIsZero(N0.getOperand(0),
9884                                 APInt::getHighBitsSet(32, 16)))
9885         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9886     }
9887   }
9888
9889   // Nothing to be done for scalar shifts.
9890   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9891   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9892     return SDValue();
9893
9894   assert(ST->hasNEON() && "unexpected vector shift");
9895   int64_t Cnt;
9896
9897   switch (N->getOpcode()) {
9898   default: llvm_unreachable("unexpected shift opcode");
9899
9900   case ISD::SHL:
9901     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9902       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9903                          DAG.getConstant(Cnt, MVT::i32));
9904     break;
9905
9906   case ISD::SRA:
9907   case ISD::SRL:
9908     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9909       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9910                             ARMISD::VSHRs : ARMISD::VSHRu);
9911       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9912                          DAG.getConstant(Cnt, MVT::i32));
9913     }
9914   }
9915   return SDValue();
9916 }
9917
9918 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9919 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9920 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9921                                     const ARMSubtarget *ST) {
9922   SDValue N0 = N->getOperand(0);
9923
9924   // Check for sign- and zero-extensions of vector extract operations of 8-
9925   // and 16-bit vector elements.  NEON supports these directly.  They are
9926   // handled during DAG combining because type legalization will promote them
9927   // to 32-bit types and it is messy to recognize the operations after that.
9928   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9929     SDValue Vec = N0.getOperand(0);
9930     SDValue Lane = N0.getOperand(1);
9931     EVT VT = N->getValueType(0);
9932     EVT EltVT = N0.getValueType();
9933     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9934
9935     if (VT == MVT::i32 &&
9936         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9937         TLI.isTypeLegal(Vec.getValueType()) &&
9938         isa<ConstantSDNode>(Lane)) {
9939
9940       unsigned Opc = 0;
9941       switch (N->getOpcode()) {
9942       default: llvm_unreachable("unexpected opcode");
9943       case ISD::SIGN_EXTEND:
9944         Opc = ARMISD::VGETLANEs;
9945         break;
9946       case ISD::ZERO_EXTEND:
9947       case ISD::ANY_EXTEND:
9948         Opc = ARMISD::VGETLANEu;
9949         break;
9950       }
9951       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9952     }
9953   }
9954
9955   return SDValue();
9956 }
9957
9958 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9959 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9960 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9961                                        const ARMSubtarget *ST) {
9962   // If the target supports NEON, try to use vmax/vmin instructions for f32
9963   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9964   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9965   // a NaN; only do the transformation when it matches that behavior.
9966
9967   // For now only do this when using NEON for FP operations; if using VFP, it
9968   // is not obvious that the benefit outweighs the cost of switching to the
9969   // NEON pipeline.
9970   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9971       N->getValueType(0) != MVT::f32)
9972     return SDValue();
9973
9974   SDValue CondLHS = N->getOperand(0);
9975   SDValue CondRHS = N->getOperand(1);
9976   SDValue LHS = N->getOperand(2);
9977   SDValue RHS = N->getOperand(3);
9978   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9979
9980   unsigned Opcode = 0;
9981   bool IsReversed;
9982   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9983     IsReversed = false; // x CC y ? x : y
9984   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9985     IsReversed = true ; // x CC y ? y : x
9986   } else {
9987     return SDValue();
9988   }
9989
9990   bool IsUnordered;
9991   switch (CC) {
9992   default: break;
9993   case ISD::SETOLT:
9994   case ISD::SETOLE:
9995   case ISD::SETLT:
9996   case ISD::SETLE:
9997   case ISD::SETULT:
9998   case ISD::SETULE:
9999     // If LHS is NaN, an ordered comparison will be false and the result will
10000     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
10001     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
10002     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
10003     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10004       break;
10005     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
10006     // will return -0, so vmin can only be used for unsafe math or if one of
10007     // the operands is known to be nonzero.
10008     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
10009         !DAG.getTarget().Options.UnsafeFPMath &&
10010         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10011       break;
10012     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
10013     break;
10014
10015   case ISD::SETOGT:
10016   case ISD::SETOGE:
10017   case ISD::SETGT:
10018   case ISD::SETGE:
10019   case ISD::SETUGT:
10020   case ISD::SETUGE:
10021     // If LHS is NaN, an ordered comparison will be false and the result will
10022     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
10023     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
10024     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
10025     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10026       break;
10027     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
10028     // will return +0, so vmax can only be used for unsafe math or if one of
10029     // the operands is known to be nonzero.
10030     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
10031         !DAG.getTarget().Options.UnsafeFPMath &&
10032         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10033       break;
10034     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
10035     break;
10036   }
10037
10038   if (!Opcode)
10039     return SDValue();
10040   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
10041 }
10042
10043 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10044 SDValue
10045 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10046   SDValue Cmp = N->getOperand(4);
10047   if (Cmp.getOpcode() != ARMISD::CMPZ)
10048     // Only looking at EQ and NE cases.
10049     return SDValue();
10050
10051   EVT VT = N->getValueType(0);
10052   SDLoc dl(N);
10053   SDValue LHS = Cmp.getOperand(0);
10054   SDValue RHS = Cmp.getOperand(1);
10055   SDValue FalseVal = N->getOperand(0);
10056   SDValue TrueVal = N->getOperand(1);
10057   SDValue ARMcc = N->getOperand(2);
10058   ARMCC::CondCodes CC =
10059     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10060
10061   // Simplify
10062   //   mov     r1, r0
10063   //   cmp     r1, x
10064   //   mov     r0, y
10065   //   moveq   r0, x
10066   // to
10067   //   cmp     r0, x
10068   //   movne   r0, y
10069   //
10070   //   mov     r1, r0
10071   //   cmp     r1, x
10072   //   mov     r0, x
10073   //   movne   r0, y
10074   // to
10075   //   cmp     r0, x
10076   //   movne   r0, y
10077   /// FIXME: Turn this into a target neutral optimization?
10078   SDValue Res;
10079   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10080     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10081                       N->getOperand(3), Cmp);
10082   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10083     SDValue ARMcc;
10084     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10085     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10086                       N->getOperand(3), NewCmp);
10087   }
10088
10089   if (Res.getNode()) {
10090     APInt KnownZero, KnownOne;
10091     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
10092     // Capture demanded bits information that would be otherwise lost.
10093     if (KnownZero == 0xfffffffe)
10094       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10095                         DAG.getValueType(MVT::i1));
10096     else if (KnownZero == 0xffffff00)
10097       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10098                         DAG.getValueType(MVT::i8));
10099     else if (KnownZero == 0xffff0000)
10100       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10101                         DAG.getValueType(MVT::i16));
10102   }
10103
10104   return Res;
10105 }
10106
10107 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10108                                              DAGCombinerInfo &DCI) const {
10109   switch (N->getOpcode()) {
10110   default: break;
10111   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
10112   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
10113   case ISD::SUB:        return PerformSUBCombine(N, DCI);
10114   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
10115   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
10116   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
10117   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
10118   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
10119   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
10120   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10121   case ISD::STORE:      return PerformSTORECombine(N, DCI);
10122   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
10123   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10124   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10125   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10126   case ISD::FP_TO_SINT:
10127   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10128   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
10129   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10130   case ISD::SHL:
10131   case ISD::SRA:
10132   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10133   case ISD::SIGN_EXTEND:
10134   case ISD::ZERO_EXTEND:
10135   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10136   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
10137   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10138   case ARMISD::VLD2DUP:
10139   case ARMISD::VLD3DUP:
10140   case ARMISD::VLD4DUP:
10141     return CombineBaseUpdate(N, DCI);
10142   case ARMISD::BUILD_VECTOR:
10143     return PerformARMBUILD_VECTORCombine(N, DCI);
10144   case ISD::INTRINSIC_VOID:
10145   case ISD::INTRINSIC_W_CHAIN:
10146     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10147     case Intrinsic::arm_neon_vld1:
10148     case Intrinsic::arm_neon_vld2:
10149     case Intrinsic::arm_neon_vld3:
10150     case Intrinsic::arm_neon_vld4:
10151     case Intrinsic::arm_neon_vld2lane:
10152     case Intrinsic::arm_neon_vld3lane:
10153     case Intrinsic::arm_neon_vld4lane:
10154     case Intrinsic::arm_neon_vst1:
10155     case Intrinsic::arm_neon_vst2:
10156     case Intrinsic::arm_neon_vst3:
10157     case Intrinsic::arm_neon_vst4:
10158     case Intrinsic::arm_neon_vst2lane:
10159     case Intrinsic::arm_neon_vst3lane:
10160     case Intrinsic::arm_neon_vst4lane:
10161       return CombineBaseUpdate(N, DCI);
10162     default: break;
10163     }
10164     break;
10165   }
10166   return SDValue();
10167 }
10168
10169 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10170                                                           EVT VT) const {
10171   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10172 }
10173
10174 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
10175   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10176   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10177
10178   switch (VT.getSimpleVT().SimpleTy) {
10179   default:
10180     return false;
10181   case MVT::i8:
10182   case MVT::i16:
10183   case MVT::i32: {
10184     // Unaligned access can use (for example) LRDB, LRDH, LDR
10185     if (AllowsUnaligned) {
10186       if (Fast)
10187         *Fast = Subtarget->hasV7Ops();
10188       return true;
10189     }
10190     return false;
10191   }
10192   case MVT::f64:
10193   case MVT::v2f64: {
10194     // For any little-endian targets with neon, we can support unaligned ld/st
10195     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10196     // A big-endian target may also explictly support unaligned accesses
10197     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
10198       if (Fast)
10199         *Fast = true;
10200       return true;
10201     }
10202     return false;
10203   }
10204   }
10205 }
10206
10207 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10208                        unsigned AlignCheck) {
10209   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10210           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10211 }
10212
10213 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10214                                            unsigned DstAlign, unsigned SrcAlign,
10215                                            bool IsMemset, bool ZeroMemset,
10216                                            bool MemcpyStrSrc,
10217                                            MachineFunction &MF) const {
10218   const Function *F = MF.getFunction();
10219
10220   // See if we can use NEON instructions for this...
10221   if ((!IsMemset || ZeroMemset) &&
10222       Subtarget->hasNEON() &&
10223       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
10224                                        Attribute::NoImplicitFloat)) {
10225     bool Fast;
10226     if (Size >= 16 &&
10227         (memOpAlign(SrcAlign, DstAlign, 16) ||
10228          (allowsUnalignedMemoryAccesses(MVT::v2f64, &Fast) && Fast))) {
10229       return MVT::v2f64;
10230     } else if (Size >= 8 &&
10231                (memOpAlign(SrcAlign, DstAlign, 8) ||
10232                 (allowsUnalignedMemoryAccesses(MVT::f64, &Fast) && Fast))) {
10233       return MVT::f64;
10234     }
10235   }
10236
10237   // Lowering to i32/i16 if the size permits.
10238   if (Size >= 4)
10239     return MVT::i32;
10240   else if (Size >= 2)
10241     return MVT::i16;
10242
10243   // Let the target-independent logic figure it out.
10244   return MVT::Other;
10245 }
10246
10247 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10248   if (Val.getOpcode() != ISD::LOAD)
10249     return false;
10250
10251   EVT VT1 = Val.getValueType();
10252   if (!VT1.isSimple() || !VT1.isInteger() ||
10253       !VT2.isSimple() || !VT2.isInteger())
10254     return false;
10255
10256   switch (VT1.getSimpleVT().SimpleTy) {
10257   default: break;
10258   case MVT::i1:
10259   case MVT::i8:
10260   case MVT::i16:
10261     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10262     return true;
10263   }
10264
10265   return false;
10266 }
10267
10268 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10269   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10270     return false;
10271
10272   if (!isTypeLegal(EVT::getEVT(Ty1)))
10273     return false;
10274
10275   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10276
10277   // Assuming the caller doesn't have a zeroext or signext return parameter,
10278   // truncation all the way down to i1 is valid.
10279   return true;
10280 }
10281
10282
10283 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10284   if (V < 0)
10285     return false;
10286
10287   unsigned Scale = 1;
10288   switch (VT.getSimpleVT().SimpleTy) {
10289   default: return false;
10290   case MVT::i1:
10291   case MVT::i8:
10292     // Scale == 1;
10293     break;
10294   case MVT::i16:
10295     // Scale == 2;
10296     Scale = 2;
10297     break;
10298   case MVT::i32:
10299     // Scale == 4;
10300     Scale = 4;
10301     break;
10302   }
10303
10304   if ((V & (Scale - 1)) != 0)
10305     return false;
10306   V /= Scale;
10307   return V == (V & ((1LL << 5) - 1));
10308 }
10309
10310 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10311                                       const ARMSubtarget *Subtarget) {
10312   bool isNeg = false;
10313   if (V < 0) {
10314     isNeg = true;
10315     V = - V;
10316   }
10317
10318   switch (VT.getSimpleVT().SimpleTy) {
10319   default: return false;
10320   case MVT::i1:
10321   case MVT::i8:
10322   case MVT::i16:
10323   case MVT::i32:
10324     // + imm12 or - imm8
10325     if (isNeg)
10326       return V == (V & ((1LL << 8) - 1));
10327     return V == (V & ((1LL << 12) - 1));
10328   case MVT::f32:
10329   case MVT::f64:
10330     // Same as ARM mode. FIXME: NEON?
10331     if (!Subtarget->hasVFP2())
10332       return false;
10333     if ((V & 3) != 0)
10334       return false;
10335     V >>= 2;
10336     return V == (V & ((1LL << 8) - 1));
10337   }
10338 }
10339
10340 /// isLegalAddressImmediate - Return true if the integer value can be used
10341 /// as the offset of the target addressing mode for load / store of the
10342 /// given type.
10343 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10344                                     const ARMSubtarget *Subtarget) {
10345   if (V == 0)
10346     return true;
10347
10348   if (!VT.isSimple())
10349     return false;
10350
10351   if (Subtarget->isThumb1Only())
10352     return isLegalT1AddressImmediate(V, VT);
10353   else if (Subtarget->isThumb2())
10354     return isLegalT2AddressImmediate(V, VT, Subtarget);
10355
10356   // ARM mode.
10357   if (V < 0)
10358     V = - V;
10359   switch (VT.getSimpleVT().SimpleTy) {
10360   default: return false;
10361   case MVT::i1:
10362   case MVT::i8:
10363   case MVT::i32:
10364     // +- imm12
10365     return V == (V & ((1LL << 12) - 1));
10366   case MVT::i16:
10367     // +- imm8
10368     return V == (V & ((1LL << 8) - 1));
10369   case MVT::f32:
10370   case MVT::f64:
10371     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10372       return false;
10373     if ((V & 3) != 0)
10374       return false;
10375     V >>= 2;
10376     return V == (V & ((1LL << 8) - 1));
10377   }
10378 }
10379
10380 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10381                                                       EVT VT) const {
10382   int Scale = AM.Scale;
10383   if (Scale < 0)
10384     return false;
10385
10386   switch (VT.getSimpleVT().SimpleTy) {
10387   default: return false;
10388   case MVT::i1:
10389   case MVT::i8:
10390   case MVT::i16:
10391   case MVT::i32:
10392     if (Scale == 1)
10393       return true;
10394     // r + r << imm
10395     Scale = Scale & ~1;
10396     return Scale == 2 || Scale == 4 || Scale == 8;
10397   case MVT::i64:
10398     // r + r
10399     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10400       return true;
10401     return false;
10402   case MVT::isVoid:
10403     // Note, we allow "void" uses (basically, uses that aren't loads or
10404     // stores), because arm allows folding a scale into many arithmetic
10405     // operations.  This should be made more precise and revisited later.
10406
10407     // Allow r << imm, but the imm has to be a multiple of two.
10408     if (Scale & 1) return false;
10409     return isPowerOf2_32(Scale);
10410   }
10411 }
10412
10413 /// isLegalAddressingMode - Return true if the addressing mode represented
10414 /// by AM is legal for this target, for a load/store of the specified type.
10415 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10416                                               Type *Ty) const {
10417   EVT VT = getValueType(Ty, true);
10418   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10419     return false;
10420
10421   // Can never fold addr of global into load/store.
10422   if (AM.BaseGV)
10423     return false;
10424
10425   switch (AM.Scale) {
10426   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10427     break;
10428   case 1:
10429     if (Subtarget->isThumb1Only())
10430       return false;
10431     // FALL THROUGH.
10432   default:
10433     // ARM doesn't support any R+R*scale+imm addr modes.
10434     if (AM.BaseOffs)
10435       return false;
10436
10437     if (!VT.isSimple())
10438       return false;
10439
10440     if (Subtarget->isThumb2())
10441       return isLegalT2ScaledAddressingMode(AM, VT);
10442
10443     int Scale = AM.Scale;
10444     switch (VT.getSimpleVT().SimpleTy) {
10445     default: return false;
10446     case MVT::i1:
10447     case MVT::i8:
10448     case MVT::i32:
10449       if (Scale < 0) Scale = -Scale;
10450       if (Scale == 1)
10451         return true;
10452       // r + r << imm
10453       return isPowerOf2_32(Scale & ~1);
10454     case MVT::i16:
10455     case MVT::i64:
10456       // r + r
10457       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10458         return true;
10459       return false;
10460
10461     case MVT::isVoid:
10462       // Note, we allow "void" uses (basically, uses that aren't loads or
10463       // stores), because arm allows folding a scale into many arithmetic
10464       // operations.  This should be made more precise and revisited later.
10465
10466       // Allow r << imm, but the imm has to be a multiple of two.
10467       if (Scale & 1) return false;
10468       return isPowerOf2_32(Scale);
10469     }
10470   }
10471   return true;
10472 }
10473
10474 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10475 /// icmp immediate, that is the target has icmp instructions which can compare
10476 /// a register against the immediate without having to materialize the
10477 /// immediate into a register.
10478 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10479   // Thumb2 and ARM modes can use cmn for negative immediates.
10480   if (!Subtarget->isThumb())
10481     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10482   if (Subtarget->isThumb2())
10483     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10484   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10485   return Imm >= 0 && Imm <= 255;
10486 }
10487
10488 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10489 /// *or sub* immediate, that is the target has add or sub instructions which can
10490 /// add a register with the immediate without having to materialize the
10491 /// immediate into a register.
10492 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10493   // Same encoding for add/sub, just flip the sign.
10494   int64_t AbsImm = llvm::abs64(Imm);
10495   if (!Subtarget->isThumb())
10496     return ARM_AM::getSOImmVal(AbsImm) != -1;
10497   if (Subtarget->isThumb2())
10498     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10499   // Thumb1 only has 8-bit unsigned immediate.
10500   return AbsImm >= 0 && AbsImm <= 255;
10501 }
10502
10503 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10504                                       bool isSEXTLoad, SDValue &Base,
10505                                       SDValue &Offset, bool &isInc,
10506                                       SelectionDAG &DAG) {
10507   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10508     return false;
10509
10510   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10511     // AddressingMode 3
10512     Base = Ptr->getOperand(0);
10513     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10514       int RHSC = (int)RHS->getZExtValue();
10515       if (RHSC < 0 && RHSC > -256) {
10516         assert(Ptr->getOpcode() == ISD::ADD);
10517         isInc = false;
10518         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10519         return true;
10520       }
10521     }
10522     isInc = (Ptr->getOpcode() == ISD::ADD);
10523     Offset = Ptr->getOperand(1);
10524     return true;
10525   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10526     // AddressingMode 2
10527     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10528       int RHSC = (int)RHS->getZExtValue();
10529       if (RHSC < 0 && RHSC > -0x1000) {
10530         assert(Ptr->getOpcode() == ISD::ADD);
10531         isInc = false;
10532         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10533         Base = Ptr->getOperand(0);
10534         return true;
10535       }
10536     }
10537
10538     if (Ptr->getOpcode() == ISD::ADD) {
10539       isInc = true;
10540       ARM_AM::ShiftOpc ShOpcVal=
10541         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10542       if (ShOpcVal != ARM_AM::no_shift) {
10543         Base = Ptr->getOperand(1);
10544         Offset = Ptr->getOperand(0);
10545       } else {
10546         Base = Ptr->getOperand(0);
10547         Offset = Ptr->getOperand(1);
10548       }
10549       return true;
10550     }
10551
10552     isInc = (Ptr->getOpcode() == ISD::ADD);
10553     Base = Ptr->getOperand(0);
10554     Offset = Ptr->getOperand(1);
10555     return true;
10556   }
10557
10558   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10559   return false;
10560 }
10561
10562 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10563                                      bool isSEXTLoad, SDValue &Base,
10564                                      SDValue &Offset, bool &isInc,
10565                                      SelectionDAG &DAG) {
10566   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10567     return false;
10568
10569   Base = Ptr->getOperand(0);
10570   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10571     int RHSC = (int)RHS->getZExtValue();
10572     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10573       assert(Ptr->getOpcode() == ISD::ADD);
10574       isInc = false;
10575       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10576       return true;
10577     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10578       isInc = Ptr->getOpcode() == ISD::ADD;
10579       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10580       return true;
10581     }
10582   }
10583
10584   return false;
10585 }
10586
10587 /// getPreIndexedAddressParts - returns true by value, base pointer and
10588 /// offset pointer and addressing mode by reference if the node's address
10589 /// can be legally represented as pre-indexed load / store address.
10590 bool
10591 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10592                                              SDValue &Offset,
10593                                              ISD::MemIndexedMode &AM,
10594                                              SelectionDAG &DAG) const {
10595   if (Subtarget->isThumb1Only())
10596     return false;
10597
10598   EVT VT;
10599   SDValue Ptr;
10600   bool isSEXTLoad = false;
10601   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10602     Ptr = LD->getBasePtr();
10603     VT  = LD->getMemoryVT();
10604     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10605   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10606     Ptr = ST->getBasePtr();
10607     VT  = ST->getMemoryVT();
10608   } else
10609     return false;
10610
10611   bool isInc;
10612   bool isLegal = false;
10613   if (Subtarget->isThumb2())
10614     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10615                                        Offset, isInc, DAG);
10616   else
10617     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10618                                         Offset, isInc, DAG);
10619   if (!isLegal)
10620     return false;
10621
10622   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10623   return true;
10624 }
10625
10626 /// getPostIndexedAddressParts - returns true by value, base pointer and
10627 /// offset pointer and addressing mode by reference if this node can be
10628 /// combined with a load / store to form a post-indexed load / store.
10629 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10630                                                    SDValue &Base,
10631                                                    SDValue &Offset,
10632                                                    ISD::MemIndexedMode &AM,
10633                                                    SelectionDAG &DAG) const {
10634   if (Subtarget->isThumb1Only())
10635     return false;
10636
10637   EVT VT;
10638   SDValue Ptr;
10639   bool isSEXTLoad = false;
10640   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10641     VT  = LD->getMemoryVT();
10642     Ptr = LD->getBasePtr();
10643     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10644   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10645     VT  = ST->getMemoryVT();
10646     Ptr = ST->getBasePtr();
10647   } else
10648     return false;
10649
10650   bool isInc;
10651   bool isLegal = false;
10652   if (Subtarget->isThumb2())
10653     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10654                                        isInc, DAG);
10655   else
10656     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10657                                         isInc, DAG);
10658   if (!isLegal)
10659     return false;
10660
10661   if (Ptr != Base) {
10662     // Swap base ptr and offset to catch more post-index load / store when
10663     // it's legal. In Thumb2 mode, offset must be an immediate.
10664     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10665         !Subtarget->isThumb2())
10666       std::swap(Base, Offset);
10667
10668     // Post-indexed load / store update the base pointer.
10669     if (Ptr != Base)
10670       return false;
10671   }
10672
10673   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10674   return true;
10675 }
10676
10677 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10678                                                        APInt &KnownZero,
10679                                                        APInt &KnownOne,
10680                                                        const SelectionDAG &DAG,
10681                                                        unsigned Depth) const {
10682   unsigned BitWidth = KnownOne.getBitWidth();
10683   KnownZero = KnownOne = APInt(BitWidth, 0);
10684   switch (Op.getOpcode()) {
10685   default: break;
10686   case ARMISD::ADDC:
10687   case ARMISD::ADDE:
10688   case ARMISD::SUBC:
10689   case ARMISD::SUBE:
10690     // These nodes' second result is a boolean
10691     if (Op.getResNo() == 0)
10692       break;
10693     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10694     break;
10695   case ARMISD::CMOV: {
10696     // Bits are known zero/one if known on the LHS and RHS.
10697     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10698     if (KnownZero == 0 && KnownOne == 0) return;
10699
10700     APInt KnownZeroRHS, KnownOneRHS;
10701     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10702     KnownZero &= KnownZeroRHS;
10703     KnownOne  &= KnownOneRHS;
10704     return;
10705   }
10706   }
10707 }
10708
10709 //===----------------------------------------------------------------------===//
10710 //                           ARM Inline Assembly Support
10711 //===----------------------------------------------------------------------===//
10712
10713 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10714   // Looking for "rev" which is V6+.
10715   if (!Subtarget->hasV6Ops())
10716     return false;
10717
10718   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10719   std::string AsmStr = IA->getAsmString();
10720   SmallVector<StringRef, 4> AsmPieces;
10721   SplitString(AsmStr, AsmPieces, ";\n");
10722
10723   switch (AsmPieces.size()) {
10724   default: return false;
10725   case 1:
10726     AsmStr = AsmPieces[0];
10727     AsmPieces.clear();
10728     SplitString(AsmStr, AsmPieces, " \t,");
10729
10730     // rev $0, $1
10731     if (AsmPieces.size() == 3 &&
10732         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10733         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10734       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10735       if (Ty && Ty->getBitWidth() == 32)
10736         return IntrinsicLowering::LowerToByteSwap(CI);
10737     }
10738     break;
10739   }
10740
10741   return false;
10742 }
10743
10744 /// getConstraintType - Given a constraint letter, return the type of
10745 /// constraint it is for this target.
10746 ARMTargetLowering::ConstraintType
10747 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10748   if (Constraint.size() == 1) {
10749     switch (Constraint[0]) {
10750     default:  break;
10751     case 'l': return C_RegisterClass;
10752     case 'w': return C_RegisterClass;
10753     case 'h': return C_RegisterClass;
10754     case 'x': return C_RegisterClass;
10755     case 't': return C_RegisterClass;
10756     case 'j': return C_Other; // Constant for movw.
10757       // An address with a single base register. Due to the way we
10758       // currently handle addresses it is the same as an 'r' memory constraint.
10759     case 'Q': return C_Memory;
10760     }
10761   } else if (Constraint.size() == 2) {
10762     switch (Constraint[0]) {
10763     default: break;
10764     // All 'U+' constraints are addresses.
10765     case 'U': return C_Memory;
10766     }
10767   }
10768   return TargetLowering::getConstraintType(Constraint);
10769 }
10770
10771 /// Examine constraint type and operand type and determine a weight value.
10772 /// This object must already have been set up with the operand type
10773 /// and the current alternative constraint selected.
10774 TargetLowering::ConstraintWeight
10775 ARMTargetLowering::getSingleConstraintMatchWeight(
10776     AsmOperandInfo &info, const char *constraint) const {
10777   ConstraintWeight weight = CW_Invalid;
10778   Value *CallOperandVal = info.CallOperandVal;
10779     // If we don't have a value, we can't do a match,
10780     // but allow it at the lowest weight.
10781   if (CallOperandVal == NULL)
10782     return CW_Default;
10783   Type *type = CallOperandVal->getType();
10784   // Look at the constraint type.
10785   switch (*constraint) {
10786   default:
10787     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10788     break;
10789   case 'l':
10790     if (type->isIntegerTy()) {
10791       if (Subtarget->isThumb())
10792         weight = CW_SpecificReg;
10793       else
10794         weight = CW_Register;
10795     }
10796     break;
10797   case 'w':
10798     if (type->isFloatingPointTy())
10799       weight = CW_Register;
10800     break;
10801   }
10802   return weight;
10803 }
10804
10805 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10806 RCPair
10807 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10808                                                 MVT VT) const {
10809   if (Constraint.size() == 1) {
10810     // GCC ARM Constraint Letters
10811     switch (Constraint[0]) {
10812     case 'l': // Low regs or general regs.
10813       if (Subtarget->isThumb())
10814         return RCPair(0U, &ARM::tGPRRegClass);
10815       return RCPair(0U, &ARM::GPRRegClass);
10816     case 'h': // High regs or no regs.
10817       if (Subtarget->isThumb())
10818         return RCPair(0U, &ARM::hGPRRegClass);
10819       break;
10820     case 'r':
10821       return RCPair(0U, &ARM::GPRRegClass);
10822     case 'w':
10823       if (VT == MVT::Other)
10824         break;
10825       if (VT == MVT::f32)
10826         return RCPair(0U, &ARM::SPRRegClass);
10827       if (VT.getSizeInBits() == 64)
10828         return RCPair(0U, &ARM::DPRRegClass);
10829       if (VT.getSizeInBits() == 128)
10830         return RCPair(0U, &ARM::QPRRegClass);
10831       break;
10832     case 'x':
10833       if (VT == MVT::Other)
10834         break;
10835       if (VT == MVT::f32)
10836         return RCPair(0U, &ARM::SPR_8RegClass);
10837       if (VT.getSizeInBits() == 64)
10838         return RCPair(0U, &ARM::DPR_8RegClass);
10839       if (VT.getSizeInBits() == 128)
10840         return RCPair(0U, &ARM::QPR_8RegClass);
10841       break;
10842     case 't':
10843       if (VT == MVT::f32)
10844         return RCPair(0U, &ARM::SPRRegClass);
10845       break;
10846     }
10847   }
10848   if (StringRef("{cc}").equals_lower(Constraint))
10849     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10850
10851   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10852 }
10853
10854 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10855 /// vector.  If it is invalid, don't add anything to Ops.
10856 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10857                                                      std::string &Constraint,
10858                                                      std::vector<SDValue>&Ops,
10859                                                      SelectionDAG &DAG) const {
10860   SDValue Result(0, 0);
10861
10862   // Currently only support length 1 constraints.
10863   if (Constraint.length() != 1) return;
10864
10865   char ConstraintLetter = Constraint[0];
10866   switch (ConstraintLetter) {
10867   default: break;
10868   case 'j':
10869   case 'I': case 'J': case 'K': case 'L':
10870   case 'M': case 'N': case 'O':
10871     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10872     if (!C)
10873       return;
10874
10875     int64_t CVal64 = C->getSExtValue();
10876     int CVal = (int) CVal64;
10877     // None of these constraints allow values larger than 32 bits.  Check
10878     // that the value fits in an int.
10879     if (CVal != CVal64)
10880       return;
10881
10882     switch (ConstraintLetter) {
10883       case 'j':
10884         // Constant suitable for movw, must be between 0 and
10885         // 65535.
10886         if (Subtarget->hasV6T2Ops())
10887           if (CVal >= 0 && CVal <= 65535)
10888             break;
10889         return;
10890       case 'I':
10891         if (Subtarget->isThumb1Only()) {
10892           // This must be a constant between 0 and 255, for ADD
10893           // immediates.
10894           if (CVal >= 0 && CVal <= 255)
10895             break;
10896         } else if (Subtarget->isThumb2()) {
10897           // A constant that can be used as an immediate value in a
10898           // data-processing instruction.
10899           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10900             break;
10901         } else {
10902           // A constant that can be used as an immediate value in a
10903           // data-processing instruction.
10904           if (ARM_AM::getSOImmVal(CVal) != -1)
10905             break;
10906         }
10907         return;
10908
10909       case 'J':
10910         if (Subtarget->isThumb()) {  // FIXME thumb2
10911           // This must be a constant between -255 and -1, for negated ADD
10912           // immediates. This can be used in GCC with an "n" modifier that
10913           // prints the negated value, for use with SUB instructions. It is
10914           // not useful otherwise but is implemented for compatibility.
10915           if (CVal >= -255 && CVal <= -1)
10916             break;
10917         } else {
10918           // This must be a constant between -4095 and 4095. It is not clear
10919           // what this constraint is intended for. Implemented for
10920           // compatibility with GCC.
10921           if (CVal >= -4095 && CVal <= 4095)
10922             break;
10923         }
10924         return;
10925
10926       case 'K':
10927         if (Subtarget->isThumb1Only()) {
10928           // A 32-bit value where only one byte has a nonzero value. Exclude
10929           // zero to match GCC. This constraint is used by GCC internally for
10930           // constants that can be loaded with a move/shift combination.
10931           // It is not useful otherwise but is implemented for compatibility.
10932           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10933             break;
10934         } else if (Subtarget->isThumb2()) {
10935           // A constant whose bitwise inverse can be used as an immediate
10936           // value in a data-processing instruction. This can be used in GCC
10937           // with a "B" modifier that prints the inverted value, for use with
10938           // BIC and MVN instructions. It is not useful otherwise but is
10939           // implemented for compatibility.
10940           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10941             break;
10942         } else {
10943           // A constant whose bitwise inverse can be used as an immediate
10944           // value in a data-processing instruction. This can be used in GCC
10945           // with a "B" modifier that prints the inverted value, for use with
10946           // BIC and MVN instructions. It is not useful otherwise but is
10947           // implemented for compatibility.
10948           if (ARM_AM::getSOImmVal(~CVal) != -1)
10949             break;
10950         }
10951         return;
10952
10953       case 'L':
10954         if (Subtarget->isThumb1Only()) {
10955           // This must be a constant between -7 and 7,
10956           // for 3-operand ADD/SUB immediate instructions.
10957           if (CVal >= -7 && CVal < 7)
10958             break;
10959         } else if (Subtarget->isThumb2()) {
10960           // A constant whose negation can be used as an immediate value in a
10961           // data-processing instruction. This can be used in GCC with an "n"
10962           // modifier that prints the negated value, for use with SUB
10963           // instructions. It is not useful otherwise but is implemented for
10964           // compatibility.
10965           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10966             break;
10967         } else {
10968           // A constant whose negation can be used as an immediate value in a
10969           // data-processing instruction. This can be used in GCC with an "n"
10970           // modifier that prints the negated value, for use with SUB
10971           // instructions. It is not useful otherwise but is implemented for
10972           // compatibility.
10973           if (ARM_AM::getSOImmVal(-CVal) != -1)
10974             break;
10975         }
10976         return;
10977
10978       case 'M':
10979         if (Subtarget->isThumb()) { // FIXME thumb2
10980           // This must be a multiple of 4 between 0 and 1020, for
10981           // ADD sp + immediate.
10982           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10983             break;
10984         } else {
10985           // A power of two or a constant between 0 and 32.  This is used in
10986           // GCC for the shift amount on shifted register operands, but it is
10987           // useful in general for any shift amounts.
10988           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10989             break;
10990         }
10991         return;
10992
10993       case 'N':
10994         if (Subtarget->isThumb()) {  // FIXME thumb2
10995           // This must be a constant between 0 and 31, for shift amounts.
10996           if (CVal >= 0 && CVal <= 31)
10997             break;
10998         }
10999         return;
11000
11001       case 'O':
11002         if (Subtarget->isThumb()) {  // FIXME thumb2
11003           // This must be a multiple of 4 between -508 and 508, for
11004           // ADD/SUB sp = sp + immediate.
11005           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11006             break;
11007         }
11008         return;
11009     }
11010     Result = DAG.getTargetConstant(CVal, Op.getValueType());
11011     break;
11012   }
11013
11014   if (Result.getNode()) {
11015     Ops.push_back(Result);
11016     return;
11017   }
11018   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11019 }
11020
11021 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11022   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
11023   unsigned Opcode = Op->getOpcode();
11024   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11025       "Invalid opcode for Div/Rem lowering");
11026   bool isSigned = (Opcode == ISD::SDIVREM);
11027   EVT VT = Op->getValueType(0);
11028   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11029
11030   RTLIB::Libcall LC;
11031   switch (VT.getSimpleVT().SimpleTy) {
11032   default: llvm_unreachable("Unexpected request for libcall!");
11033   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
11034   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11035   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11036   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11037   }
11038
11039   SDValue InChain = DAG.getEntryNode();
11040
11041   TargetLowering::ArgListTy Args;
11042   TargetLowering::ArgListEntry Entry;
11043   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
11044     EVT ArgVT = Op->getOperand(i).getValueType();
11045     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11046     Entry.Node = Op->getOperand(i);
11047     Entry.Ty = ArgTy;
11048     Entry.isSExt = isSigned;
11049     Entry.isZExt = !isSigned;
11050     Args.push_back(Entry);
11051   }
11052
11053   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11054                                          getPointerTy());
11055
11056   Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
11057
11058   SDLoc dl(Op);
11059   TargetLowering::
11060   CallLoweringInfo CLI(InChain, RetTy, isSigned, !isSigned, false, true,
11061                     0, getLibcallCallingConv(LC), /*isTailCall=*/false,
11062                     /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
11063                     Callee, Args, DAG, dl);
11064   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11065
11066   return CallInfo.first;
11067 }
11068
11069 bool
11070 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11071   // The ARM target isn't yet aware of offsets.
11072   return false;
11073 }
11074
11075 bool ARM::isBitFieldInvertedMask(unsigned v) {
11076   if (v == 0xffffffff)
11077     return false;
11078
11079   // there can be 1's on either or both "outsides", all the "inside"
11080   // bits must be 0's
11081   unsigned TO = CountTrailingOnes_32(v);
11082   unsigned LO = CountLeadingOnes_32(v);
11083   v = (v >> TO) << TO;
11084   v = (v << LO) >> LO;
11085   return v == 0;
11086 }
11087
11088 /// isFPImmLegal - Returns true if the target can instruction select the
11089 /// specified FP immediate natively. If false, the legalizer will
11090 /// materialize the FP immediate as a load from a constant pool.
11091 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11092   if (!Subtarget->hasVFP3())
11093     return false;
11094   if (VT == MVT::f32)
11095     return ARM_AM::getFP32Imm(Imm) != -1;
11096   if (VT == MVT::f64)
11097     return ARM_AM::getFP64Imm(Imm) != -1;
11098   return false;
11099 }
11100
11101 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11102 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11103 /// specified in the intrinsic calls.
11104 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11105                                            const CallInst &I,
11106                                            unsigned Intrinsic) const {
11107   switch (Intrinsic) {
11108   case Intrinsic::arm_neon_vld1:
11109   case Intrinsic::arm_neon_vld2:
11110   case Intrinsic::arm_neon_vld3:
11111   case Intrinsic::arm_neon_vld4:
11112   case Intrinsic::arm_neon_vld2lane:
11113   case Intrinsic::arm_neon_vld3lane:
11114   case Intrinsic::arm_neon_vld4lane: {
11115     Info.opc = ISD::INTRINSIC_W_CHAIN;
11116     // Conservatively set memVT to the entire set of vectors loaded.
11117     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
11118     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11119     Info.ptrVal = I.getArgOperand(0);
11120     Info.offset = 0;
11121     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11122     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11123     Info.vol = false; // volatile loads with NEON intrinsics not supported
11124     Info.readMem = true;
11125     Info.writeMem = false;
11126     return true;
11127   }
11128   case Intrinsic::arm_neon_vst1:
11129   case Intrinsic::arm_neon_vst2:
11130   case Intrinsic::arm_neon_vst3:
11131   case Intrinsic::arm_neon_vst4:
11132   case Intrinsic::arm_neon_vst2lane:
11133   case Intrinsic::arm_neon_vst3lane:
11134   case Intrinsic::arm_neon_vst4lane: {
11135     Info.opc = ISD::INTRINSIC_VOID;
11136     // Conservatively set memVT to the entire set of vectors stored.
11137     unsigned NumElts = 0;
11138     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11139       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11140       if (!ArgTy->isVectorTy())
11141         break;
11142       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
11143     }
11144     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11145     Info.ptrVal = I.getArgOperand(0);
11146     Info.offset = 0;
11147     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11148     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11149     Info.vol = false; // volatile stores with NEON intrinsics not supported
11150     Info.readMem = false;
11151     Info.writeMem = true;
11152     return true;
11153   }
11154   case Intrinsic::arm_ldrex: {
11155     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11156     Info.opc = ISD::INTRINSIC_W_CHAIN;
11157     Info.memVT = MVT::getVT(PtrTy->getElementType());
11158     Info.ptrVal = I.getArgOperand(0);
11159     Info.offset = 0;
11160     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11161     Info.vol = true;
11162     Info.readMem = true;
11163     Info.writeMem = false;
11164     return true;
11165   }
11166   case Intrinsic::arm_strex: {
11167     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11168     Info.opc = ISD::INTRINSIC_W_CHAIN;
11169     Info.memVT = MVT::getVT(PtrTy->getElementType());
11170     Info.ptrVal = I.getArgOperand(1);
11171     Info.offset = 0;
11172     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11173     Info.vol = true;
11174     Info.readMem = false;
11175     Info.writeMem = true;
11176     return true;
11177   }
11178   case Intrinsic::arm_strexd: {
11179     Info.opc = ISD::INTRINSIC_W_CHAIN;
11180     Info.memVT = MVT::i64;
11181     Info.ptrVal = I.getArgOperand(2);
11182     Info.offset = 0;
11183     Info.align = 8;
11184     Info.vol = true;
11185     Info.readMem = false;
11186     Info.writeMem = true;
11187     return true;
11188   }
11189   case Intrinsic::arm_ldrexd: {
11190     Info.opc = ISD::INTRINSIC_W_CHAIN;
11191     Info.memVT = MVT::i64;
11192     Info.ptrVal = I.getArgOperand(0);
11193     Info.offset = 0;
11194     Info.align = 8;
11195     Info.vol = true;
11196     Info.readMem = true;
11197     Info.writeMem = false;
11198     return true;
11199   }
11200   default:
11201     break;
11202   }
11203
11204   return false;
11205 }