a2c6f0c3950884fca930ef5d0ae80c4c05ccb8fe
[oota-llvm.git] / lib / Target / ARM / ARMISelLowering.cpp
1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "arm-isel"
16 #include "ARMISelLowering.h"
17 #include "ARM.h"
18 #include "ARMCallingConv.h"
19 #include "ARMConstantPoolValue.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "ARMPerfectShuffle.h"
22 #include "ARMSubtarget.h"
23 #include "ARMTargetMachine.h"
24 #include "ARMTargetObjectFile.h"
25 #include "MCTargetDesc/ARMAddressingModes.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/IntrinsicLowering.h"
30 #include "llvm/CodeGen/MachineBasicBlock.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalValue.h"
41 #include "llvm/IR/Instruction.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/IR/Type.h"
45 #include "llvm/MC/MCSectionMachO.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/Target/TargetOptions.h"
51 using namespace llvm;
52
53 STATISTIC(NumTailCalls, "Number of tail calls");
54 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
55 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
56
57 // This option should go away when tail calls fully work.
58 static cl::opt<bool>
59 EnableARMTailCalls("arm-tail-calls", cl::Hidden,
60   cl::desc("Generate tail calls (TEMPORARY OPTION)."),
61   cl::init(false));
62
63 cl::opt<bool>
64 EnableARMLongCalls("arm-long-calls", cl::Hidden,
65   cl::desc("Generate calls via indirect call instructions"),
66   cl::init(false));
67
68 static cl::opt<bool>
69 ARMInterworking("arm-interworking", cl::Hidden,
70   cl::desc("Enable / disable ARM interworking (for debugging only)"),
71   cl::init(true));
72
73 namespace {
74   class ARMCCState : public CCState {
75   public:
76     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
77                const TargetMachine &TM, SmallVectorImpl<CCValAssign> &locs,
78                LLVMContext &C, ParmContext PC)
79         : CCState(CC, isVarArg, MF, TM, locs, C) {
80       assert(((PC == Call) || (PC == Prologue)) &&
81              "ARMCCState users must specify whether their context is call"
82              "or prologue generation.");
83       CallOrPrologue = PC;
84     }
85   };
86 }
87
88 // The APCS parameter registers.
89 static const uint16_t GPRArgRegs[] = {
90   ARM::R0, ARM::R1, ARM::R2, ARM::R3
91 };
92
93 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
94                                        MVT PromotedBitwiseVT) {
95   if (VT != PromotedLdStVT) {
96     setOperationAction(ISD::LOAD, VT, Promote);
97     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
98
99     setOperationAction(ISD::STORE, VT, Promote);
100     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
101   }
102
103   MVT ElemTy = VT.getVectorElementType();
104   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
105     setOperationAction(ISD::SETCC, VT, Custom);
106   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
107   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
108   if (ElemTy == MVT::i32) {
109     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
110     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
111     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
112     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
113   } else {
114     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
115     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
116     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
117     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
118   }
119   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
120   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
121   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
122   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
123   setOperationAction(ISD::SELECT,            VT, Expand);
124   setOperationAction(ISD::SELECT_CC,         VT, Expand);
125   setOperationAction(ISD::VSELECT,           VT, Expand);
126   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
127   if (VT.isInteger()) {
128     setOperationAction(ISD::SHL, VT, Custom);
129     setOperationAction(ISD::SRA, VT, Custom);
130     setOperationAction(ISD::SRL, VT, Custom);
131   }
132
133   // Promote all bit-wise operations.
134   if (VT.isInteger() && VT != PromotedBitwiseVT) {
135     setOperationAction(ISD::AND, VT, Promote);
136     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
137     setOperationAction(ISD::OR,  VT, Promote);
138     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
139     setOperationAction(ISD::XOR, VT, Promote);
140     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
141   }
142
143   // Neon does not support vector divide/remainder operations.
144   setOperationAction(ISD::SDIV, VT, Expand);
145   setOperationAction(ISD::UDIV, VT, Expand);
146   setOperationAction(ISD::FDIV, VT, Expand);
147   setOperationAction(ISD::SREM, VT, Expand);
148   setOperationAction(ISD::UREM, VT, Expand);
149   setOperationAction(ISD::FREM, VT, Expand);
150 }
151
152 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
153   addRegisterClass(VT, &ARM::DPRRegClass);
154   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
155 }
156
157 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
158   addRegisterClass(VT, &ARM::QPRRegClass);
159   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
160 }
161
162 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
163   if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
164     return new TargetLoweringObjectFileMachO();
165
166   return new ARMElfTargetObjectFile();
167 }
168
169 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
170     : TargetLowering(TM, createTLOF(TM)) {
171   Subtarget = &TM.getSubtarget<ARMSubtarget>();
172   RegInfo = TM.getRegisterInfo();
173   Itins = TM.getInstrItineraryData();
174
175   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
176
177   if (Subtarget->isTargetDarwin()) {
178     // Uses VFP for Thumb libfuncs if available.
179     if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
180       // Single-precision floating-point arithmetic.
181       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
182       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
183       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
184       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
185
186       // Double-precision floating-point arithmetic.
187       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
188       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
189       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
190       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
191
192       // Single-precision comparisons.
193       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
194       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
195       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
196       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
197       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
198       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
199       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
200       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
201
202       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
203       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
204       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
205       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
206       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
207       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
208       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
209       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
210
211       // Double-precision comparisons.
212       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
213       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
214       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
215       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
216       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
217       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
218       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
219       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
220
221       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
222       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
223       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
224       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
225       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
226       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
227       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
228       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
229
230       // Floating-point to integer conversions.
231       // i64 conversions are done via library routines even when generating VFP
232       // instructions, so use the same ones.
233       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
234       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
235       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
236       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
237
238       // Conversions between floating types.
239       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
240       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
241
242       // Integer to floating-point conversions.
243       // i64 conversions are done via library routines even when generating VFP
244       // instructions, so use the same ones.
245       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
246       // e.g., __floatunsidf vs. __floatunssidfvfp.
247       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
248       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
249       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
250       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
251     }
252   }
253
254   // These libcalls are not available in 32-bit.
255   setLibcallName(RTLIB::SHL_I128, 0);
256   setLibcallName(RTLIB::SRL_I128, 0);
257   setLibcallName(RTLIB::SRA_I128, 0);
258
259   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetDarwin()) {
260     // Double-precision floating-point arithmetic helper functions
261     // RTABI chapter 4.1.2, Table 2
262     setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
263     setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
264     setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
265     setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
266     setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
267     setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
268     setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
269     setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
270
271     // Double-precision floating-point comparison helper functions
272     // RTABI chapter 4.1.2, Table 3
273     setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
274     setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
275     setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
276     setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
277     setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
278     setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
279     setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
280     setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
281     setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
282     setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
283     setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
284     setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
285     setLibcallName(RTLIB::UO_F64,  "__aeabi_dcmpun");
286     setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
287     setLibcallName(RTLIB::O_F64,   "__aeabi_dcmpun");
288     setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
289     setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
290     setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
291     setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
292     setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
293     setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
294     setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
295     setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
296     setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
297
298     // Single-precision floating-point arithmetic helper functions
299     // RTABI chapter 4.1.2, Table 4
300     setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
301     setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
302     setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
303     setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
304     setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
305     setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
306     setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
307     setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
308
309     // Single-precision floating-point comparison helper functions
310     // RTABI chapter 4.1.2, Table 5
311     setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
312     setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
313     setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
314     setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
315     setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
316     setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
317     setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
318     setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
319     setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
320     setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
321     setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
322     setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
323     setLibcallName(RTLIB::UO_F32,  "__aeabi_fcmpun");
324     setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
325     setLibcallName(RTLIB::O_F32,   "__aeabi_fcmpun");
326     setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
327     setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
328     setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
329     setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
330     setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
331     setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
332     setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
333     setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
334     setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
335
336     // Floating-point to integer conversions.
337     // RTABI chapter 4.1.2, Table 6
338     setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
339     setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
340     setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
341     setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
342     setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
343     setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
344     setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
345     setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
346     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
347     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
348     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
349     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
350     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
351     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
352     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
353     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
354
355     // Conversions between floating types.
356     // RTABI chapter 4.1.2, Table 7
357     setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
358     setLibcallName(RTLIB::FPEXT_F32_F64,   "__aeabi_f2d");
359     setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
360     setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
361
362     // Integer to floating-point conversions.
363     // RTABI chapter 4.1.2, Table 8
364     setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
365     setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
366     setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
367     setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
368     setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
369     setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
370     setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
371     setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
372     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
373     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
374     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
375     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
376     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
377     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
378     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
379     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
380
381     // Long long helper functions
382     // RTABI chapter 4.2, Table 9
383     setLibcallName(RTLIB::MUL_I64,  "__aeabi_lmul");
384     setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
385     setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
386     setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
387     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
388     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
389     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
390     setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
391     setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
392     setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
393
394     // Integer division functions
395     // RTABI chapter 4.3.1
396     setLibcallName(RTLIB::SDIV_I8,  "__aeabi_idiv");
397     setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
398     setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
399     setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
400     setLibcallName(RTLIB::UDIV_I8,  "__aeabi_uidiv");
401     setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
402     setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
403     setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
404     setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
405     setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
406     setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
407     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
408     setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
409     setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
410     setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
411     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
412
413     // Memory operations
414     // RTABI chapter 4.3.4
415     setLibcallName(RTLIB::MEMCPY,  "__aeabi_memcpy");
416     setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
417     setLibcallName(RTLIB::MEMSET,  "__aeabi_memset");
418     setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
419     setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
420     setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
421   }
422
423   // Use divmod compiler-rt calls for iOS 5.0 and later.
424   if (Subtarget->getTargetTriple().isiOS() &&
425       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
426     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
427     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
428   }
429
430   if (Subtarget->isThumb1Only())
431     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
432   else
433     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
434   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
435       !Subtarget->isThumb1Only()) {
436     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
437     if (!Subtarget->isFPOnlySP())
438       addRegisterClass(MVT::f64, &ARM::DPRRegClass);
439
440     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
441   }
442
443   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
444        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
445     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
446          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
447       setTruncStoreAction((MVT::SimpleValueType)VT,
448                           (MVT::SimpleValueType)InnerVT, Expand);
449     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
450     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
451     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
452   }
453
454   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
455   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
456
457   if (Subtarget->hasNEON()) {
458     addDRTypeForNEON(MVT::v2f32);
459     addDRTypeForNEON(MVT::v8i8);
460     addDRTypeForNEON(MVT::v4i16);
461     addDRTypeForNEON(MVT::v2i32);
462     addDRTypeForNEON(MVT::v1i64);
463
464     addQRTypeForNEON(MVT::v4f32);
465     addQRTypeForNEON(MVT::v2f64);
466     addQRTypeForNEON(MVT::v16i8);
467     addQRTypeForNEON(MVT::v8i16);
468     addQRTypeForNEON(MVT::v4i32);
469     addQRTypeForNEON(MVT::v2i64);
470
471     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
472     // neither Neon nor VFP support any arithmetic operations on it.
473     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
474     // supported for v4f32.
475     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
476     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
477     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
478     // FIXME: Code duplication: FDIV and FREM are expanded always, see
479     // ARMTargetLowering::addTypeForNEON method for details.
480     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
481     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
482     // FIXME: Create unittest.
483     // In another words, find a way when "copysign" appears in DAG with vector
484     // operands.
485     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
486     // FIXME: Code duplication: SETCC has custom operation action, see
487     // ARMTargetLowering::addTypeForNEON method for details.
488     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
489     // FIXME: Create unittest for FNEG and for FABS.
490     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
491     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
492     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
493     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
494     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
495     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
496     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
497     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
498     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
499     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
500     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
501     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
502     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
503     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
504     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
505     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
506     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
507     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
508     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
509
510     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
511     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
512     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
513     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
514     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
515     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
516     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
517     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
518     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
519     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
520     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
521     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
522     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
523     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
524     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
525
526     // Mark v2f32 intrinsics.
527     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
528     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
529     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
530     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
531     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
532     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
533     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
534     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
535     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
536     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
537     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
538     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
539     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
540     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
541     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
542
543     // Neon does not support some operations on v1i64 and v2i64 types.
544     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
545     // Custom handling for some quad-vector types to detect VMULL.
546     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
547     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
548     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
549     // Custom handling for some vector types to avoid expensive expansions
550     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
551     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
552     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
553     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
554     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
555     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
556     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
557     // a destination type that is wider than the source, and nor does
558     // it have a FP_TO_[SU]INT instruction with a narrower destination than
559     // source.
560     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
561     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
562     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
563     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
564
565     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
566     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
567
568     // Custom expand long extensions to vectors.
569     setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32,  Custom);
570     setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32,  Custom);
571     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64,  Custom);
572     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64,  Custom);
573     setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
574     setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
575     setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64,  Custom);
576     setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64,  Custom);
577
578     // NEON does not have single instruction CTPOP for vectors with element
579     // types wider than 8-bits.  However, custom lowering can leverage the
580     // v8i8/v16i8 vcnt instruction.
581     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
582     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
583     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
584     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
585
586     // NEON only has FMA instructions as of VFP4.
587     if (!Subtarget->hasVFP4()) {
588       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
589       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
590     }
591
592     setTargetDAGCombine(ISD::INTRINSIC_VOID);
593     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
594     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
595     setTargetDAGCombine(ISD::SHL);
596     setTargetDAGCombine(ISD::SRL);
597     setTargetDAGCombine(ISD::SRA);
598     setTargetDAGCombine(ISD::SIGN_EXTEND);
599     setTargetDAGCombine(ISD::ZERO_EXTEND);
600     setTargetDAGCombine(ISD::ANY_EXTEND);
601     setTargetDAGCombine(ISD::SELECT_CC);
602     setTargetDAGCombine(ISD::BUILD_VECTOR);
603     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
604     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
605     setTargetDAGCombine(ISD::STORE);
606     setTargetDAGCombine(ISD::FP_TO_SINT);
607     setTargetDAGCombine(ISD::FP_TO_UINT);
608     setTargetDAGCombine(ISD::FDIV);
609
610     // It is legal to extload from v4i8 to v4i16 or v4i32.
611     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
612                   MVT::v4i16, MVT::v2i16,
613                   MVT::v2i32};
614     for (unsigned i = 0; i < 6; ++i) {
615       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
616       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
617       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
618     }
619   }
620
621   // ARM and Thumb2 support UMLAL/SMLAL.
622   if (!Subtarget->isThumb1Only())
623     setTargetDAGCombine(ISD::ADDC);
624
625
626   computeRegisterProperties();
627
628   // ARM does not have f32 extending load.
629   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
630
631   // ARM does not have i1 sign extending load.
632   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
633
634   // ARM supports all 4 flavors of integer indexed load / store.
635   if (!Subtarget->isThumb1Only()) {
636     for (unsigned im = (unsigned)ISD::PRE_INC;
637          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
638       setIndexedLoadAction(im,  MVT::i1,  Legal);
639       setIndexedLoadAction(im,  MVT::i8,  Legal);
640       setIndexedLoadAction(im,  MVT::i16, Legal);
641       setIndexedLoadAction(im,  MVT::i32, Legal);
642       setIndexedStoreAction(im, MVT::i1,  Legal);
643       setIndexedStoreAction(im, MVT::i8,  Legal);
644       setIndexedStoreAction(im, MVT::i16, Legal);
645       setIndexedStoreAction(im, MVT::i32, Legal);
646     }
647   }
648
649   // i64 operation support.
650   setOperationAction(ISD::MUL,     MVT::i64, Expand);
651   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
652   if (Subtarget->isThumb1Only()) {
653     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
654     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
655   }
656   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
657       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
658     setOperationAction(ISD::MULHS, MVT::i32, Expand);
659
660   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
661   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
662   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
663   setOperationAction(ISD::SRL,       MVT::i64, Custom);
664   setOperationAction(ISD::SRA,       MVT::i64, Custom);
665
666   if (!Subtarget->isThumb1Only()) {
667     // FIXME: We should do this for Thumb1 as well.
668     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
669     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
670     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
671     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
672   }
673
674   // ARM does not have ROTL.
675   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
676   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
677   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
678   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
679     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
680
681   // These just redirect to CTTZ and CTLZ on ARM.
682   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
683   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
684
685   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
686
687   // Only ARMv6 has BSWAP.
688   if (!Subtarget->hasV6Ops())
689     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
690
691   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
692       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
693     // These are expanded into libcalls if the cpu doesn't have HW divider.
694     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
695     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
696   }
697
698   // FIXME: Also set divmod for SREM on EABI
699   setOperationAction(ISD::SREM,  MVT::i32, Expand);
700   setOperationAction(ISD::UREM,  MVT::i32, Expand);
701   // Register based DivRem for AEABI (RTABI 4.2)
702   if (Subtarget->isTargetAEABI()) {
703     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
704     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
705     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
706     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
707     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
708     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
709     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
710     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
711
712     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
713     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
714     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
715     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
716     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
717     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
718     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
719     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
720
721     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
722     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
723   } else {
724     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
725     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
726   }
727
728   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
729   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
730   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
731   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
732   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
733
734   setOperationAction(ISD::TRAP, MVT::Other, Legal);
735
736   // Use the default implementation.
737   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
738   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
739   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
740   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
741   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
742   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
743
744   if (!Subtarget->isTargetDarwin()) {
745     // Non-Darwin platforms may return values in these registers via the
746     // personality function.
747     setExceptionPointerRegister(ARM::R0);
748     setExceptionSelectorRegister(ARM::R1);
749   }
750
751   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
752   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
753   // the default expansion.
754   // FIXME: This should be checking for v6k, not just v6.
755   if (Subtarget->hasDataBarrier() ||
756       (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
757     // membarrier needs custom lowering; the rest are legal and handled
758     // normally.
759     setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
760     // Custom lowering for 64-bit ops
761     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i64, Custom);
762     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i64, Custom);
763     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i64, Custom);
764     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i64, Custom);
765     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i64, Custom);
766     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i64, Custom);
767     setOperationAction(ISD::ATOMIC_LOAD_MIN,  MVT::i64, Custom);
768     setOperationAction(ISD::ATOMIC_LOAD_MAX,  MVT::i64, Custom);
769     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
770     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
771     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
772     // On v8, we have particularly efficient implementations of atomic fences
773     // if they can be combined with nearby atomic loads and stores.
774     if (!Subtarget->hasV8Ops()) {
775       // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
776       setInsertFencesForAtomic(true);
777     }
778     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
779     //setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Custom);
780   } else {
781     // Set them all for expansion, which will force libcalls.
782     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
783     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
784     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
785     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
786     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
787     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
788     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
789     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
790     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
791     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
792     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
793     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
794     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
795     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
796     // Unordered/Monotonic case.
797     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
798     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
799   }
800
801   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
802
803   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
804   if (!Subtarget->hasV6Ops()) {
805     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
806     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
807   }
808   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
809
810   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
811       !Subtarget->isThumb1Only()) {
812     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
813     // iff target supports vfp2.
814     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
815     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
816   }
817
818   // We want to custom lower some of our intrinsics.
819   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
820   if (Subtarget->isTargetDarwin()) {
821     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
822     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
823     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
824   }
825
826   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
827   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
828   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
829   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
830   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
831   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
832   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
833   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
834   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
835
836   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
837   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
838   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
839   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
840   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
841
842   // We don't support sin/cos/fmod/copysign/pow
843   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
844   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
845   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
846   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
847   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
848   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
849   setOperationAction(ISD::FREM,      MVT::f64, Expand);
850   setOperationAction(ISD::FREM,      MVT::f32, Expand);
851   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
852       !Subtarget->isThumb1Only()) {
853     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
854     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
855   }
856   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
857   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
858
859   if (!Subtarget->hasVFP4()) {
860     setOperationAction(ISD::FMA, MVT::f64, Expand);
861     setOperationAction(ISD::FMA, MVT::f32, Expand);
862   }
863
864   // Various VFP goodness
865   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
866     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
867     if (Subtarget->hasVFP2()) {
868       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
869       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
870       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
871       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
872     }
873     // Special handling for half-precision FP.
874     if (!Subtarget->hasFP16()) {
875       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
876       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
877     }
878   }
879
880   // We have target-specific dag combine patterns for the following nodes:
881   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
882   setTargetDAGCombine(ISD::ADD);
883   setTargetDAGCombine(ISD::SUB);
884   setTargetDAGCombine(ISD::MUL);
885   setTargetDAGCombine(ISD::AND);
886   setTargetDAGCombine(ISD::OR);
887   setTargetDAGCombine(ISD::XOR);
888
889   if (Subtarget->hasV6Ops())
890     setTargetDAGCombine(ISD::SRL);
891
892   setStackPointerRegisterToSaveRestore(ARM::SP);
893
894   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
895       !Subtarget->hasVFP2())
896     setSchedulingPreference(Sched::RegPressure);
897   else
898     setSchedulingPreference(Sched::Hybrid);
899
900   //// temporary - rewrite interface to use type
901   MaxStoresPerMemset = 8;
902   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
903   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
904   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
905   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
906   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
907
908   // On ARM arguments smaller than 4 bytes are extended, so all arguments
909   // are at least 4 bytes aligned.
910   setMinStackArgumentAlignment(4);
911
912   // Prefer likely predicted branches to selects on out-of-order cores.
913   PredictableSelectIsExpensive = Subtarget->isLikeA9();
914
915   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
916 }
917
918 static void getExclusiveOperation(unsigned Size, AtomicOrdering Ord,
919                                   bool isThumb2, unsigned &LdrOpc,
920                                   unsigned &StrOpc) {
921   static const unsigned LoadBares[4][2] =  {{ARM::LDREXB, ARM::t2LDREXB},
922                                             {ARM::LDREXH, ARM::t2LDREXH},
923                                             {ARM::LDREX,  ARM::t2LDREX},
924                                             {ARM::LDREXD, ARM::t2LDREXD}};
925   static const unsigned LoadAcqs[4][2] =   {{ARM::LDAEXB, ARM::t2LDAEXB},
926                                             {ARM::LDAEXH, ARM::t2LDAEXH},
927                                             {ARM::LDAEX,  ARM::t2LDAEX},
928                                             {ARM::LDAEXD, ARM::t2LDAEXD}};
929   static const unsigned StoreBares[4][2] = {{ARM::STREXB, ARM::t2STREXB},
930                                             {ARM::STREXH, ARM::t2STREXH},
931                                             {ARM::STREX,  ARM::t2STREX},
932                                             {ARM::STREXD, ARM::t2STREXD}};
933   static const unsigned StoreRels[4][2] =  {{ARM::STLEXB, ARM::t2STLEXB},
934                                             {ARM::STLEXH, ARM::t2STLEXH},
935                                             {ARM::STLEX,  ARM::t2STLEX},
936                                             {ARM::STLEXD, ARM::t2STLEXD}};
937
938   const unsigned (*LoadOps)[2], (*StoreOps)[2];
939   if (Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent)
940     LoadOps = LoadAcqs;
941   else
942     LoadOps = LoadBares;
943
944   if (Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent)
945     StoreOps = StoreRels;
946   else
947     StoreOps = StoreBares;
948
949   assert(isPowerOf2_32(Size) && Size <= 8 &&
950          "unsupported size for atomic binary op!");
951
952   LdrOpc = LoadOps[Log2_32(Size)][isThumb2];
953   StrOpc = StoreOps[Log2_32(Size)][isThumb2];
954 }
955
956 // FIXME: It might make sense to define the representative register class as the
957 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
958 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
959 // SPR's representative would be DPR_VFP2. This should work well if register
960 // pressure tracking were modified such that a register use would increment the
961 // pressure of the register class's representative and all of it's super
962 // classes' representatives transitively. We have not implemented this because
963 // of the difficulty prior to coalescing of modeling operand register classes
964 // due to the common occurrence of cross class copies and subregister insertions
965 // and extractions.
966 std::pair<const TargetRegisterClass*, uint8_t>
967 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
968   const TargetRegisterClass *RRC = 0;
969   uint8_t Cost = 1;
970   switch (VT.SimpleTy) {
971   default:
972     return TargetLowering::findRepresentativeClass(VT);
973   // Use DPR as representative register class for all floating point
974   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
975   // the cost is 1 for both f32 and f64.
976   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
977   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
978     RRC = &ARM::DPRRegClass;
979     // When NEON is used for SP, only half of the register file is available
980     // because operations that define both SP and DP results will be constrained
981     // to the VFP2 class (D0-D15). We currently model this constraint prior to
982     // coalescing by double-counting the SP regs. See the FIXME above.
983     if (Subtarget->useNEONForSinglePrecisionFP())
984       Cost = 2;
985     break;
986   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
987   case MVT::v4f32: case MVT::v2f64:
988     RRC = &ARM::DPRRegClass;
989     Cost = 2;
990     break;
991   case MVT::v4i64:
992     RRC = &ARM::DPRRegClass;
993     Cost = 4;
994     break;
995   case MVT::v8i64:
996     RRC = &ARM::DPRRegClass;
997     Cost = 8;
998     break;
999   }
1000   return std::make_pair(RRC, Cost);
1001 }
1002
1003 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1004   switch (Opcode) {
1005   default: return 0;
1006   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1007   case ARMISD::WrapperDYN:    return "ARMISD::WrapperDYN";
1008   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1009   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1010   case ARMISD::CALL:          return "ARMISD::CALL";
1011   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1012   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1013   case ARMISD::tCALL:         return "ARMISD::tCALL";
1014   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1015   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1016   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1017   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1018   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1019   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1020   case ARMISD::CMP:           return "ARMISD::CMP";
1021   case ARMISD::CMN:           return "ARMISD::CMN";
1022   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1023   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1024   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1025   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1026   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1027
1028   case ARMISD::CMOV:          return "ARMISD::CMOV";
1029
1030   case ARMISD::RBIT:          return "ARMISD::RBIT";
1031
1032   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
1033   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
1034   case ARMISD::SITOF:         return "ARMISD::SITOF";
1035   case ARMISD::UITOF:         return "ARMISD::UITOF";
1036
1037   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1038   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1039   case ARMISD::RRX:           return "ARMISD::RRX";
1040
1041   case ARMISD::ADDC:          return "ARMISD::ADDC";
1042   case ARMISD::ADDE:          return "ARMISD::ADDE";
1043   case ARMISD::SUBC:          return "ARMISD::SUBC";
1044   case ARMISD::SUBE:          return "ARMISD::SUBE";
1045
1046   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1047   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1048
1049   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1050   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1051
1052   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1053
1054   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1055
1056   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1057
1058   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1059
1060   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1061
1062   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1063   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1064   case ARMISD::VCGE:          return "ARMISD::VCGE";
1065   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1066   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1067   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1068   case ARMISD::VCGT:          return "ARMISD::VCGT";
1069   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1070   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1071   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1072   case ARMISD::VTST:          return "ARMISD::VTST";
1073
1074   case ARMISD::VSHL:          return "ARMISD::VSHL";
1075   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1076   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1077   case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
1078   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
1079   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
1080   case ARMISD::VSHRN:         return "ARMISD::VSHRN";
1081   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1082   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1083   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1084   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1085   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1086   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1087   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1088   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1089   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1090   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1091   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1092   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1093   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1094   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1095   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1096   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1097   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1098   case ARMISD::VDUP:          return "ARMISD::VDUP";
1099   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1100   case ARMISD::VEXT:          return "ARMISD::VEXT";
1101   case ARMISD::VREV64:        return "ARMISD::VREV64";
1102   case ARMISD::VREV32:        return "ARMISD::VREV32";
1103   case ARMISD::VREV16:        return "ARMISD::VREV16";
1104   case ARMISD::VZIP:          return "ARMISD::VZIP";
1105   case ARMISD::VUZP:          return "ARMISD::VUZP";
1106   case ARMISD::VTRN:          return "ARMISD::VTRN";
1107   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1108   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1109   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1110   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1111   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1112   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1113   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1114   case ARMISD::FMAX:          return "ARMISD::FMAX";
1115   case ARMISD::FMIN:          return "ARMISD::FMIN";
1116   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1117   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1118   case ARMISD::BFI:           return "ARMISD::BFI";
1119   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1120   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1121   case ARMISD::VBSL:          return "ARMISD::VBSL";
1122   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1123   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1124   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1125   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1126   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1127   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1128   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1129   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1130   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1131   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1132   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1133   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1134   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1135   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1136   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1137   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1138   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1139   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1140   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1141   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1142   }
1143 }
1144
1145 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1146   if (!VT.isVector()) return getPointerTy();
1147   return VT.changeVectorElementTypeToInteger();
1148 }
1149
1150 /// getRegClassFor - Return the register class that should be used for the
1151 /// specified value type.
1152 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1153   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1154   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1155   // load / store 4 to 8 consecutive D registers.
1156   if (Subtarget->hasNEON()) {
1157     if (VT == MVT::v4i64)
1158       return &ARM::QQPRRegClass;
1159     if (VT == MVT::v8i64)
1160       return &ARM::QQQQPRRegClass;
1161   }
1162   return TargetLowering::getRegClassFor(VT);
1163 }
1164
1165 // Create a fast isel object.
1166 FastISel *
1167 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1168                                   const TargetLibraryInfo *libInfo) const {
1169   return ARM::createFastISel(funcInfo, libInfo);
1170 }
1171
1172 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1173 /// be used for loads / stores from the global.
1174 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1175   return (Subtarget->isThumb1Only() ? 127 : 4095);
1176 }
1177
1178 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1179   unsigned NumVals = N->getNumValues();
1180   if (!NumVals)
1181     return Sched::RegPressure;
1182
1183   for (unsigned i = 0; i != NumVals; ++i) {
1184     EVT VT = N->getValueType(i);
1185     if (VT == MVT::Glue || VT == MVT::Other)
1186       continue;
1187     if (VT.isFloatingPoint() || VT.isVector())
1188       return Sched::ILP;
1189   }
1190
1191   if (!N->isMachineOpcode())
1192     return Sched::RegPressure;
1193
1194   // Load are scheduled for latency even if there instruction itinerary
1195   // is not available.
1196   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1197   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1198
1199   if (MCID.getNumDefs() == 0)
1200     return Sched::RegPressure;
1201   if (!Itins->isEmpty() &&
1202       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1203     return Sched::ILP;
1204
1205   return Sched::RegPressure;
1206 }
1207
1208 //===----------------------------------------------------------------------===//
1209 // Lowering Code
1210 //===----------------------------------------------------------------------===//
1211
1212 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1213 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1214   switch (CC) {
1215   default: llvm_unreachable("Unknown condition code!");
1216   case ISD::SETNE:  return ARMCC::NE;
1217   case ISD::SETEQ:  return ARMCC::EQ;
1218   case ISD::SETGT:  return ARMCC::GT;
1219   case ISD::SETGE:  return ARMCC::GE;
1220   case ISD::SETLT:  return ARMCC::LT;
1221   case ISD::SETLE:  return ARMCC::LE;
1222   case ISD::SETUGT: return ARMCC::HI;
1223   case ISD::SETUGE: return ARMCC::HS;
1224   case ISD::SETULT: return ARMCC::LO;
1225   case ISD::SETULE: return ARMCC::LS;
1226   }
1227 }
1228
1229 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1230 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1231                         ARMCC::CondCodes &CondCode2) {
1232   CondCode2 = ARMCC::AL;
1233   switch (CC) {
1234   default: llvm_unreachable("Unknown FP condition!");
1235   case ISD::SETEQ:
1236   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1237   case ISD::SETGT:
1238   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1239   case ISD::SETGE:
1240   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1241   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1242   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1243   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1244   case ISD::SETO:   CondCode = ARMCC::VC; break;
1245   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1246   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1247   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1248   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1249   case ISD::SETLT:
1250   case ISD::SETULT: CondCode = ARMCC::LT; break;
1251   case ISD::SETLE:
1252   case ISD::SETULE: CondCode = ARMCC::LE; break;
1253   case ISD::SETNE:
1254   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1255   }
1256 }
1257
1258 //===----------------------------------------------------------------------===//
1259 //                      Calling Convention Implementation
1260 //===----------------------------------------------------------------------===//
1261
1262 #include "ARMGenCallingConv.inc"
1263
1264 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1265 /// given CallingConvention value.
1266 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1267                                                  bool Return,
1268                                                  bool isVarArg) const {
1269   switch (CC) {
1270   default:
1271     llvm_unreachable("Unsupported calling convention");
1272   case CallingConv::Fast:
1273     if (Subtarget->hasVFP2() && !isVarArg) {
1274       if (!Subtarget->isAAPCS_ABI())
1275         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1276       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1277       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1278     }
1279     // Fallthrough
1280   case CallingConv::C: {
1281     // Use target triple & subtarget features to do actual dispatch.
1282     if (!Subtarget->isAAPCS_ABI())
1283       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1284     else if (Subtarget->hasVFP2() &&
1285              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1286              !isVarArg)
1287       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1288     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1289   }
1290   case CallingConv::ARM_AAPCS_VFP:
1291     if (!isVarArg)
1292       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1293     // Fallthrough
1294   case CallingConv::ARM_AAPCS:
1295     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1296   case CallingConv::ARM_APCS:
1297     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1298   case CallingConv::GHC:
1299     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1300   }
1301 }
1302
1303 /// LowerCallResult - Lower the result values of a call into the
1304 /// appropriate copies out of appropriate physical registers.
1305 SDValue
1306 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1307                                    CallingConv::ID CallConv, bool isVarArg,
1308                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1309                                    SDLoc dl, SelectionDAG &DAG,
1310                                    SmallVectorImpl<SDValue> &InVals,
1311                                    bool isThisReturn, SDValue ThisVal) const {
1312
1313   // Assign locations to each value returned by this call.
1314   SmallVector<CCValAssign, 16> RVLocs;
1315   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1316                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1317   CCInfo.AnalyzeCallResult(Ins,
1318                            CCAssignFnForNode(CallConv, /* Return*/ true,
1319                                              isVarArg));
1320
1321   // Copy all of the result registers out of their specified physreg.
1322   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1323     CCValAssign VA = RVLocs[i];
1324
1325     // Pass 'this' value directly from the argument to return value, to avoid
1326     // reg unit interference
1327     if (i == 0 && isThisReturn) {
1328       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1329              "unexpected return calling convention register assignment");
1330       InVals.push_back(ThisVal);
1331       continue;
1332     }
1333
1334     SDValue Val;
1335     if (VA.needsCustom()) {
1336       // Handle f64 or half of a v2f64.
1337       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1338                                       InFlag);
1339       Chain = Lo.getValue(1);
1340       InFlag = Lo.getValue(2);
1341       VA = RVLocs[++i]; // skip ahead to next loc
1342       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1343                                       InFlag);
1344       Chain = Hi.getValue(1);
1345       InFlag = Hi.getValue(2);
1346       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1347
1348       if (VA.getLocVT() == MVT::v2f64) {
1349         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1350         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1351                           DAG.getConstant(0, MVT::i32));
1352
1353         VA = RVLocs[++i]; // skip ahead to next loc
1354         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1355         Chain = Lo.getValue(1);
1356         InFlag = Lo.getValue(2);
1357         VA = RVLocs[++i]; // skip ahead to next loc
1358         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1359         Chain = Hi.getValue(1);
1360         InFlag = Hi.getValue(2);
1361         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1362         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1363                           DAG.getConstant(1, MVT::i32));
1364       }
1365     } else {
1366       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1367                                InFlag);
1368       Chain = Val.getValue(1);
1369       InFlag = Val.getValue(2);
1370     }
1371
1372     switch (VA.getLocInfo()) {
1373     default: llvm_unreachable("Unknown loc info!");
1374     case CCValAssign::Full: break;
1375     case CCValAssign::BCvt:
1376       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1377       break;
1378     }
1379
1380     InVals.push_back(Val);
1381   }
1382
1383   return Chain;
1384 }
1385
1386 /// LowerMemOpCallTo - Store the argument to the stack.
1387 SDValue
1388 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1389                                     SDValue StackPtr, SDValue Arg,
1390                                     SDLoc dl, SelectionDAG &DAG,
1391                                     const CCValAssign &VA,
1392                                     ISD::ArgFlagsTy Flags) const {
1393   unsigned LocMemOffset = VA.getLocMemOffset();
1394   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1395   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1396   return DAG.getStore(Chain, dl, Arg, PtrOff,
1397                       MachinePointerInfo::getStack(LocMemOffset),
1398                       false, false, 0);
1399 }
1400
1401 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1402                                          SDValue Chain, SDValue &Arg,
1403                                          RegsToPassVector &RegsToPass,
1404                                          CCValAssign &VA, CCValAssign &NextVA,
1405                                          SDValue &StackPtr,
1406                                          SmallVectorImpl<SDValue> &MemOpChains,
1407                                          ISD::ArgFlagsTy Flags) const {
1408
1409   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1410                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1411   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1412
1413   if (NextVA.isRegLoc())
1414     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1415   else {
1416     assert(NextVA.isMemLoc());
1417     if (StackPtr.getNode() == 0)
1418       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1419
1420     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1421                                            dl, DAG, NextVA,
1422                                            Flags));
1423   }
1424 }
1425
1426 /// LowerCall - Lowering a call into a callseq_start <-
1427 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1428 /// nodes.
1429 SDValue
1430 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1431                              SmallVectorImpl<SDValue> &InVals) const {
1432   SelectionDAG &DAG                     = CLI.DAG;
1433   SDLoc &dl                          = CLI.DL;
1434   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1435   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1436   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1437   SDValue Chain                         = CLI.Chain;
1438   SDValue Callee                        = CLI.Callee;
1439   bool &isTailCall                      = CLI.IsTailCall;
1440   CallingConv::ID CallConv              = CLI.CallConv;
1441   bool doesNotRet                       = CLI.DoesNotReturn;
1442   bool isVarArg                         = CLI.IsVarArg;
1443
1444   MachineFunction &MF = DAG.getMachineFunction();
1445   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1446   bool isThisReturn   = false;
1447   bool isSibCall      = false;
1448   // Disable tail calls if they're not supported.
1449   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1450     isTailCall = false;
1451   if (isTailCall) {
1452     // Check if it's really possible to do a tail call.
1453     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1454                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1455                                                    Outs, OutVals, Ins, DAG);
1456     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1457     // detected sibcalls.
1458     if (isTailCall) {
1459       ++NumTailCalls;
1460       isSibCall = true;
1461     }
1462   }
1463
1464   // Analyze operands of the call, assigning locations to each operand.
1465   SmallVector<CCValAssign, 16> ArgLocs;
1466   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1467                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1468   CCInfo.AnalyzeCallOperands(Outs,
1469                              CCAssignFnForNode(CallConv, /* Return*/ false,
1470                                                isVarArg));
1471
1472   // Get a count of how many bytes are to be pushed on the stack.
1473   unsigned NumBytes = CCInfo.getNextStackOffset();
1474
1475   // For tail calls, memory operands are available in our caller's stack.
1476   if (isSibCall)
1477     NumBytes = 0;
1478
1479   // Adjust the stack pointer for the new arguments...
1480   // These operations are automatically eliminated by the prolog/epilog pass
1481   if (!isSibCall)
1482     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1483                                  dl);
1484
1485   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1486
1487   RegsToPassVector RegsToPass;
1488   SmallVector<SDValue, 8> MemOpChains;
1489
1490   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1491   // of tail call optimization, arguments are handled later.
1492   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1493        i != e;
1494        ++i, ++realArgIdx) {
1495     CCValAssign &VA = ArgLocs[i];
1496     SDValue Arg = OutVals[realArgIdx];
1497     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1498     bool isByVal = Flags.isByVal();
1499
1500     // Promote the value if needed.
1501     switch (VA.getLocInfo()) {
1502     default: llvm_unreachable("Unknown loc info!");
1503     case CCValAssign::Full: break;
1504     case CCValAssign::SExt:
1505       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1506       break;
1507     case CCValAssign::ZExt:
1508       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1509       break;
1510     case CCValAssign::AExt:
1511       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1512       break;
1513     case CCValAssign::BCvt:
1514       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1515       break;
1516     }
1517
1518     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1519     if (VA.needsCustom()) {
1520       if (VA.getLocVT() == MVT::v2f64) {
1521         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1522                                   DAG.getConstant(0, MVT::i32));
1523         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1524                                   DAG.getConstant(1, MVT::i32));
1525
1526         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1527                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1528
1529         VA = ArgLocs[++i]; // skip ahead to next loc
1530         if (VA.isRegLoc()) {
1531           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1532                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1533         } else {
1534           assert(VA.isMemLoc());
1535
1536           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1537                                                  dl, DAG, VA, Flags));
1538         }
1539       } else {
1540         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1541                          StackPtr, MemOpChains, Flags);
1542       }
1543     } else if (VA.isRegLoc()) {
1544       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1545         assert(VA.getLocVT() == MVT::i32 &&
1546                "unexpected calling convention register assignment");
1547         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1548                "unexpected use of 'returned'");
1549         isThisReturn = true;
1550       }
1551       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1552     } else if (isByVal) {
1553       assert(VA.isMemLoc());
1554       unsigned offset = 0;
1555
1556       // True if this byval aggregate will be split between registers
1557       // and memory.
1558       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1559       unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1560
1561       if (CurByValIdx < ByValArgsCount) {
1562
1563         unsigned RegBegin, RegEnd;
1564         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1565
1566         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1567         unsigned int i, j;
1568         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1569           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1570           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1571           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1572                                      MachinePointerInfo(),
1573                                      false, false, false, 0);
1574           MemOpChains.push_back(Load.getValue(1));
1575           RegsToPass.push_back(std::make_pair(j, Load));
1576         }
1577
1578         // If parameter size outsides register area, "offset" value
1579         // helps us to calculate stack slot for remained part properly.
1580         offset = RegEnd - RegBegin;
1581
1582         CCInfo.nextInRegsParam();
1583       }
1584
1585       if (Flags.getByValSize() > 4*offset) {
1586         unsigned LocMemOffset = VA.getLocMemOffset();
1587         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1588         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1589                                   StkPtrOff);
1590         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1591         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1592         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1593                                            MVT::i32);
1594         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1595
1596         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1597         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1598         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1599                                           Ops, array_lengthof(Ops)));
1600       }
1601     } else if (!isSibCall) {
1602       assert(VA.isMemLoc());
1603
1604       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1605                                              dl, DAG, VA, Flags));
1606     }
1607   }
1608
1609   if (!MemOpChains.empty())
1610     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1611                         &MemOpChains[0], MemOpChains.size());
1612
1613   // Build a sequence of copy-to-reg nodes chained together with token chain
1614   // and flag operands which copy the outgoing args into the appropriate regs.
1615   SDValue InFlag;
1616   // Tail call byval lowering might overwrite argument registers so in case of
1617   // tail call optimization the copies to registers are lowered later.
1618   if (!isTailCall)
1619     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1620       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1621                                RegsToPass[i].second, InFlag);
1622       InFlag = Chain.getValue(1);
1623     }
1624
1625   // For tail calls lower the arguments to the 'real' stack slot.
1626   if (isTailCall) {
1627     // Force all the incoming stack arguments to be loaded from the stack
1628     // before any new outgoing arguments are stored to the stack, because the
1629     // outgoing stack slots may alias the incoming argument stack slots, and
1630     // the alias isn't otherwise explicit. This is slightly more conservative
1631     // than necessary, because it means that each store effectively depends
1632     // on every argument instead of just those arguments it would clobber.
1633
1634     // Do not flag preceding copytoreg stuff together with the following stuff.
1635     InFlag = SDValue();
1636     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1637       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1638                                RegsToPass[i].second, InFlag);
1639       InFlag = Chain.getValue(1);
1640     }
1641     InFlag = SDValue();
1642   }
1643
1644   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1645   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1646   // node so that legalize doesn't hack it.
1647   bool isDirect = false;
1648   bool isARMFunc = false;
1649   bool isLocalARMFunc = false;
1650   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1651
1652   if (EnableARMLongCalls) {
1653     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1654             && "long-calls with non-static relocation model!");
1655     // Handle a global address or an external symbol. If it's not one of
1656     // those, the target's already in a register, so we don't need to do
1657     // anything extra.
1658     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1659       const GlobalValue *GV = G->getGlobal();
1660       // Create a constant pool entry for the callee address
1661       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1662       ARMConstantPoolValue *CPV =
1663         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1664
1665       // Get the address of the callee into a register
1666       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1667       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1668       Callee = DAG.getLoad(getPointerTy(), dl,
1669                            DAG.getEntryNode(), CPAddr,
1670                            MachinePointerInfo::getConstantPool(),
1671                            false, false, false, 0);
1672     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1673       const char *Sym = S->getSymbol();
1674
1675       // Create a constant pool entry for the callee address
1676       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1677       ARMConstantPoolValue *CPV =
1678         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1679                                       ARMPCLabelIndex, 0);
1680       // Get the address of the callee into a register
1681       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1682       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1683       Callee = DAG.getLoad(getPointerTy(), dl,
1684                            DAG.getEntryNode(), CPAddr,
1685                            MachinePointerInfo::getConstantPool(),
1686                            false, false, false, 0);
1687     }
1688   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1689     const GlobalValue *GV = G->getGlobal();
1690     isDirect = true;
1691     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1692     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1693                    getTargetMachine().getRelocationModel() != Reloc::Static;
1694     isARMFunc = !Subtarget->isThumb() || isStub;
1695     // ARM call to a local ARM function is predicable.
1696     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1697     // tBX takes a register source operand.
1698     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1699       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1700       ARMConstantPoolValue *CPV =
1701         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1702       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1703       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1704       Callee = DAG.getLoad(getPointerTy(), dl,
1705                            DAG.getEntryNode(), CPAddr,
1706                            MachinePointerInfo::getConstantPool(),
1707                            false, false, false, 0);
1708       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1709       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1710                            getPointerTy(), Callee, PICLabel);
1711     } else {
1712       // On ELF targets for PIC code, direct calls should go through the PLT
1713       unsigned OpFlags = 0;
1714       if (Subtarget->isTargetELF() &&
1715           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1716         OpFlags = ARMII::MO_PLT;
1717       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1718     }
1719   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1720     isDirect = true;
1721     bool isStub = Subtarget->isTargetDarwin() &&
1722                   getTargetMachine().getRelocationModel() != Reloc::Static;
1723     isARMFunc = !Subtarget->isThumb() || isStub;
1724     // tBX takes a register source operand.
1725     const char *Sym = S->getSymbol();
1726     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1727       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1728       ARMConstantPoolValue *CPV =
1729         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1730                                       ARMPCLabelIndex, 4);
1731       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1732       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1733       Callee = DAG.getLoad(getPointerTy(), dl,
1734                            DAG.getEntryNode(), CPAddr,
1735                            MachinePointerInfo::getConstantPool(),
1736                            false, false, false, 0);
1737       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1738       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1739                            getPointerTy(), Callee, PICLabel);
1740     } else {
1741       unsigned OpFlags = 0;
1742       // On ELF targets for PIC code, direct calls should go through the PLT
1743       if (Subtarget->isTargetELF() &&
1744                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1745         OpFlags = ARMII::MO_PLT;
1746       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1747     }
1748   }
1749
1750   // FIXME: handle tail calls differently.
1751   unsigned CallOpc;
1752   bool HasMinSizeAttr = MF.getFunction()->getAttributes().
1753     hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
1754   if (Subtarget->isThumb()) {
1755     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1756       CallOpc = ARMISD::CALL_NOLINK;
1757     else
1758       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1759   } else {
1760     if (!isDirect && !Subtarget->hasV5TOps())
1761       CallOpc = ARMISD::CALL_NOLINK;
1762     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1763                // Emit regular call when code size is the priority
1764                !HasMinSizeAttr)
1765       // "mov lr, pc; b _foo" to avoid confusing the RSP
1766       CallOpc = ARMISD::CALL_NOLINK;
1767     else
1768       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1769   }
1770
1771   std::vector<SDValue> Ops;
1772   Ops.push_back(Chain);
1773   Ops.push_back(Callee);
1774
1775   // Add argument registers to the end of the list so that they are known live
1776   // into the call.
1777   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1778     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1779                                   RegsToPass[i].second.getValueType()));
1780
1781   // Add a register mask operand representing the call-preserved registers.
1782   const uint32_t *Mask;
1783   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1784   const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1785   if (isThisReturn) {
1786     // For 'this' returns, use the R0-preserving mask if applicable
1787     Mask = ARI->getThisReturnPreservedMask(CallConv);
1788     if (!Mask) {
1789       // Set isThisReturn to false if the calling convention is not one that
1790       // allows 'returned' to be modeled in this way, so LowerCallResult does
1791       // not try to pass 'this' straight through 
1792       isThisReturn = false;
1793       Mask = ARI->getCallPreservedMask(CallConv);
1794     }
1795   } else
1796     Mask = ARI->getCallPreservedMask(CallConv);
1797
1798   assert(Mask && "Missing call preserved mask for calling convention");
1799   Ops.push_back(DAG.getRegisterMask(Mask));
1800
1801   if (InFlag.getNode())
1802     Ops.push_back(InFlag);
1803
1804   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1805   if (isTailCall)
1806     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1807
1808   // Returns a chain and a flag for retval copy to use.
1809   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1810   InFlag = Chain.getValue(1);
1811
1812   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1813                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1814   if (!Ins.empty())
1815     InFlag = Chain.getValue(1);
1816
1817   // Handle result values, copying them out of physregs into vregs that we
1818   // return.
1819   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1820                          InVals, isThisReturn,
1821                          isThisReturn ? OutVals[0] : SDValue());
1822 }
1823
1824 /// HandleByVal - Every parameter *after* a byval parameter is passed
1825 /// on the stack.  Remember the next parameter register to allocate,
1826 /// and then confiscate the rest of the parameter registers to insure
1827 /// this.
1828 void
1829 ARMTargetLowering::HandleByVal(
1830     CCState *State, unsigned &size, unsigned Align) const {
1831   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1832   assert((State->getCallOrPrologue() == Prologue ||
1833           State->getCallOrPrologue() == Call) &&
1834          "unhandled ParmContext");
1835
1836   // For in-prologue parameters handling, we also introduce stack offset
1837   // for byval registers: see CallingConvLower.cpp, CCState::HandleByVal.
1838   // This behaviour outsides AAPCS rules (5.5 Parameters Passing) of how
1839   // NSAA should be evaluted (NSAA means "next stacked argument address").
1840   // So: NextStackOffset = NSAAOffset + SizeOfByValParamsStoredInRegs.
1841   // Then: NSAAOffset = NextStackOffset - SizeOfByValParamsStoredInRegs.
1842   unsigned NSAAOffset = State->getNextStackOffset();
1843   if (State->getCallOrPrologue() != Call) {
1844     for (unsigned i = 0, e = State->getInRegsParamsCount(); i != e; ++i) {
1845       unsigned RB, RE;
1846       State->getInRegsParamInfo(i, RB, RE);
1847       assert(NSAAOffset >= (RE-RB)*4 &&
1848              "Stack offset for byval regs doesn't introduced anymore?");
1849       NSAAOffset -= (RE-RB)*4;
1850     }
1851   }
1852   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1853     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1854       unsigned AlignInRegs = Align / 4;
1855       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1856       for (unsigned i = 0; i < Waste; ++i)
1857         reg = State->AllocateReg(GPRArgRegs, 4);
1858     }
1859     if (reg != 0) {
1860       unsigned excess = 4 * (ARM::R4 - reg);
1861
1862       // Special case when NSAA != SP and parameter size greater than size of
1863       // all remained GPR regs. In that case we can't split parameter, we must
1864       // send it to stack. We also must set NCRN to R4, so waste all
1865       // remained registers.
1866       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1867         while (State->AllocateReg(GPRArgRegs, 4))
1868           ;
1869         return;
1870       }
1871
1872       // First register for byval parameter is the first register that wasn't
1873       // allocated before this method call, so it would be "reg".
1874       // If parameter is small enough to be saved in range [reg, r4), then
1875       // the end (first after last) register would be reg + param-size-in-regs,
1876       // else parameter would be splitted between registers and stack,
1877       // end register would be r4 in this case.
1878       unsigned ByValRegBegin = reg;
1879       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1880       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1881       // Note, first register is allocated in the beginning of function already,
1882       // allocate remained amount of registers we need.
1883       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1884         State->AllocateReg(GPRArgRegs, 4);
1885       // At a call site, a byval parameter that is split between
1886       // registers and memory needs its size truncated here.  In a
1887       // function prologue, such byval parameters are reassembled in
1888       // memory, and are not truncated.
1889       if (State->getCallOrPrologue() == Call) {
1890         // Make remained size equal to 0 in case, when
1891         // the whole structure may be stored into registers.
1892         if (size < excess)
1893           size = 0;
1894         else
1895           size -= excess;
1896       }
1897     }
1898   }
1899 }
1900
1901 /// MatchingStackOffset - Return true if the given stack call argument is
1902 /// already available in the same position (relatively) of the caller's
1903 /// incoming argument stack.
1904 static
1905 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1906                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1907                          const TargetInstrInfo *TII) {
1908   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1909   int FI = INT_MAX;
1910   if (Arg.getOpcode() == ISD::CopyFromReg) {
1911     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1912     if (!TargetRegisterInfo::isVirtualRegister(VR))
1913       return false;
1914     MachineInstr *Def = MRI->getVRegDef(VR);
1915     if (!Def)
1916       return false;
1917     if (!Flags.isByVal()) {
1918       if (!TII->isLoadFromStackSlot(Def, FI))
1919         return false;
1920     } else {
1921       return false;
1922     }
1923   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1924     if (Flags.isByVal())
1925       // ByVal argument is passed in as a pointer but it's now being
1926       // dereferenced. e.g.
1927       // define @foo(%struct.X* %A) {
1928       //   tail call @bar(%struct.X* byval %A)
1929       // }
1930       return false;
1931     SDValue Ptr = Ld->getBasePtr();
1932     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1933     if (!FINode)
1934       return false;
1935     FI = FINode->getIndex();
1936   } else
1937     return false;
1938
1939   assert(FI != INT_MAX);
1940   if (!MFI->isFixedObjectIndex(FI))
1941     return false;
1942   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1943 }
1944
1945 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1946 /// for tail call optimization. Targets which want to do tail call
1947 /// optimization should implement this function.
1948 bool
1949 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1950                                                      CallingConv::ID CalleeCC,
1951                                                      bool isVarArg,
1952                                                      bool isCalleeStructRet,
1953                                                      bool isCallerStructRet,
1954                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1955                                     const SmallVectorImpl<SDValue> &OutVals,
1956                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1957                                                      SelectionDAG& DAG) const {
1958   const Function *CallerF = DAG.getMachineFunction().getFunction();
1959   CallingConv::ID CallerCC = CallerF->getCallingConv();
1960   bool CCMatch = CallerCC == CalleeCC;
1961
1962   // Look for obvious safe cases to perform tail call optimization that do not
1963   // require ABI changes. This is what gcc calls sibcall.
1964
1965   // Do not sibcall optimize vararg calls unless the call site is not passing
1966   // any arguments.
1967   if (isVarArg && !Outs.empty())
1968     return false;
1969
1970   // Exception-handling functions need a special set of instructions to indicate
1971   // a return to the hardware. Tail-calling another function would probably
1972   // break this.
1973   if (CallerF->hasFnAttribute("interrupt"))
1974     return false;
1975
1976   // Also avoid sibcall optimization if either caller or callee uses struct
1977   // return semantics.
1978   if (isCalleeStructRet || isCallerStructRet)
1979     return false;
1980
1981   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1982   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1983   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1984   // support in the assembler and linker to be used. This would need to be
1985   // fixed to fully support tail calls in Thumb1.
1986   //
1987   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1988   // LR.  This means if we need to reload LR, it takes an extra instructions,
1989   // which outweighs the value of the tail call; but here we don't know yet
1990   // whether LR is going to be used.  Probably the right approach is to
1991   // generate the tail call here and turn it back into CALL/RET in
1992   // emitEpilogue if LR is used.
1993
1994   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1995   // but we need to make sure there are enough registers; the only valid
1996   // registers are the 4 used for parameters.  We don't currently do this
1997   // case.
1998   if (Subtarget->isThumb1Only())
1999     return false;
2000
2001   // If the calling conventions do not match, then we'd better make sure the
2002   // results are returned in the same way as what the caller expects.
2003   if (!CCMatch) {
2004     SmallVector<CCValAssign, 16> RVLocs1;
2005     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2006                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
2007     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2008
2009     SmallVector<CCValAssign, 16> RVLocs2;
2010     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2011                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
2012     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2013
2014     if (RVLocs1.size() != RVLocs2.size())
2015       return false;
2016     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2017       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2018         return false;
2019       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2020         return false;
2021       if (RVLocs1[i].isRegLoc()) {
2022         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2023           return false;
2024       } else {
2025         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2026           return false;
2027       }
2028     }
2029   }
2030
2031   // If Caller's vararg or byval argument has been split between registers and
2032   // stack, do not perform tail call, since part of the argument is in caller's
2033   // local frame.
2034   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2035                                       getInfo<ARMFunctionInfo>();
2036   if (AFI_Caller->getArgRegsSaveSize())
2037     return false;
2038
2039   // If the callee takes no arguments then go on to check the results of the
2040   // call.
2041   if (!Outs.empty()) {
2042     // Check if stack adjustment is needed. For now, do not do this if any
2043     // argument is passed on the stack.
2044     SmallVector<CCValAssign, 16> ArgLocs;
2045     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2046                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
2047     CCInfo.AnalyzeCallOperands(Outs,
2048                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2049     if (CCInfo.getNextStackOffset()) {
2050       MachineFunction &MF = DAG.getMachineFunction();
2051
2052       // Check if the arguments are already laid out in the right way as
2053       // the caller's fixed stack objects.
2054       MachineFrameInfo *MFI = MF.getFrameInfo();
2055       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2056       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2057       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2058            i != e;
2059            ++i, ++realArgIdx) {
2060         CCValAssign &VA = ArgLocs[i];
2061         EVT RegVT = VA.getLocVT();
2062         SDValue Arg = OutVals[realArgIdx];
2063         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2064         if (VA.getLocInfo() == CCValAssign::Indirect)
2065           return false;
2066         if (VA.needsCustom()) {
2067           // f64 and vector types are split into multiple registers or
2068           // register/stack-slot combinations.  The types will not match
2069           // the registers; give up on memory f64 refs until we figure
2070           // out what to do about this.
2071           if (!VA.isRegLoc())
2072             return false;
2073           if (!ArgLocs[++i].isRegLoc())
2074             return false;
2075           if (RegVT == MVT::v2f64) {
2076             if (!ArgLocs[++i].isRegLoc())
2077               return false;
2078             if (!ArgLocs[++i].isRegLoc())
2079               return false;
2080           }
2081         } else if (!VA.isRegLoc()) {
2082           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2083                                    MFI, MRI, TII))
2084             return false;
2085         }
2086       }
2087     }
2088   }
2089
2090   return true;
2091 }
2092
2093 bool
2094 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2095                                   MachineFunction &MF, bool isVarArg,
2096                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2097                                   LLVMContext &Context) const {
2098   SmallVector<CCValAssign, 16> RVLocs;
2099   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2100   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2101                                                     isVarArg));
2102 }
2103
2104 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2105                                     SDLoc DL, SelectionDAG &DAG) {
2106   const MachineFunction &MF = DAG.getMachineFunction();
2107   const Function *F = MF.getFunction();
2108
2109   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2110
2111   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2112   // version of the "preferred return address". These offsets affect the return
2113   // instruction if this is a return from PL1 without hypervisor extensions.
2114   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2115   //    SWI:     0      "subs pc, lr, #0"
2116   //    ABORT:   +4     "subs pc, lr, #4"
2117   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2118   // UNDEF varies depending on where the exception came from ARM or Thumb
2119   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2120
2121   int64_t LROffset;
2122   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2123       IntKind == "ABORT")
2124     LROffset = 4;
2125   else if (IntKind == "SWI" || IntKind == "UNDEF")
2126     LROffset = 0;
2127   else
2128     report_fatal_error("Unsupported interrupt attribute. If present, value "
2129                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2130
2131   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2132
2133   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other,
2134                      RetOps.data(), RetOps.size());
2135 }
2136
2137 SDValue
2138 ARMTargetLowering::LowerReturn(SDValue Chain,
2139                                CallingConv::ID CallConv, bool isVarArg,
2140                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2141                                const SmallVectorImpl<SDValue> &OutVals,
2142                                SDLoc dl, SelectionDAG &DAG) const {
2143
2144   // CCValAssign - represent the assignment of the return value to a location.
2145   SmallVector<CCValAssign, 16> RVLocs;
2146
2147   // CCState - Info about the registers and stack slots.
2148   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2149                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2150
2151   // Analyze outgoing return values.
2152   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2153                                                isVarArg));
2154
2155   SDValue Flag;
2156   SmallVector<SDValue, 4> RetOps;
2157   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2158
2159   // Copy the result values into the output registers.
2160   for (unsigned i = 0, realRVLocIdx = 0;
2161        i != RVLocs.size();
2162        ++i, ++realRVLocIdx) {
2163     CCValAssign &VA = RVLocs[i];
2164     assert(VA.isRegLoc() && "Can only return in registers!");
2165
2166     SDValue Arg = OutVals[realRVLocIdx];
2167
2168     switch (VA.getLocInfo()) {
2169     default: llvm_unreachable("Unknown loc info!");
2170     case CCValAssign::Full: break;
2171     case CCValAssign::BCvt:
2172       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2173       break;
2174     }
2175
2176     if (VA.needsCustom()) {
2177       if (VA.getLocVT() == MVT::v2f64) {
2178         // Extract the first half and return it in two registers.
2179         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2180                                    DAG.getConstant(0, MVT::i32));
2181         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2182                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2183
2184         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
2185         Flag = Chain.getValue(1);
2186         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2187         VA = RVLocs[++i]; // skip ahead to next loc
2188         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2189                                  HalfGPRs.getValue(1), Flag);
2190         Flag = Chain.getValue(1);
2191         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2192         VA = RVLocs[++i]; // skip ahead to next loc
2193
2194         // Extract the 2nd half and fall through to handle it as an f64 value.
2195         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2196                           DAG.getConstant(1, MVT::i32));
2197       }
2198       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2199       // available.
2200       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2201                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
2202       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
2203       Flag = Chain.getValue(1);
2204       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2205       VA = RVLocs[++i]; // skip ahead to next loc
2206       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
2207                                Flag);
2208     } else
2209       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2210
2211     // Guarantee that all emitted copies are
2212     // stuck together, avoiding something bad.
2213     Flag = Chain.getValue(1);
2214     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2215   }
2216
2217   // Update chain and glue.
2218   RetOps[0] = Chain;
2219   if (Flag.getNode())
2220     RetOps.push_back(Flag);
2221
2222   // CPUs which aren't M-class use a special sequence to return from
2223   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2224   // though we use "subs pc, lr, #N").
2225   //
2226   // M-class CPUs actually use a normal return sequence with a special
2227   // (hardware-provided) value in LR, so the normal code path works.
2228   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2229       !Subtarget->isMClass()) {
2230     if (Subtarget->isThumb1Only())
2231       report_fatal_error("interrupt attribute is not supported in Thumb1");
2232     return LowerInterruptReturn(RetOps, dl, DAG);
2233   }
2234
2235   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
2236                      RetOps.data(), RetOps.size());
2237 }
2238
2239 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2240   if (N->getNumValues() != 1)
2241     return false;
2242   if (!N->hasNUsesOfValue(1, 0))
2243     return false;
2244
2245   SDValue TCChain = Chain;
2246   SDNode *Copy = *N->use_begin();
2247   if (Copy->getOpcode() == ISD::CopyToReg) {
2248     // If the copy has a glue operand, we conservatively assume it isn't safe to
2249     // perform a tail call.
2250     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2251       return false;
2252     TCChain = Copy->getOperand(0);
2253   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2254     SDNode *VMov = Copy;
2255     // f64 returned in a pair of GPRs.
2256     SmallPtrSet<SDNode*, 2> Copies;
2257     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2258          UI != UE; ++UI) {
2259       if (UI->getOpcode() != ISD::CopyToReg)
2260         return false;
2261       Copies.insert(*UI);
2262     }
2263     if (Copies.size() > 2)
2264       return false;
2265
2266     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2267          UI != UE; ++UI) {
2268       SDValue UseChain = UI->getOperand(0);
2269       if (Copies.count(UseChain.getNode()))
2270         // Second CopyToReg
2271         Copy = *UI;
2272       else
2273         // First CopyToReg
2274         TCChain = UseChain;
2275     }
2276   } else if (Copy->getOpcode() == ISD::BITCAST) {
2277     // f32 returned in a single GPR.
2278     if (!Copy->hasOneUse())
2279       return false;
2280     Copy = *Copy->use_begin();
2281     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2282       return false;
2283     TCChain = Copy->getOperand(0);
2284   } else {
2285     return false;
2286   }
2287
2288   bool HasRet = false;
2289   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2290        UI != UE; ++UI) {
2291     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2292         UI->getOpcode() != ARMISD::INTRET_FLAG)
2293       return false;
2294     HasRet = true;
2295   }
2296
2297   if (!HasRet)
2298     return false;
2299
2300   Chain = TCChain;
2301   return true;
2302 }
2303
2304 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2305   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2306     return false;
2307
2308   if (!CI->isTailCall())
2309     return false;
2310
2311   return !Subtarget->isThumb1Only();
2312 }
2313
2314 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2315 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2316 // one of the above mentioned nodes. It has to be wrapped because otherwise
2317 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2318 // be used to form addressing mode. These wrapped nodes will be selected
2319 // into MOVi.
2320 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2321   EVT PtrVT = Op.getValueType();
2322   // FIXME there is no actual debug info here
2323   SDLoc dl(Op);
2324   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2325   SDValue Res;
2326   if (CP->isMachineConstantPoolEntry())
2327     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2328                                     CP->getAlignment());
2329   else
2330     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2331                                     CP->getAlignment());
2332   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2333 }
2334
2335 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2336   return MachineJumpTableInfo::EK_Inline;
2337 }
2338
2339 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2340                                              SelectionDAG &DAG) const {
2341   MachineFunction &MF = DAG.getMachineFunction();
2342   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2343   unsigned ARMPCLabelIndex = 0;
2344   SDLoc DL(Op);
2345   EVT PtrVT = getPointerTy();
2346   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2347   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2348   SDValue CPAddr;
2349   if (RelocM == Reloc::Static) {
2350     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2351   } else {
2352     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2353     ARMPCLabelIndex = AFI->createPICLabelUId();
2354     ARMConstantPoolValue *CPV =
2355       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2356                                       ARMCP::CPBlockAddress, PCAdj);
2357     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2358   }
2359   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2360   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2361                                MachinePointerInfo::getConstantPool(),
2362                                false, false, false, 0);
2363   if (RelocM == Reloc::Static)
2364     return Result;
2365   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2366   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2367 }
2368
2369 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2370 SDValue
2371 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2372                                                  SelectionDAG &DAG) const {
2373   SDLoc dl(GA);
2374   EVT PtrVT = getPointerTy();
2375   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2376   MachineFunction &MF = DAG.getMachineFunction();
2377   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2378   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2379   ARMConstantPoolValue *CPV =
2380     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2381                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2382   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2383   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2384   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2385                          MachinePointerInfo::getConstantPool(),
2386                          false, false, false, 0);
2387   SDValue Chain = Argument.getValue(1);
2388
2389   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2390   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2391
2392   // call __tls_get_addr.
2393   ArgListTy Args;
2394   ArgListEntry Entry;
2395   Entry.Node = Argument;
2396   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2397   Args.push_back(Entry);
2398   // FIXME: is there useful debug info available here?
2399   TargetLowering::CallLoweringInfo CLI(Chain,
2400                 (Type *) Type::getInt32Ty(*DAG.getContext()),
2401                 false, false, false, false,
2402                 0, CallingConv::C, /*isTailCall=*/false,
2403                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2404                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2405   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2406   return CallResult.first;
2407 }
2408
2409 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2410 // "local exec" model.
2411 SDValue
2412 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2413                                         SelectionDAG &DAG,
2414                                         TLSModel::Model model) const {
2415   const GlobalValue *GV = GA->getGlobal();
2416   SDLoc dl(GA);
2417   SDValue Offset;
2418   SDValue Chain = DAG.getEntryNode();
2419   EVT PtrVT = getPointerTy();
2420   // Get the Thread Pointer
2421   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2422
2423   if (model == TLSModel::InitialExec) {
2424     MachineFunction &MF = DAG.getMachineFunction();
2425     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2426     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2427     // Initial exec model.
2428     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2429     ARMConstantPoolValue *CPV =
2430       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2431                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2432                                       true);
2433     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2434     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2435     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2436                          MachinePointerInfo::getConstantPool(),
2437                          false, false, false, 0);
2438     Chain = Offset.getValue(1);
2439
2440     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2441     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2442
2443     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2444                          MachinePointerInfo::getConstantPool(),
2445                          false, false, false, 0);
2446   } else {
2447     // local exec model
2448     assert(model == TLSModel::LocalExec);
2449     ARMConstantPoolValue *CPV =
2450       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2451     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2452     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2453     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2454                          MachinePointerInfo::getConstantPool(),
2455                          false, false, false, 0);
2456   }
2457
2458   // The address of the thread local variable is the add of the thread
2459   // pointer with the offset of the variable.
2460   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2461 }
2462
2463 SDValue
2464 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2465   // TODO: implement the "local dynamic" model
2466   assert(Subtarget->isTargetELF() &&
2467          "TLS not implemented for non-ELF targets");
2468   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2469
2470   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2471
2472   switch (model) {
2473     case TLSModel::GeneralDynamic:
2474     case TLSModel::LocalDynamic:
2475       return LowerToTLSGeneralDynamicModel(GA, DAG);
2476     case TLSModel::InitialExec:
2477     case TLSModel::LocalExec:
2478       return LowerToTLSExecModels(GA, DAG, model);
2479   }
2480   llvm_unreachable("bogus TLS model");
2481 }
2482
2483 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2484                                                  SelectionDAG &DAG) const {
2485   EVT PtrVT = getPointerTy();
2486   SDLoc dl(Op);
2487   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2488   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2489     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2490     ARMConstantPoolValue *CPV =
2491       ARMConstantPoolConstant::Create(GV,
2492                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2493     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2494     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2495     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2496                                  CPAddr,
2497                                  MachinePointerInfo::getConstantPool(),
2498                                  false, false, false, 0);
2499     SDValue Chain = Result.getValue(1);
2500     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2501     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2502     if (!UseGOTOFF)
2503       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2504                            MachinePointerInfo::getGOT(),
2505                            false, false, false, 0);
2506     return Result;
2507   }
2508
2509   // If we have T2 ops, we can materialize the address directly via movt/movw
2510   // pair. This is always cheaper.
2511   if (Subtarget->useMovt()) {
2512     ++NumMovwMovt;
2513     // FIXME: Once remat is capable of dealing with instructions with register
2514     // operands, expand this into two nodes.
2515     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2516                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2517   } else {
2518     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2519     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2520     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2521                        MachinePointerInfo::getConstantPool(),
2522                        false, false, false, 0);
2523   }
2524 }
2525
2526 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2527                                                     SelectionDAG &DAG) const {
2528   EVT PtrVT = getPointerTy();
2529   SDLoc dl(Op);
2530   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2531   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2532
2533   // FIXME: Enable this for static codegen when tool issues are fixed.  Also
2534   // update ARMFastISel::ARMMaterializeGV.
2535   if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2536     ++NumMovwMovt;
2537     // FIXME: Once remat is capable of dealing with instructions with register
2538     // operands, expand this into two nodes.
2539     if (RelocM == Reloc::Static)
2540       return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2541                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2542
2543     unsigned Wrapper = (RelocM == Reloc::PIC_)
2544       ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2545     SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2546                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2547     if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2548       Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2549                            MachinePointerInfo::getGOT(),
2550                            false, false, false, 0);
2551     return Result;
2552   }
2553
2554   unsigned ARMPCLabelIndex = 0;
2555   SDValue CPAddr;
2556   if (RelocM == Reloc::Static) {
2557     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2558   } else {
2559     ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2560     ARMPCLabelIndex = AFI->createPICLabelUId();
2561     unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2562     ARMConstantPoolValue *CPV =
2563       ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2564                                       PCAdj);
2565     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2566   }
2567   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2568
2569   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2570                                MachinePointerInfo::getConstantPool(),
2571                                false, false, false, 0);
2572   SDValue Chain = Result.getValue(1);
2573
2574   if (RelocM == Reloc::PIC_) {
2575     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2576     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2577   }
2578
2579   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2580     Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2581                          false, false, false, 0);
2582
2583   return Result;
2584 }
2585
2586 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2587                                                     SelectionDAG &DAG) const {
2588   assert(Subtarget->isTargetELF() &&
2589          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2590   MachineFunction &MF = DAG.getMachineFunction();
2591   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2592   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2593   EVT PtrVT = getPointerTy();
2594   SDLoc dl(Op);
2595   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2596   ARMConstantPoolValue *CPV =
2597     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2598                                   ARMPCLabelIndex, PCAdj);
2599   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2600   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2601   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2602                                MachinePointerInfo::getConstantPool(),
2603                                false, false, false, 0);
2604   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2605   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2606 }
2607
2608 SDValue
2609 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2610   SDLoc dl(Op);
2611   SDValue Val = DAG.getConstant(0, MVT::i32);
2612   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2613                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2614                      Op.getOperand(1), Val);
2615 }
2616
2617 SDValue
2618 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2619   SDLoc dl(Op);
2620   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2621                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2622 }
2623
2624 SDValue
2625 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2626                                           const ARMSubtarget *Subtarget) const {
2627   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2628   SDLoc dl(Op);
2629   switch (IntNo) {
2630   default: return SDValue();    // Don't custom lower most intrinsics.
2631   case Intrinsic::arm_thread_pointer: {
2632     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2633     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2634   }
2635   case Intrinsic::eh_sjlj_lsda: {
2636     MachineFunction &MF = DAG.getMachineFunction();
2637     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2638     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2639     EVT PtrVT = getPointerTy();
2640     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2641     SDValue CPAddr;
2642     unsigned PCAdj = (RelocM != Reloc::PIC_)
2643       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2644     ARMConstantPoolValue *CPV =
2645       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2646                                       ARMCP::CPLSDA, PCAdj);
2647     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2648     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2649     SDValue Result =
2650       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2651                   MachinePointerInfo::getConstantPool(),
2652                   false, false, false, 0);
2653
2654     if (RelocM == Reloc::PIC_) {
2655       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2656       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2657     }
2658     return Result;
2659   }
2660   case Intrinsic::arm_neon_vmulls:
2661   case Intrinsic::arm_neon_vmullu: {
2662     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2663       ? ARMISD::VMULLs : ARMISD::VMULLu;
2664     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2665                        Op.getOperand(1), Op.getOperand(2));
2666   }
2667   }
2668 }
2669
2670 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2671                                  const ARMSubtarget *Subtarget) {
2672   // FIXME: handle "fence singlethread" more efficiently.
2673   SDLoc dl(Op);
2674   if (!Subtarget->hasDataBarrier()) {
2675     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2676     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2677     // here.
2678     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2679            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2680     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2681                        DAG.getConstant(0, MVT::i32));
2682   }
2683
2684   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2685   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2686   unsigned Domain = ARM_MB::ISH;
2687   if (Subtarget->isMClass()) {
2688     // Only a full system barrier exists in the M-class architectures.
2689     Domain = ARM_MB::SY;
2690   } else if (Subtarget->isSwift() && Ord == Release) {
2691     // Swift happens to implement ISHST barriers in a way that's compatible with
2692     // Release semantics but weaker than ISH so we'd be fools not to use
2693     // it. Beware: other processors probably don't!
2694     Domain = ARM_MB::ISHST;
2695   }
2696
2697   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2698                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2699                      DAG.getConstant(Domain, MVT::i32));
2700 }
2701
2702 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2703                              const ARMSubtarget *Subtarget) {
2704   // ARM pre v5TE and Thumb1 does not have preload instructions.
2705   if (!(Subtarget->isThumb2() ||
2706         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2707     // Just preserve the chain.
2708     return Op.getOperand(0);
2709
2710   SDLoc dl(Op);
2711   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2712   if (!isRead &&
2713       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2714     // ARMv7 with MP extension has PLDW.
2715     return Op.getOperand(0);
2716
2717   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2718   if (Subtarget->isThumb()) {
2719     // Invert the bits.
2720     isRead = ~isRead & 1;
2721     isData = ~isData & 1;
2722   }
2723
2724   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2725                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2726                      DAG.getConstant(isData, MVT::i32));
2727 }
2728
2729 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2730   MachineFunction &MF = DAG.getMachineFunction();
2731   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2732
2733   // vastart just stores the address of the VarArgsFrameIndex slot into the
2734   // memory location argument.
2735   SDLoc dl(Op);
2736   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2737   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2738   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2739   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2740                       MachinePointerInfo(SV), false, false, 0);
2741 }
2742
2743 SDValue
2744 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2745                                         SDValue &Root, SelectionDAG &DAG,
2746                                         SDLoc dl) const {
2747   MachineFunction &MF = DAG.getMachineFunction();
2748   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2749
2750   const TargetRegisterClass *RC;
2751   if (AFI->isThumb1OnlyFunction())
2752     RC = &ARM::tGPRRegClass;
2753   else
2754     RC = &ARM::GPRRegClass;
2755
2756   // Transform the arguments stored in physical registers into virtual ones.
2757   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2758   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2759
2760   SDValue ArgValue2;
2761   if (NextVA.isMemLoc()) {
2762     MachineFrameInfo *MFI = MF.getFrameInfo();
2763     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2764
2765     // Create load node to retrieve arguments from the stack.
2766     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2767     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2768                             MachinePointerInfo::getFixedStack(FI),
2769                             false, false, false, 0);
2770   } else {
2771     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2772     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2773   }
2774
2775   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2776 }
2777
2778 void
2779 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2780                                   unsigned InRegsParamRecordIdx,
2781                                   unsigned ArgSize,
2782                                   unsigned &ArgRegsSize,
2783                                   unsigned &ArgRegsSaveSize)
2784   const {
2785   unsigned NumGPRs;
2786   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2787     unsigned RBegin, REnd;
2788     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2789     NumGPRs = REnd - RBegin;
2790   } else {
2791     unsigned int firstUnalloced;
2792     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2793                                                 sizeof(GPRArgRegs) /
2794                                                 sizeof(GPRArgRegs[0]));
2795     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2796   }
2797
2798   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2799   ArgRegsSize = NumGPRs * 4;
2800
2801   // If parameter is split between stack and GPRs...
2802   if (NumGPRs && Align == 8 &&
2803       (ArgRegsSize < ArgSize ||
2804         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2805     // Add padding for part of param recovered from GPRs, so
2806     // its last byte must be at address K*8 - 1.
2807     // We need to do it, since remained (stack) part of parameter has
2808     // stack alignment, and we need to "attach" "GPRs head" without gaps
2809     // to it:
2810     // Stack:
2811     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2812     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2813     //
2814     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2815     unsigned Padding =
2816         ((ArgRegsSize + AFI->getArgRegsSaveSize() + Align - 1) & ~(Align-1)) -
2817         (ArgRegsSize + AFI->getArgRegsSaveSize());
2818     ArgRegsSaveSize = ArgRegsSize + Padding;
2819   } else
2820     // We don't need to extend regs save size for byval parameters if they
2821     // are passed via GPRs only.
2822     ArgRegsSaveSize = ArgRegsSize;
2823 }
2824
2825 // The remaining GPRs hold either the beginning of variable-argument
2826 // data, or the beginning of an aggregate passed by value (usually
2827 // byval).  Either way, we allocate stack slots adjacent to the data
2828 // provided by our caller, and store the unallocated registers there.
2829 // If this is a variadic function, the va_list pointer will begin with
2830 // these values; otherwise, this reassembles a (byval) structure that
2831 // was split between registers and memory.
2832 // Return: The frame index registers were stored into.
2833 int
2834 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2835                                   SDLoc dl, SDValue &Chain,
2836                                   const Value *OrigArg,
2837                                   unsigned InRegsParamRecordIdx,
2838                                   unsigned OffsetFromOrigArg,
2839                                   unsigned ArgOffset,
2840                                   unsigned ArgSize,
2841                                   bool ForceMutable) const {
2842
2843   // Currently, two use-cases possible:
2844   // Case #1. Non var-args function, and we meet first byval parameter.
2845   //          Setup first unallocated register as first byval register;
2846   //          eat all remained registers
2847   //          (these two actions are performed by HandleByVal method).
2848   //          Then, here, we initialize stack frame with
2849   //          "store-reg" instructions.
2850   // Case #2. Var-args function, that doesn't contain byval parameters.
2851   //          The same: eat all remained unallocated registers,
2852   //          initialize stack frame.
2853
2854   MachineFunction &MF = DAG.getMachineFunction();
2855   MachineFrameInfo *MFI = MF.getFrameInfo();
2856   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2857   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2858   unsigned RBegin, REnd;
2859   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2860     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2861     firstRegToSaveIndex = RBegin - ARM::R0;
2862     lastRegToSaveIndex = REnd - ARM::R0;
2863   } else {
2864     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2865       (GPRArgRegs, array_lengthof(GPRArgRegs));
2866     lastRegToSaveIndex = 4;
2867   }
2868
2869   unsigned ArgRegsSize, ArgRegsSaveSize;
2870   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2871                  ArgRegsSize, ArgRegsSaveSize);
2872
2873   // Store any by-val regs to their spots on the stack so that they may be
2874   // loaded by deferencing the result of formal parameter pointer or va_next.
2875   // Note: once stack area for byval/varargs registers
2876   // was initialized, it can't be initialized again.
2877   if (ArgRegsSaveSize) {
2878
2879     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2880
2881     if (Padding) {
2882       assert(AFI->getStoredByValParamsPadding() == 0 &&
2883              "The only parameter may be padded.");
2884       AFI->setStoredByValParamsPadding(Padding);
2885     }
2886
2887     int FrameIndex = MFI->CreateFixedObject(
2888                       ArgRegsSaveSize,
2889                       Padding + ArgOffset,
2890                       false);
2891     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2892
2893     SmallVector<SDValue, 4> MemOps;
2894     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2895          ++firstRegToSaveIndex, ++i) {
2896       const TargetRegisterClass *RC;
2897       if (AFI->isThumb1OnlyFunction())
2898         RC = &ARM::tGPRRegClass;
2899       else
2900         RC = &ARM::GPRRegClass;
2901
2902       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2903       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2904       SDValue Store =
2905         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2906                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2907                      false, false, 0);
2908       MemOps.push_back(Store);
2909       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2910                         DAG.getConstant(4, getPointerTy()));
2911     }
2912
2913     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2914
2915     if (!MemOps.empty())
2916       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2917                           &MemOps[0], MemOps.size());
2918     return FrameIndex;
2919   } else
2920     // This will point to the next argument passed via stack.
2921     return MFI->CreateFixedObject(
2922         4, AFI->getStoredByValParamsPadding() + ArgOffset, !ForceMutable);
2923 }
2924
2925 // Setup stack frame, the va_list pointer will start from.
2926 void
2927 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2928                                         SDLoc dl, SDValue &Chain,
2929                                         unsigned ArgOffset,
2930                                         bool ForceMutable) const {
2931   MachineFunction &MF = DAG.getMachineFunction();
2932   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2933
2934   // Try to store any remaining integer argument regs
2935   // to their spots on the stack so that they may be loaded by deferencing
2936   // the result of va_next.
2937   // If there is no regs to be stored, just point address after last
2938   // argument passed via stack.
2939   int FrameIndex =
2940     StoreByValRegs(CCInfo, DAG, dl, Chain, 0, CCInfo.getInRegsParamsCount(),
2941                    0, ArgOffset, 0, ForceMutable);
2942
2943   AFI->setVarArgsFrameIndex(FrameIndex);
2944 }
2945
2946 SDValue
2947 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2948                                         CallingConv::ID CallConv, bool isVarArg,
2949                                         const SmallVectorImpl<ISD::InputArg>
2950                                           &Ins,
2951                                         SDLoc dl, SelectionDAG &DAG,
2952                                         SmallVectorImpl<SDValue> &InVals)
2953                                           const {
2954   MachineFunction &MF = DAG.getMachineFunction();
2955   MachineFrameInfo *MFI = MF.getFrameInfo();
2956
2957   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2958
2959   // Assign locations to all of the incoming arguments.
2960   SmallVector<CCValAssign, 16> ArgLocs;
2961   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2962                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2963   CCInfo.AnalyzeFormalArguments(Ins,
2964                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2965                                                   isVarArg));
2966
2967   SmallVector<SDValue, 16> ArgValues;
2968   int lastInsIndex = -1;
2969   SDValue ArgValue;
2970   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2971   unsigned CurArgIdx = 0;
2972
2973   // Initially ArgRegsSaveSize is zero.
2974   // Then we increase this value each time we meet byval parameter.
2975   // We also increase this value in case of varargs function.
2976   AFI->setArgRegsSaveSize(0);
2977
2978   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2979     CCValAssign &VA = ArgLocs[i];
2980     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2981     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2982     // Arguments stored in registers.
2983     if (VA.isRegLoc()) {
2984       EVT RegVT = VA.getLocVT();
2985
2986       if (VA.needsCustom()) {
2987         // f64 and vector types are split up into multiple registers or
2988         // combinations of registers and stack slots.
2989         if (VA.getLocVT() == MVT::v2f64) {
2990           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2991                                                    Chain, DAG, dl);
2992           VA = ArgLocs[++i]; // skip ahead to next loc
2993           SDValue ArgValue2;
2994           if (VA.isMemLoc()) {
2995             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2996             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2997             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2998                                     MachinePointerInfo::getFixedStack(FI),
2999                                     false, false, false, 0);
3000           } else {
3001             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3002                                              Chain, DAG, dl);
3003           }
3004           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3005           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3006                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3007           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3008                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3009         } else
3010           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3011
3012       } else {
3013         const TargetRegisterClass *RC;
3014
3015         if (RegVT == MVT::f32)
3016           RC = &ARM::SPRRegClass;
3017         else if (RegVT == MVT::f64)
3018           RC = &ARM::DPRRegClass;
3019         else if (RegVT == MVT::v2f64)
3020           RC = &ARM::QPRRegClass;
3021         else if (RegVT == MVT::i32)
3022           RC = AFI->isThumb1OnlyFunction() ?
3023             (const TargetRegisterClass*)&ARM::tGPRRegClass :
3024             (const TargetRegisterClass*)&ARM::GPRRegClass;
3025         else
3026           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3027
3028         // Transform the arguments in physical registers into virtual ones.
3029         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3030         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3031       }
3032
3033       // If this is an 8 or 16-bit value, it is really passed promoted
3034       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3035       // truncate to the right size.
3036       switch (VA.getLocInfo()) {
3037       default: llvm_unreachable("Unknown loc info!");
3038       case CCValAssign::Full: break;
3039       case CCValAssign::BCvt:
3040         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3041         break;
3042       case CCValAssign::SExt:
3043         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3044                                DAG.getValueType(VA.getValVT()));
3045         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3046         break;
3047       case CCValAssign::ZExt:
3048         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3049                                DAG.getValueType(VA.getValVT()));
3050         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3051         break;
3052       }
3053
3054       InVals.push_back(ArgValue);
3055
3056     } else { // VA.isRegLoc()
3057
3058       // sanity check
3059       assert(VA.isMemLoc());
3060       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3061
3062       int index = ArgLocs[i].getValNo();
3063
3064       // Some Ins[] entries become multiple ArgLoc[] entries.
3065       // Process them only once.
3066       if (index != lastInsIndex)
3067         {
3068           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3069           // FIXME: For now, all byval parameter objects are marked mutable.
3070           // This can be changed with more analysis.
3071           // In case of tail call optimization mark all arguments mutable.
3072           // Since they could be overwritten by lowering of arguments in case of
3073           // a tail call.
3074           if (Flags.isByVal()) {
3075             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3076             int FrameIndex = StoreByValRegs(
3077                 CCInfo, DAG, dl, Chain, CurOrigArg,
3078                 CurByValIndex,
3079                 Ins[VA.getValNo()].PartOffset,
3080                 VA.getLocMemOffset(),
3081                 Flags.getByValSize(),
3082                 true /*force mutable frames*/);
3083             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3084             CCInfo.nextInRegsParam();
3085           } else {
3086             unsigned FIOffset = VA.getLocMemOffset() +
3087                                 AFI->getStoredByValParamsPadding();
3088             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3089                                             FIOffset, true);
3090
3091             // Create load nodes to retrieve arguments from the stack.
3092             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3093             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3094                                          MachinePointerInfo::getFixedStack(FI),
3095                                          false, false, false, 0));
3096           }
3097           lastInsIndex = index;
3098         }
3099     }
3100   }
3101
3102   // varargs
3103   if (isVarArg)
3104     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3105                          CCInfo.getNextStackOffset());
3106
3107   return Chain;
3108 }
3109
3110 /// isFloatingPointZero - Return true if this is +0.0.
3111 static bool isFloatingPointZero(SDValue Op) {
3112   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3113     return CFP->getValueAPF().isPosZero();
3114   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3115     // Maybe this has already been legalized into the constant pool?
3116     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3117       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3118       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3119         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3120           return CFP->getValueAPF().isPosZero();
3121     }
3122   }
3123   return false;
3124 }
3125
3126 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3127 /// the given operands.
3128 SDValue
3129 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3130                              SDValue &ARMcc, SelectionDAG &DAG,
3131                              SDLoc dl) const {
3132   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3133     unsigned C = RHSC->getZExtValue();
3134     if (!isLegalICmpImmediate(C)) {
3135       // Constant does not fit, try adjusting it by one?
3136       switch (CC) {
3137       default: break;
3138       case ISD::SETLT:
3139       case ISD::SETGE:
3140         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3141           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3142           RHS = DAG.getConstant(C-1, MVT::i32);
3143         }
3144         break;
3145       case ISD::SETULT:
3146       case ISD::SETUGE:
3147         if (C != 0 && isLegalICmpImmediate(C-1)) {
3148           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3149           RHS = DAG.getConstant(C-1, MVT::i32);
3150         }
3151         break;
3152       case ISD::SETLE:
3153       case ISD::SETGT:
3154         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3155           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3156           RHS = DAG.getConstant(C+1, MVT::i32);
3157         }
3158         break;
3159       case ISD::SETULE:
3160       case ISD::SETUGT:
3161         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3162           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3163           RHS = DAG.getConstant(C+1, MVT::i32);
3164         }
3165         break;
3166       }
3167     }
3168   }
3169
3170   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3171   ARMISD::NodeType CompareType;
3172   switch (CondCode) {
3173   default:
3174     CompareType = ARMISD::CMP;
3175     break;
3176   case ARMCC::EQ:
3177   case ARMCC::NE:
3178     // Uses only Z Flag
3179     CompareType = ARMISD::CMPZ;
3180     break;
3181   }
3182   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3183   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3184 }
3185
3186 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3187 SDValue
3188 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3189                              SDLoc dl) const {
3190   SDValue Cmp;
3191   if (!isFloatingPointZero(RHS))
3192     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3193   else
3194     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3195   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3196 }
3197
3198 /// duplicateCmp - Glue values can have only one use, so this function
3199 /// duplicates a comparison node.
3200 SDValue
3201 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3202   unsigned Opc = Cmp.getOpcode();
3203   SDLoc DL(Cmp);
3204   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3205     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3206
3207   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3208   Cmp = Cmp.getOperand(0);
3209   Opc = Cmp.getOpcode();
3210   if (Opc == ARMISD::CMPFP)
3211     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3212   else {
3213     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3214     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3215   }
3216   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3217 }
3218
3219 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3220   SDValue Cond = Op.getOperand(0);
3221   SDValue SelectTrue = Op.getOperand(1);
3222   SDValue SelectFalse = Op.getOperand(2);
3223   SDLoc dl(Op);
3224
3225   // Convert:
3226   //
3227   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3228   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3229   //
3230   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3231     const ConstantSDNode *CMOVTrue =
3232       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3233     const ConstantSDNode *CMOVFalse =
3234       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3235
3236     if (CMOVTrue && CMOVFalse) {
3237       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3238       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3239
3240       SDValue True;
3241       SDValue False;
3242       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3243         True = SelectTrue;
3244         False = SelectFalse;
3245       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3246         True = SelectFalse;
3247         False = SelectTrue;
3248       }
3249
3250       if (True.getNode() && False.getNode()) {
3251         EVT VT = Op.getValueType();
3252         SDValue ARMcc = Cond.getOperand(2);
3253         SDValue CCR = Cond.getOperand(3);
3254         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3255         assert(True.getValueType() == VT);
3256         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3257       }
3258     }
3259   }
3260
3261   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3262   // undefined bits before doing a full-word comparison with zero.
3263   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3264                      DAG.getConstant(1, Cond.getValueType()));
3265
3266   return DAG.getSelectCC(dl, Cond,
3267                          DAG.getConstant(0, Cond.getValueType()),
3268                          SelectTrue, SelectFalse, ISD::SETNE);
3269 }
3270
3271 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3272   if (CC == ISD::SETNE)
3273     return ISD::SETEQ;
3274   return ISD::getSetCCSwappedOperands(CC);
3275 }
3276
3277 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3278                                  bool &swpCmpOps, bool &swpVselOps) {
3279   // Start by selecting the GE condition code for opcodes that return true for
3280   // 'equality'
3281   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3282       CC == ISD::SETULE)
3283     CondCode = ARMCC::GE;
3284
3285   // and GT for opcodes that return false for 'equality'.
3286   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3287            CC == ISD::SETULT)
3288     CondCode = ARMCC::GT;
3289
3290   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3291   // to swap the compare operands.
3292   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3293       CC == ISD::SETULT)
3294     swpCmpOps = true;
3295
3296   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3297   // If we have an unordered opcode, we need to swap the operands to the VSEL
3298   // instruction (effectively negating the condition).
3299   //
3300   // This also has the effect of swapping which one of 'less' or 'greater'
3301   // returns true, so we also swap the compare operands. It also switches
3302   // whether we return true for 'equality', so we compensate by picking the
3303   // opposite condition code to our original choice.
3304   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3305       CC == ISD::SETUGT) {
3306     swpCmpOps = !swpCmpOps;
3307     swpVselOps = !swpVselOps;
3308     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3309   }
3310
3311   // 'ordered' is 'anything but unordered', so use the VS condition code and
3312   // swap the VSEL operands.
3313   if (CC == ISD::SETO) {
3314     CondCode = ARMCC::VS;
3315     swpVselOps = true;
3316   }
3317
3318   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3319   // code and swap the VSEL operands.
3320   if (CC == ISD::SETUNE) {
3321     CondCode = ARMCC::EQ;
3322     swpVselOps = true;
3323   }
3324 }
3325
3326 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3327   EVT VT = Op.getValueType();
3328   SDValue LHS = Op.getOperand(0);
3329   SDValue RHS = Op.getOperand(1);
3330   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3331   SDValue TrueVal = Op.getOperand(2);
3332   SDValue FalseVal = Op.getOperand(3);
3333   SDLoc dl(Op);
3334
3335   if (LHS.getValueType() == MVT::i32) {
3336     // Try to generate VSEL on ARMv8.
3337     // The VSEL instruction can't use all the usual ARM condition
3338     // codes: it only has two bits to select the condition code, so it's
3339     // constrained to use only GE, GT, VS and EQ.
3340     //
3341     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3342     // swap the operands of the previous compare instruction (effectively
3343     // inverting the compare condition, swapping 'less' and 'greater') and
3344     // sometimes need to swap the operands to the VSEL (which inverts the
3345     // condition in the sense of firing whenever the previous condition didn't)
3346     if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3347                                       TrueVal.getValueType() == MVT::f64)) {
3348       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3349       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3350           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3351         CC = getInverseCCForVSEL(CC);
3352         std::swap(TrueVal, FalseVal);
3353       }
3354     }
3355
3356     SDValue ARMcc;
3357     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3358     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3359     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3360                        Cmp);
3361   }
3362
3363   ARMCC::CondCodes CondCode, CondCode2;
3364   FPCCToARMCC(CC, CondCode, CondCode2);
3365
3366   // Try to generate VSEL on ARMv8.
3367   if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3368                                     TrueVal.getValueType() == MVT::f64)) {
3369     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3370     // same operands, as follows:
3371     //   c = fcmp [ogt, olt, ugt, ult] a, b
3372     //   select c, a, b
3373     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3374     // handled differently than the original code sequence.
3375     if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3376         RHS == FalseVal) {
3377       if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3378         return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3379       if (CC == ISD::SETOLT || CC == ISD::SETULT)
3380         return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3381     }
3382
3383     bool swpCmpOps = false;
3384     bool swpVselOps = false;
3385     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3386
3387     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3388         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3389       if (swpCmpOps)
3390         std::swap(LHS, RHS);
3391       if (swpVselOps)
3392         std::swap(TrueVal, FalseVal);
3393     }
3394   }
3395
3396   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3397   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3398   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3399   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3400                                ARMcc, CCR, Cmp);
3401   if (CondCode2 != ARMCC::AL) {
3402     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3403     // FIXME: Needs another CMP because flag can have but one use.
3404     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3405     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3406                          Result, TrueVal, ARMcc2, CCR, Cmp2);
3407   }
3408   return Result;
3409 }
3410
3411 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3412 /// to morph to an integer compare sequence.
3413 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3414                            const ARMSubtarget *Subtarget) {
3415   SDNode *N = Op.getNode();
3416   if (!N->hasOneUse())
3417     // Otherwise it requires moving the value from fp to integer registers.
3418     return false;
3419   if (!N->getNumValues())
3420     return false;
3421   EVT VT = Op.getValueType();
3422   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3423     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3424     // vmrs are very slow, e.g. cortex-a8.
3425     return false;
3426
3427   if (isFloatingPointZero(Op)) {
3428     SeenZero = true;
3429     return true;
3430   }
3431   return ISD::isNormalLoad(N);
3432 }
3433
3434 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3435   if (isFloatingPointZero(Op))
3436     return DAG.getConstant(0, MVT::i32);
3437
3438   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3439     return DAG.getLoad(MVT::i32, SDLoc(Op),
3440                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3441                        Ld->isVolatile(), Ld->isNonTemporal(),
3442                        Ld->isInvariant(), Ld->getAlignment());
3443
3444   llvm_unreachable("Unknown VFP cmp argument!");
3445 }
3446
3447 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3448                            SDValue &RetVal1, SDValue &RetVal2) {
3449   if (isFloatingPointZero(Op)) {
3450     RetVal1 = DAG.getConstant(0, MVT::i32);
3451     RetVal2 = DAG.getConstant(0, MVT::i32);
3452     return;
3453   }
3454
3455   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3456     SDValue Ptr = Ld->getBasePtr();
3457     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3458                           Ld->getChain(), Ptr,
3459                           Ld->getPointerInfo(),
3460                           Ld->isVolatile(), Ld->isNonTemporal(),
3461                           Ld->isInvariant(), Ld->getAlignment());
3462
3463     EVT PtrType = Ptr.getValueType();
3464     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3465     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3466                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3467     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3468                           Ld->getChain(), NewPtr,
3469                           Ld->getPointerInfo().getWithOffset(4),
3470                           Ld->isVolatile(), Ld->isNonTemporal(),
3471                           Ld->isInvariant(), NewAlign);
3472     return;
3473   }
3474
3475   llvm_unreachable("Unknown VFP cmp argument!");
3476 }
3477
3478 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3479 /// f32 and even f64 comparisons to integer ones.
3480 SDValue
3481 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3482   SDValue Chain = Op.getOperand(0);
3483   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3484   SDValue LHS = Op.getOperand(2);
3485   SDValue RHS = Op.getOperand(3);
3486   SDValue Dest = Op.getOperand(4);
3487   SDLoc dl(Op);
3488
3489   bool LHSSeenZero = false;
3490   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3491   bool RHSSeenZero = false;
3492   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3493   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3494     // If unsafe fp math optimization is enabled and there are no other uses of
3495     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3496     // to an integer comparison.
3497     if (CC == ISD::SETOEQ)
3498       CC = ISD::SETEQ;
3499     else if (CC == ISD::SETUNE)
3500       CC = ISD::SETNE;
3501
3502     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3503     SDValue ARMcc;
3504     if (LHS.getValueType() == MVT::f32) {
3505       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3506                         bitcastf32Toi32(LHS, DAG), Mask);
3507       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3508                         bitcastf32Toi32(RHS, DAG), Mask);
3509       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3510       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3511       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3512                          Chain, Dest, ARMcc, CCR, Cmp);
3513     }
3514
3515     SDValue LHS1, LHS2;
3516     SDValue RHS1, RHS2;
3517     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3518     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3519     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3520     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3521     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3522     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3523     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3524     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3525     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3526   }
3527
3528   return SDValue();
3529 }
3530
3531 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3532   SDValue Chain = Op.getOperand(0);
3533   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3534   SDValue LHS = Op.getOperand(2);
3535   SDValue RHS = Op.getOperand(3);
3536   SDValue Dest = Op.getOperand(4);
3537   SDLoc dl(Op);
3538
3539   if (LHS.getValueType() == MVT::i32) {
3540     SDValue ARMcc;
3541     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3542     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3543     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3544                        Chain, Dest, ARMcc, CCR, Cmp);
3545   }
3546
3547   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3548
3549   if (getTargetMachine().Options.UnsafeFPMath &&
3550       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3551        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3552     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3553     if (Result.getNode())
3554       return Result;
3555   }
3556
3557   ARMCC::CondCodes CondCode, CondCode2;
3558   FPCCToARMCC(CC, CondCode, CondCode2);
3559
3560   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3561   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3562   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3563   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3564   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3565   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3566   if (CondCode2 != ARMCC::AL) {
3567     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3568     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3569     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3570   }
3571   return Res;
3572 }
3573
3574 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3575   SDValue Chain = Op.getOperand(0);
3576   SDValue Table = Op.getOperand(1);
3577   SDValue Index = Op.getOperand(2);
3578   SDLoc dl(Op);
3579
3580   EVT PTy = getPointerTy();
3581   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3582   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3583   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3584   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3585   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3586   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3587   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3588   if (Subtarget->isThumb2()) {
3589     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3590     // which does another jump to the destination. This also makes it easier
3591     // to translate it to TBB / TBH later.
3592     // FIXME: This might not work if the function is extremely large.
3593     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3594                        Addr, Op.getOperand(2), JTI, UId);
3595   }
3596   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3597     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3598                        MachinePointerInfo::getJumpTable(),
3599                        false, false, false, 0);
3600     Chain = Addr.getValue(1);
3601     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3602     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3603   } else {
3604     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3605                        MachinePointerInfo::getJumpTable(),
3606                        false, false, false, 0);
3607     Chain = Addr.getValue(1);
3608     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3609   }
3610 }
3611
3612 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3613   EVT VT = Op.getValueType();
3614   SDLoc dl(Op);
3615
3616   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3617     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3618       return Op;
3619     return DAG.UnrollVectorOp(Op.getNode());
3620   }
3621
3622   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3623          "Invalid type for custom lowering!");
3624   if (VT != MVT::v4i16)
3625     return DAG.UnrollVectorOp(Op.getNode());
3626
3627   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3628   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3629 }
3630
3631 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3632   EVT VT = Op.getValueType();
3633   if (VT.isVector())
3634     return LowerVectorFP_TO_INT(Op, DAG);
3635
3636   SDLoc dl(Op);
3637   unsigned Opc;
3638
3639   switch (Op.getOpcode()) {
3640   default: llvm_unreachable("Invalid opcode!");
3641   case ISD::FP_TO_SINT:
3642     Opc = ARMISD::FTOSI;
3643     break;
3644   case ISD::FP_TO_UINT:
3645     Opc = ARMISD::FTOUI;
3646     break;
3647   }
3648   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3649   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3650 }
3651
3652 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3653   EVT VT = Op.getValueType();
3654   SDLoc dl(Op);
3655
3656   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3657     if (VT.getVectorElementType() == MVT::f32)
3658       return Op;
3659     return DAG.UnrollVectorOp(Op.getNode());
3660   }
3661
3662   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3663          "Invalid type for custom lowering!");
3664   if (VT != MVT::v4f32)
3665     return DAG.UnrollVectorOp(Op.getNode());
3666
3667   unsigned CastOpc;
3668   unsigned Opc;
3669   switch (Op.getOpcode()) {
3670   default: llvm_unreachable("Invalid opcode!");
3671   case ISD::SINT_TO_FP:
3672     CastOpc = ISD::SIGN_EXTEND;
3673     Opc = ISD::SINT_TO_FP;
3674     break;
3675   case ISD::UINT_TO_FP:
3676     CastOpc = ISD::ZERO_EXTEND;
3677     Opc = ISD::UINT_TO_FP;
3678     break;
3679   }
3680
3681   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3682   return DAG.getNode(Opc, dl, VT, Op);
3683 }
3684
3685 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3686   EVT VT = Op.getValueType();
3687   if (VT.isVector())
3688     return LowerVectorINT_TO_FP(Op, DAG);
3689
3690   SDLoc dl(Op);
3691   unsigned Opc;
3692
3693   switch (Op.getOpcode()) {
3694   default: llvm_unreachable("Invalid opcode!");
3695   case ISD::SINT_TO_FP:
3696     Opc = ARMISD::SITOF;
3697     break;
3698   case ISD::UINT_TO_FP:
3699     Opc = ARMISD::UITOF;
3700     break;
3701   }
3702
3703   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3704   return DAG.getNode(Opc, dl, VT, Op);
3705 }
3706
3707 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3708   // Implement fcopysign with a fabs and a conditional fneg.
3709   SDValue Tmp0 = Op.getOperand(0);
3710   SDValue Tmp1 = Op.getOperand(1);
3711   SDLoc dl(Op);
3712   EVT VT = Op.getValueType();
3713   EVT SrcVT = Tmp1.getValueType();
3714   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3715     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3716   bool UseNEON = !InGPR && Subtarget->hasNEON();
3717
3718   if (UseNEON) {
3719     // Use VBSL to copy the sign bit.
3720     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3721     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3722                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3723     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3724     if (VT == MVT::f64)
3725       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3726                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3727                          DAG.getConstant(32, MVT::i32));
3728     else /*if (VT == MVT::f32)*/
3729       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3730     if (SrcVT == MVT::f32) {
3731       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3732       if (VT == MVT::f64)
3733         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3734                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3735                            DAG.getConstant(32, MVT::i32));
3736     } else if (VT == MVT::f32)
3737       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3738                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3739                          DAG.getConstant(32, MVT::i32));
3740     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3741     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3742
3743     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3744                                             MVT::i32);
3745     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3746     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3747                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3748
3749     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3750                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3751                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3752     if (VT == MVT::f32) {
3753       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3754       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3755                         DAG.getConstant(0, MVT::i32));
3756     } else {
3757       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3758     }
3759
3760     return Res;
3761   }
3762
3763   // Bitcast operand 1 to i32.
3764   if (SrcVT == MVT::f64)
3765     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3766                        &Tmp1, 1).getValue(1);
3767   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3768
3769   // Or in the signbit with integer operations.
3770   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3771   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3772   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3773   if (VT == MVT::f32) {
3774     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3775                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3776     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3777                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3778   }
3779
3780   // f64: Or the high part with signbit and then combine two parts.
3781   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3782                      &Tmp0, 1);
3783   SDValue Lo = Tmp0.getValue(0);
3784   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3785   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3786   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3787 }
3788
3789 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3790   MachineFunction &MF = DAG.getMachineFunction();
3791   MachineFrameInfo *MFI = MF.getFrameInfo();
3792   MFI->setReturnAddressIsTaken(true);
3793
3794   EVT VT = Op.getValueType();
3795   SDLoc dl(Op);
3796   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3797   if (Depth) {
3798     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3799     SDValue Offset = DAG.getConstant(4, MVT::i32);
3800     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3801                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3802                        MachinePointerInfo(), false, false, false, 0);
3803   }
3804
3805   // Return LR, which contains the return address. Mark it an implicit live-in.
3806   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3807   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3808 }
3809
3810 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3811   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3812   MFI->setFrameAddressIsTaken(true);
3813
3814   EVT VT = Op.getValueType();
3815   SDLoc dl(Op);  // FIXME probably not meaningful
3816   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3817   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3818     ? ARM::R7 : ARM::R11;
3819   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3820   while (Depth--)
3821     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3822                             MachinePointerInfo(),
3823                             false, false, false, 0);
3824   return FrameAddr;
3825 }
3826
3827 /// Custom Expand long vector extensions, where size(DestVec) > 2*size(SrcVec),
3828 /// and size(DestVec) > 128-bits.
3829 /// This is achieved by doing the one extension from the SrcVec, splitting the
3830 /// result, extending these parts, and then concatenating these into the
3831 /// destination.
3832 static SDValue ExpandVectorExtension(SDNode *N, SelectionDAG &DAG) {
3833   SDValue Op = N->getOperand(0);
3834   EVT SrcVT = Op.getValueType();
3835   EVT DestVT = N->getValueType(0);
3836
3837   assert(DestVT.getSizeInBits() > 128 &&
3838          "Custom sext/zext expansion needs >128-bit vector.");
3839   // If this is a normal length extension, use the default expansion.
3840   if (SrcVT.getSizeInBits()*4 != DestVT.getSizeInBits() &&
3841       SrcVT.getSizeInBits()*8 != DestVT.getSizeInBits())
3842     return SDValue();
3843
3844   SDLoc dl(N);
3845   unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
3846   unsigned DestEltSize = DestVT.getVectorElementType().getSizeInBits();
3847   unsigned NumElts = SrcVT.getVectorNumElements();
3848   LLVMContext &Ctx = *DAG.getContext();
3849   SDValue Mid, SplitLo, SplitHi, ExtLo, ExtHi;
3850
3851   EVT MidVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3852                                NumElts);
3853   EVT SplitVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3854                                  NumElts/2);
3855   EVT ExtVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, DestEltSize),
3856                                NumElts/2);
3857
3858   Mid = DAG.getNode(N->getOpcode(), dl, MidVT, Op);
3859   SplitLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3860                         DAG.getIntPtrConstant(0));
3861   SplitHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3862                         DAG.getIntPtrConstant(NumElts/2));
3863   ExtLo = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitLo);
3864   ExtHi = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitHi);
3865   return DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, ExtLo, ExtHi);
3866 }
3867
3868 /// ExpandBITCAST - If the target supports VFP, this function is called to
3869 /// expand a bit convert where either the source or destination type is i64 to
3870 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3871 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3872 /// vectors), since the legalizer won't know what to do with that.
3873 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3874   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3875   SDLoc dl(N);
3876   SDValue Op = N->getOperand(0);
3877
3878   // This function is only supposed to be called for i64 types, either as the
3879   // source or destination of the bit convert.
3880   EVT SrcVT = Op.getValueType();
3881   EVT DstVT = N->getValueType(0);
3882   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3883          "ExpandBITCAST called for non-i64 type");
3884
3885   // Turn i64->f64 into VMOVDRR.
3886   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3887     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3888                              DAG.getConstant(0, MVT::i32));
3889     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3890                              DAG.getConstant(1, MVT::i32));
3891     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3892                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3893   }
3894
3895   // Turn f64->i64 into VMOVRRD.
3896   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3897     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3898                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3899     // Merge the pieces into a single i64 value.
3900     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3901   }
3902
3903   return SDValue();
3904 }
3905
3906 /// getZeroVector - Returns a vector of specified type with all zero elements.
3907 /// Zero vectors are used to represent vector negation and in those cases
3908 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3909 /// not support i64 elements, so sometimes the zero vectors will need to be
3910 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3911 /// zero vector.
3912 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3913   assert(VT.isVector() && "Expected a vector type");
3914   // The canonical modified immediate encoding of a zero vector is....0!
3915   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3916   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3917   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3918   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3919 }
3920
3921 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3922 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3923 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3924                                                 SelectionDAG &DAG) const {
3925   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3926   EVT VT = Op.getValueType();
3927   unsigned VTBits = VT.getSizeInBits();
3928   SDLoc dl(Op);
3929   SDValue ShOpLo = Op.getOperand(0);
3930   SDValue ShOpHi = Op.getOperand(1);
3931   SDValue ShAmt  = Op.getOperand(2);
3932   SDValue ARMcc;
3933   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3934
3935   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3936
3937   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3938                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3939   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3940   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3941                                    DAG.getConstant(VTBits, MVT::i32));
3942   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3943   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3944   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3945
3946   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3947   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3948                           ARMcc, DAG, dl);
3949   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3950   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3951                            CCR, Cmp);
3952
3953   SDValue Ops[2] = { Lo, Hi };
3954   return DAG.getMergeValues(Ops, 2, dl);
3955 }
3956
3957 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3958 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3959 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3960                                                SelectionDAG &DAG) const {
3961   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3962   EVT VT = Op.getValueType();
3963   unsigned VTBits = VT.getSizeInBits();
3964   SDLoc dl(Op);
3965   SDValue ShOpLo = Op.getOperand(0);
3966   SDValue ShOpHi = Op.getOperand(1);
3967   SDValue ShAmt  = Op.getOperand(2);
3968   SDValue ARMcc;
3969
3970   assert(Op.getOpcode() == ISD::SHL_PARTS);
3971   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3972                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3973   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3974   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3975                                    DAG.getConstant(VTBits, MVT::i32));
3976   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3977   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3978
3979   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3980   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3981   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3982                           ARMcc, DAG, dl);
3983   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3984   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3985                            CCR, Cmp);
3986
3987   SDValue Ops[2] = { Lo, Hi };
3988   return DAG.getMergeValues(Ops, 2, dl);
3989 }
3990
3991 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3992                                             SelectionDAG &DAG) const {
3993   // The rounding mode is in bits 23:22 of the FPSCR.
3994   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3995   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3996   // so that the shift + and get folded into a bitfield extract.
3997   SDLoc dl(Op);
3998   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3999                               DAG.getConstant(Intrinsic::arm_get_fpscr,
4000                                               MVT::i32));
4001   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4002                                   DAG.getConstant(1U << 22, MVT::i32));
4003   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4004                               DAG.getConstant(22, MVT::i32));
4005   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4006                      DAG.getConstant(3, MVT::i32));
4007 }
4008
4009 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4010                          const ARMSubtarget *ST) {
4011   EVT VT = N->getValueType(0);
4012   SDLoc dl(N);
4013
4014   if (!ST->hasV6T2Ops())
4015     return SDValue();
4016
4017   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4018   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4019 }
4020
4021 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4022 /// for each 16-bit element from operand, repeated.  The basic idea is to
4023 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4024 ///
4025 /// Trace for v4i16:
4026 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4027 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4028 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4029 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4030 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4031 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4032 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4033 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4034 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4035   EVT VT = N->getValueType(0);
4036   SDLoc DL(N);
4037
4038   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4039   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4040   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4041   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4042   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4043   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4044 }
4045
4046 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4047 /// bit-count for each 16-bit element from the operand.  We need slightly
4048 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4049 /// 64/128-bit registers.
4050 ///
4051 /// Trace for v4i16:
4052 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4053 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4054 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4055 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4056 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4057   EVT VT = N->getValueType(0);
4058   SDLoc DL(N);
4059
4060   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4061   if (VT.is64BitVector()) {
4062     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4063     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4064                        DAG.getIntPtrConstant(0));
4065   } else {
4066     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4067                                     BitCounts, DAG.getIntPtrConstant(0));
4068     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4069   }
4070 }
4071
4072 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4073 /// bit-count for each 32-bit element from the operand.  The idea here is
4074 /// to split the vector into 16-bit elements, leverage the 16-bit count
4075 /// routine, and then combine the results.
4076 ///
4077 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4078 /// input    = [v0    v1    ] (vi: 32-bit elements)
4079 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4080 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4081 /// vrev: N0 = [k1 k0 k3 k2 ]
4082 ///            [k0 k1 k2 k3 ]
4083 ///       N1 =+[k1 k0 k3 k2 ]
4084 ///            [k0 k2 k1 k3 ]
4085 ///       N2 =+[k1 k3 k0 k2 ]
4086 ///            [k0    k2    k1    k3    ]
4087 /// Extended =+[k1    k3    k0    k2    ]
4088 ///            [k0    k2    ]
4089 /// Extracted=+[k1    k3    ]
4090 ///
4091 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4092   EVT VT = N->getValueType(0);
4093   SDLoc DL(N);
4094
4095   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4096
4097   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4098   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4099   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4100   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4101   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4102
4103   if (VT.is64BitVector()) {
4104     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4105     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4106                        DAG.getIntPtrConstant(0));
4107   } else {
4108     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4109                                     DAG.getIntPtrConstant(0));
4110     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4111   }
4112 }
4113
4114 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4115                           const ARMSubtarget *ST) {
4116   EVT VT = N->getValueType(0);
4117
4118   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4119   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4120           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4121          "Unexpected type for custom ctpop lowering");
4122
4123   if (VT.getVectorElementType() == MVT::i32)
4124     return lowerCTPOP32BitElements(N, DAG);
4125   else
4126     return lowerCTPOP16BitElements(N, DAG);
4127 }
4128
4129 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4130                           const ARMSubtarget *ST) {
4131   EVT VT = N->getValueType(0);
4132   SDLoc dl(N);
4133
4134   if (!VT.isVector())
4135     return SDValue();
4136
4137   // Lower vector shifts on NEON to use VSHL.
4138   assert(ST->hasNEON() && "unexpected vector shift");
4139
4140   // Left shifts translate directly to the vshiftu intrinsic.
4141   if (N->getOpcode() == ISD::SHL)
4142     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4143                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4144                        N->getOperand(0), N->getOperand(1));
4145
4146   assert((N->getOpcode() == ISD::SRA ||
4147           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4148
4149   // NEON uses the same intrinsics for both left and right shifts.  For
4150   // right shifts, the shift amounts are negative, so negate the vector of
4151   // shift amounts.
4152   EVT ShiftVT = N->getOperand(1).getValueType();
4153   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4154                                      getZeroVector(ShiftVT, DAG, dl),
4155                                      N->getOperand(1));
4156   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4157                              Intrinsic::arm_neon_vshifts :
4158                              Intrinsic::arm_neon_vshiftu);
4159   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4160                      DAG.getConstant(vshiftInt, MVT::i32),
4161                      N->getOperand(0), NegatedCount);
4162 }
4163
4164 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4165                                 const ARMSubtarget *ST) {
4166   EVT VT = N->getValueType(0);
4167   SDLoc dl(N);
4168
4169   // We can get here for a node like i32 = ISD::SHL i32, i64
4170   if (VT != MVT::i64)
4171     return SDValue();
4172
4173   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4174          "Unknown shift to lower!");
4175
4176   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4177   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4178       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4179     return SDValue();
4180
4181   // If we are in thumb mode, we don't have RRX.
4182   if (ST->isThumb1Only()) return SDValue();
4183
4184   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4185   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4186                            DAG.getConstant(0, MVT::i32));
4187   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4188                            DAG.getConstant(1, MVT::i32));
4189
4190   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4191   // captures the result into a carry flag.
4192   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4193   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
4194
4195   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4196   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4197
4198   // Merge the pieces into a single i64 value.
4199  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4200 }
4201
4202 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4203   SDValue TmpOp0, TmpOp1;
4204   bool Invert = false;
4205   bool Swap = false;
4206   unsigned Opc = 0;
4207
4208   SDValue Op0 = Op.getOperand(0);
4209   SDValue Op1 = Op.getOperand(1);
4210   SDValue CC = Op.getOperand(2);
4211   EVT VT = Op.getValueType();
4212   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4213   SDLoc dl(Op);
4214
4215   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4216     switch (SetCCOpcode) {
4217     default: llvm_unreachable("Illegal FP comparison");
4218     case ISD::SETUNE:
4219     case ISD::SETNE:  Invert = true; // Fallthrough
4220     case ISD::SETOEQ:
4221     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4222     case ISD::SETOLT:
4223     case ISD::SETLT: Swap = true; // Fallthrough
4224     case ISD::SETOGT:
4225     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4226     case ISD::SETOLE:
4227     case ISD::SETLE:  Swap = true; // Fallthrough
4228     case ISD::SETOGE:
4229     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4230     case ISD::SETUGE: Swap = true; // Fallthrough
4231     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4232     case ISD::SETUGT: Swap = true; // Fallthrough
4233     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4234     case ISD::SETUEQ: Invert = true; // Fallthrough
4235     case ISD::SETONE:
4236       // Expand this to (OLT | OGT).
4237       TmpOp0 = Op0;
4238       TmpOp1 = Op1;
4239       Opc = ISD::OR;
4240       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4241       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4242       break;
4243     case ISD::SETUO: Invert = true; // Fallthrough
4244     case ISD::SETO:
4245       // Expand this to (OLT | OGE).
4246       TmpOp0 = Op0;
4247       TmpOp1 = Op1;
4248       Opc = ISD::OR;
4249       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4250       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4251       break;
4252     }
4253   } else {
4254     // Integer comparisons.
4255     switch (SetCCOpcode) {
4256     default: llvm_unreachable("Illegal integer comparison");
4257     case ISD::SETNE:  Invert = true;
4258     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4259     case ISD::SETLT:  Swap = true;
4260     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4261     case ISD::SETLE:  Swap = true;
4262     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4263     case ISD::SETULT: Swap = true;
4264     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4265     case ISD::SETULE: Swap = true;
4266     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4267     }
4268
4269     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4270     if (Opc == ARMISD::VCEQ) {
4271
4272       SDValue AndOp;
4273       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4274         AndOp = Op0;
4275       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4276         AndOp = Op1;
4277
4278       // Ignore bitconvert.
4279       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4280         AndOp = AndOp.getOperand(0);
4281
4282       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4283         Opc = ARMISD::VTST;
4284         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4285         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4286         Invert = !Invert;
4287       }
4288     }
4289   }
4290
4291   if (Swap)
4292     std::swap(Op0, Op1);
4293
4294   // If one of the operands is a constant vector zero, attempt to fold the
4295   // comparison to a specialized compare-against-zero form.
4296   SDValue SingleOp;
4297   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4298     SingleOp = Op0;
4299   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4300     if (Opc == ARMISD::VCGE)
4301       Opc = ARMISD::VCLEZ;
4302     else if (Opc == ARMISD::VCGT)
4303       Opc = ARMISD::VCLTZ;
4304     SingleOp = Op1;
4305   }
4306
4307   SDValue Result;
4308   if (SingleOp.getNode()) {
4309     switch (Opc) {
4310     case ARMISD::VCEQ:
4311       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4312     case ARMISD::VCGE:
4313       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4314     case ARMISD::VCLEZ:
4315       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4316     case ARMISD::VCGT:
4317       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4318     case ARMISD::VCLTZ:
4319       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4320     default:
4321       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4322     }
4323   } else {
4324      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4325   }
4326
4327   if (Invert)
4328     Result = DAG.getNOT(dl, Result, VT);
4329
4330   return Result;
4331 }
4332
4333 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4334 /// valid vector constant for a NEON instruction with a "modified immediate"
4335 /// operand (e.g., VMOV).  If so, return the encoded value.
4336 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4337                                  unsigned SplatBitSize, SelectionDAG &DAG,
4338                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4339   unsigned OpCmode, Imm;
4340
4341   // SplatBitSize is set to the smallest size that splats the vector, so a
4342   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4343   // immediate instructions others than VMOV do not support the 8-bit encoding
4344   // of a zero vector, and the default encoding of zero is supposed to be the
4345   // 32-bit version.
4346   if (SplatBits == 0)
4347     SplatBitSize = 32;
4348
4349   switch (SplatBitSize) {
4350   case 8:
4351     if (type != VMOVModImm)
4352       return SDValue();
4353     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4354     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4355     OpCmode = 0xe;
4356     Imm = SplatBits;
4357     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4358     break;
4359
4360   case 16:
4361     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4362     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4363     if ((SplatBits & ~0xff) == 0) {
4364       // Value = 0x00nn: Op=x, Cmode=100x.
4365       OpCmode = 0x8;
4366       Imm = SplatBits;
4367       break;
4368     }
4369     if ((SplatBits & ~0xff00) == 0) {
4370       // Value = 0xnn00: Op=x, Cmode=101x.
4371       OpCmode = 0xa;
4372       Imm = SplatBits >> 8;
4373       break;
4374     }
4375     return SDValue();
4376
4377   case 32:
4378     // NEON's 32-bit VMOV supports splat values where:
4379     // * only one byte is nonzero, or
4380     // * the least significant byte is 0xff and the second byte is nonzero, or
4381     // * the least significant 2 bytes are 0xff and the third is nonzero.
4382     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4383     if ((SplatBits & ~0xff) == 0) {
4384       // Value = 0x000000nn: Op=x, Cmode=000x.
4385       OpCmode = 0;
4386       Imm = SplatBits;
4387       break;
4388     }
4389     if ((SplatBits & ~0xff00) == 0) {
4390       // Value = 0x0000nn00: Op=x, Cmode=001x.
4391       OpCmode = 0x2;
4392       Imm = SplatBits >> 8;
4393       break;
4394     }
4395     if ((SplatBits & ~0xff0000) == 0) {
4396       // Value = 0x00nn0000: Op=x, Cmode=010x.
4397       OpCmode = 0x4;
4398       Imm = SplatBits >> 16;
4399       break;
4400     }
4401     if ((SplatBits & ~0xff000000) == 0) {
4402       // Value = 0xnn000000: Op=x, Cmode=011x.
4403       OpCmode = 0x6;
4404       Imm = SplatBits >> 24;
4405       break;
4406     }
4407
4408     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4409     if (type == OtherModImm) return SDValue();
4410
4411     if ((SplatBits & ~0xffff) == 0 &&
4412         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4413       // Value = 0x0000nnff: Op=x, Cmode=1100.
4414       OpCmode = 0xc;
4415       Imm = SplatBits >> 8;
4416       SplatBits |= 0xff;
4417       break;
4418     }
4419
4420     if ((SplatBits & ~0xffffff) == 0 &&
4421         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4422       // Value = 0x00nnffff: Op=x, Cmode=1101.
4423       OpCmode = 0xd;
4424       Imm = SplatBits >> 16;
4425       SplatBits |= 0xffff;
4426       break;
4427     }
4428
4429     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4430     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4431     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4432     // and fall through here to test for a valid 64-bit splat.  But, then the
4433     // caller would also need to check and handle the change in size.
4434     return SDValue();
4435
4436   case 64: {
4437     if (type != VMOVModImm)
4438       return SDValue();
4439     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4440     uint64_t BitMask = 0xff;
4441     uint64_t Val = 0;
4442     unsigned ImmMask = 1;
4443     Imm = 0;
4444     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4445       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4446         Val |= BitMask;
4447         Imm |= ImmMask;
4448       } else if ((SplatBits & BitMask) != 0) {
4449         return SDValue();
4450       }
4451       BitMask <<= 8;
4452       ImmMask <<= 1;
4453     }
4454     // Op=1, Cmode=1110.
4455     OpCmode = 0x1e;
4456     SplatBits = Val;
4457     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4458     break;
4459   }
4460
4461   default:
4462     llvm_unreachable("unexpected size for isNEONModifiedImm");
4463   }
4464
4465   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4466   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4467 }
4468
4469 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4470                                            const ARMSubtarget *ST) const {
4471   if (!ST->hasVFP3())
4472     return SDValue();
4473
4474   bool IsDouble = Op.getValueType() == MVT::f64;
4475   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4476
4477   // Try splatting with a VMOV.f32...
4478   APFloat FPVal = CFP->getValueAPF();
4479   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4480
4481   if (ImmVal != -1) {
4482     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4483       // We have code in place to select a valid ConstantFP already, no need to
4484       // do any mangling.
4485       return Op;
4486     }
4487
4488     // It's a float and we are trying to use NEON operations where
4489     // possible. Lower it to a splat followed by an extract.
4490     SDLoc DL(Op);
4491     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4492     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4493                                       NewVal);
4494     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4495                        DAG.getConstant(0, MVT::i32));
4496   }
4497
4498   // The rest of our options are NEON only, make sure that's allowed before
4499   // proceeding..
4500   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4501     return SDValue();
4502
4503   EVT VMovVT;
4504   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4505
4506   // It wouldn't really be worth bothering for doubles except for one very
4507   // important value, which does happen to match: 0.0. So make sure we don't do
4508   // anything stupid.
4509   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4510     return SDValue();
4511
4512   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4513   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4514                                      false, VMOVModImm);
4515   if (NewVal != SDValue()) {
4516     SDLoc DL(Op);
4517     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4518                                       NewVal);
4519     if (IsDouble)
4520       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4521
4522     // It's a float: cast and extract a vector element.
4523     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4524                                        VecConstant);
4525     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4526                        DAG.getConstant(0, MVT::i32));
4527   }
4528
4529   // Finally, try a VMVN.i32
4530   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4531                              false, VMVNModImm);
4532   if (NewVal != SDValue()) {
4533     SDLoc DL(Op);
4534     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4535
4536     if (IsDouble)
4537       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4538
4539     // It's a float: cast and extract a vector element.
4540     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4541                                        VecConstant);
4542     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4543                        DAG.getConstant(0, MVT::i32));
4544   }
4545
4546   return SDValue();
4547 }
4548
4549 // check if an VEXT instruction can handle the shuffle mask when the
4550 // vector sources of the shuffle are the same.
4551 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4552   unsigned NumElts = VT.getVectorNumElements();
4553
4554   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4555   if (M[0] < 0)
4556     return false;
4557
4558   Imm = M[0];
4559
4560   // If this is a VEXT shuffle, the immediate value is the index of the first
4561   // element.  The other shuffle indices must be the successive elements after
4562   // the first one.
4563   unsigned ExpectedElt = Imm;
4564   for (unsigned i = 1; i < NumElts; ++i) {
4565     // Increment the expected index.  If it wraps around, just follow it
4566     // back to index zero and keep going.
4567     ++ExpectedElt;
4568     if (ExpectedElt == NumElts)
4569       ExpectedElt = 0;
4570
4571     if (M[i] < 0) continue; // ignore UNDEF indices
4572     if (ExpectedElt != static_cast<unsigned>(M[i]))
4573       return false;
4574   }
4575
4576   return true;
4577 }
4578
4579
4580 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4581                        bool &ReverseVEXT, unsigned &Imm) {
4582   unsigned NumElts = VT.getVectorNumElements();
4583   ReverseVEXT = false;
4584
4585   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4586   if (M[0] < 0)
4587     return false;
4588
4589   Imm = M[0];
4590
4591   // If this is a VEXT shuffle, the immediate value is the index of the first
4592   // element.  The other shuffle indices must be the successive elements after
4593   // the first one.
4594   unsigned ExpectedElt = Imm;
4595   for (unsigned i = 1; i < NumElts; ++i) {
4596     // Increment the expected index.  If it wraps around, it may still be
4597     // a VEXT but the source vectors must be swapped.
4598     ExpectedElt += 1;
4599     if (ExpectedElt == NumElts * 2) {
4600       ExpectedElt = 0;
4601       ReverseVEXT = true;
4602     }
4603
4604     if (M[i] < 0) continue; // ignore UNDEF indices
4605     if (ExpectedElt != static_cast<unsigned>(M[i]))
4606       return false;
4607   }
4608
4609   // Adjust the index value if the source operands will be swapped.
4610   if (ReverseVEXT)
4611     Imm -= NumElts;
4612
4613   return true;
4614 }
4615
4616 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4617 /// instruction with the specified blocksize.  (The order of the elements
4618 /// within each block of the vector is reversed.)
4619 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4620   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4621          "Only possible block sizes for VREV are: 16, 32, 64");
4622
4623   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4624   if (EltSz == 64)
4625     return false;
4626
4627   unsigned NumElts = VT.getVectorNumElements();
4628   unsigned BlockElts = M[0] + 1;
4629   // If the first shuffle index is UNDEF, be optimistic.
4630   if (M[0] < 0)
4631     BlockElts = BlockSize / EltSz;
4632
4633   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4634     return false;
4635
4636   for (unsigned i = 0; i < NumElts; ++i) {
4637     if (M[i] < 0) continue; // ignore UNDEF indices
4638     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4639       return false;
4640   }
4641
4642   return true;
4643 }
4644
4645 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4646   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4647   // range, then 0 is placed into the resulting vector. So pretty much any mask
4648   // of 8 elements can work here.
4649   return VT == MVT::v8i8 && M.size() == 8;
4650 }
4651
4652 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4653   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4654   if (EltSz == 64)
4655     return false;
4656
4657   unsigned NumElts = VT.getVectorNumElements();
4658   WhichResult = (M[0] == 0 ? 0 : 1);
4659   for (unsigned i = 0; i < NumElts; i += 2) {
4660     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4661         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4662       return false;
4663   }
4664   return true;
4665 }
4666
4667 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4668 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4669 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4670 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4671   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4672   if (EltSz == 64)
4673     return false;
4674
4675   unsigned NumElts = VT.getVectorNumElements();
4676   WhichResult = (M[0] == 0 ? 0 : 1);
4677   for (unsigned i = 0; i < NumElts; i += 2) {
4678     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4679         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4680       return false;
4681   }
4682   return true;
4683 }
4684
4685 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4686   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4687   if (EltSz == 64)
4688     return false;
4689
4690   unsigned NumElts = VT.getVectorNumElements();
4691   WhichResult = (M[0] == 0 ? 0 : 1);
4692   for (unsigned i = 0; i != NumElts; ++i) {
4693     if (M[i] < 0) continue; // ignore UNDEF indices
4694     if ((unsigned) M[i] != 2 * i + WhichResult)
4695       return false;
4696   }
4697
4698   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4699   if (VT.is64BitVector() && EltSz == 32)
4700     return false;
4701
4702   return true;
4703 }
4704
4705 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4706 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4707 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4708 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4709   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4710   if (EltSz == 64)
4711     return false;
4712
4713   unsigned Half = VT.getVectorNumElements() / 2;
4714   WhichResult = (M[0] == 0 ? 0 : 1);
4715   for (unsigned j = 0; j != 2; ++j) {
4716     unsigned Idx = WhichResult;
4717     for (unsigned i = 0; i != Half; ++i) {
4718       int MIdx = M[i + j * Half];
4719       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4720         return false;
4721       Idx += 2;
4722     }
4723   }
4724
4725   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4726   if (VT.is64BitVector() && EltSz == 32)
4727     return false;
4728
4729   return true;
4730 }
4731
4732 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4733   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4734   if (EltSz == 64)
4735     return false;
4736
4737   unsigned NumElts = VT.getVectorNumElements();
4738   WhichResult = (M[0] == 0 ? 0 : 1);
4739   unsigned Idx = WhichResult * NumElts / 2;
4740   for (unsigned i = 0; i != NumElts; i += 2) {
4741     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4742         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4743       return false;
4744     Idx += 1;
4745   }
4746
4747   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4748   if (VT.is64BitVector() && EltSz == 32)
4749     return false;
4750
4751   return true;
4752 }
4753
4754 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4755 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4756 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4757 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4758   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4759   if (EltSz == 64)
4760     return false;
4761
4762   unsigned NumElts = VT.getVectorNumElements();
4763   WhichResult = (M[0] == 0 ? 0 : 1);
4764   unsigned Idx = WhichResult * NumElts / 2;
4765   for (unsigned i = 0; i != NumElts; i += 2) {
4766     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4767         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4768       return false;
4769     Idx += 1;
4770   }
4771
4772   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4773   if (VT.is64BitVector() && EltSz == 32)
4774     return false;
4775
4776   return true;
4777 }
4778
4779 /// \return true if this is a reverse operation on an vector.
4780 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4781   unsigned NumElts = VT.getVectorNumElements();
4782   // Make sure the mask has the right size.
4783   if (NumElts != M.size())
4784       return false;
4785
4786   // Look for <15, ..., 3, -1, 1, 0>.
4787   for (unsigned i = 0; i != NumElts; ++i)
4788     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4789       return false;
4790
4791   return true;
4792 }
4793
4794 // If N is an integer constant that can be moved into a register in one
4795 // instruction, return an SDValue of such a constant (will become a MOV
4796 // instruction).  Otherwise return null.
4797 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4798                                      const ARMSubtarget *ST, SDLoc dl) {
4799   uint64_t Val;
4800   if (!isa<ConstantSDNode>(N))
4801     return SDValue();
4802   Val = cast<ConstantSDNode>(N)->getZExtValue();
4803
4804   if (ST->isThumb1Only()) {
4805     if (Val <= 255 || ~Val <= 255)
4806       return DAG.getConstant(Val, MVT::i32);
4807   } else {
4808     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4809       return DAG.getConstant(Val, MVT::i32);
4810   }
4811   return SDValue();
4812 }
4813
4814 // If this is a case we can't handle, return null and let the default
4815 // expansion code take care of it.
4816 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4817                                              const ARMSubtarget *ST) const {
4818   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4819   SDLoc dl(Op);
4820   EVT VT = Op.getValueType();
4821
4822   APInt SplatBits, SplatUndef;
4823   unsigned SplatBitSize;
4824   bool HasAnyUndefs;
4825   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4826     if (SplatBitSize <= 64) {
4827       // Check if an immediate VMOV works.
4828       EVT VmovVT;
4829       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4830                                       SplatUndef.getZExtValue(), SplatBitSize,
4831                                       DAG, VmovVT, VT.is128BitVector(),
4832                                       VMOVModImm);
4833       if (Val.getNode()) {
4834         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4835         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4836       }
4837
4838       // Try an immediate VMVN.
4839       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4840       Val = isNEONModifiedImm(NegatedImm,
4841                                       SplatUndef.getZExtValue(), SplatBitSize,
4842                                       DAG, VmovVT, VT.is128BitVector(),
4843                                       VMVNModImm);
4844       if (Val.getNode()) {
4845         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4846         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4847       }
4848
4849       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4850       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4851         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4852         if (ImmVal != -1) {
4853           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4854           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4855         }
4856       }
4857     }
4858   }
4859
4860   // Scan through the operands to see if only one value is used.
4861   //
4862   // As an optimisation, even if more than one value is used it may be more
4863   // profitable to splat with one value then change some lanes.
4864   //
4865   // Heuristically we decide to do this if the vector has a "dominant" value,
4866   // defined as splatted to more than half of the lanes.
4867   unsigned NumElts = VT.getVectorNumElements();
4868   bool isOnlyLowElement = true;
4869   bool usesOnlyOneValue = true;
4870   bool hasDominantValue = false;
4871   bool isConstant = true;
4872
4873   // Map of the number of times a particular SDValue appears in the
4874   // element list.
4875   DenseMap<SDValue, unsigned> ValueCounts;
4876   SDValue Value;
4877   for (unsigned i = 0; i < NumElts; ++i) {
4878     SDValue V = Op.getOperand(i);
4879     if (V.getOpcode() == ISD::UNDEF)
4880       continue;
4881     if (i > 0)
4882       isOnlyLowElement = false;
4883     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4884       isConstant = false;
4885
4886     ValueCounts.insert(std::make_pair(V, 0));
4887     unsigned &Count = ValueCounts[V];
4888
4889     // Is this value dominant? (takes up more than half of the lanes)
4890     if (++Count > (NumElts / 2)) {
4891       hasDominantValue = true;
4892       Value = V;
4893     }
4894   }
4895   if (ValueCounts.size() != 1)
4896     usesOnlyOneValue = false;
4897   if (!Value.getNode() && ValueCounts.size() > 0)
4898     Value = ValueCounts.begin()->first;
4899
4900   if (ValueCounts.size() == 0)
4901     return DAG.getUNDEF(VT);
4902
4903   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
4904   // Keep going if we are hitting this case.
4905   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
4906     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4907
4908   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4909
4910   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4911   // i32 and try again.
4912   if (hasDominantValue && EltSize <= 32) {
4913     if (!isConstant) {
4914       SDValue N;
4915
4916       // If we are VDUPing a value that comes directly from a vector, that will
4917       // cause an unnecessary move to and from a GPR, where instead we could
4918       // just use VDUPLANE. We can only do this if the lane being extracted
4919       // is at a constant index, as the VDUP from lane instructions only have
4920       // constant-index forms.
4921       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4922           isa<ConstantSDNode>(Value->getOperand(1))) {
4923         // We need to create a new undef vector to use for the VDUPLANE if the
4924         // size of the vector from which we get the value is different than the
4925         // size of the vector that we need to create. We will insert the element
4926         // such that the register coalescer will remove unnecessary copies.
4927         if (VT != Value->getOperand(0).getValueType()) {
4928           ConstantSDNode *constIndex;
4929           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4930           assert(constIndex && "The index is not a constant!");
4931           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4932                              VT.getVectorNumElements();
4933           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4934                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4935                         Value, DAG.getConstant(index, MVT::i32)),
4936                            DAG.getConstant(index, MVT::i32));
4937         } else
4938           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4939                         Value->getOperand(0), Value->getOperand(1));
4940       } else
4941         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4942
4943       if (!usesOnlyOneValue) {
4944         // The dominant value was splatted as 'N', but we now have to insert
4945         // all differing elements.
4946         for (unsigned I = 0; I < NumElts; ++I) {
4947           if (Op.getOperand(I) == Value)
4948             continue;
4949           SmallVector<SDValue, 3> Ops;
4950           Ops.push_back(N);
4951           Ops.push_back(Op.getOperand(I));
4952           Ops.push_back(DAG.getConstant(I, MVT::i32));
4953           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4954         }
4955       }
4956       return N;
4957     }
4958     if (VT.getVectorElementType().isFloatingPoint()) {
4959       SmallVector<SDValue, 8> Ops;
4960       for (unsigned i = 0; i < NumElts; ++i)
4961         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4962                                   Op.getOperand(i)));
4963       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4964       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4965       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4966       if (Val.getNode())
4967         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4968     }
4969     if (usesOnlyOneValue) {
4970       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4971       if (isConstant && Val.getNode())
4972         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4973     }
4974   }
4975
4976   // If all elements are constants and the case above didn't get hit, fall back
4977   // to the default expansion, which will generate a load from the constant
4978   // pool.
4979   if (isConstant)
4980     return SDValue();
4981
4982   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4983   if (NumElts >= 4) {
4984     SDValue shuffle = ReconstructShuffle(Op, DAG);
4985     if (shuffle != SDValue())
4986       return shuffle;
4987   }
4988
4989   // Vectors with 32- or 64-bit elements can be built by directly assigning
4990   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4991   // will be legalized.
4992   if (EltSize >= 32) {
4993     // Do the expansion with floating-point types, since that is what the VFP
4994     // registers are defined to use, and since i64 is not legal.
4995     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4996     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4997     SmallVector<SDValue, 8> Ops;
4998     for (unsigned i = 0; i < NumElts; ++i)
4999       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5000     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5001     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5002   }
5003
5004   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5005   // know the default expansion would otherwise fall back on something even
5006   // worse. For a vector with one or two non-undef values, that's
5007   // scalar_to_vector for the elements followed by a shuffle (provided the
5008   // shuffle is valid for the target) and materialization element by element
5009   // on the stack followed by a load for everything else.
5010   if (!isConstant && !usesOnlyOneValue) {
5011     SDValue Vec = DAG.getUNDEF(VT);
5012     for (unsigned i = 0 ; i < NumElts; ++i) {
5013       SDValue V = Op.getOperand(i);
5014       if (V.getOpcode() == ISD::UNDEF)
5015         continue;
5016       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5017       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5018     }
5019     return Vec;
5020   }
5021
5022   return SDValue();
5023 }
5024
5025 // Gather data to see if the operation can be modelled as a
5026 // shuffle in combination with VEXTs.
5027 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5028                                               SelectionDAG &DAG) const {
5029   SDLoc dl(Op);
5030   EVT VT = Op.getValueType();
5031   unsigned NumElts = VT.getVectorNumElements();
5032
5033   SmallVector<SDValue, 2> SourceVecs;
5034   SmallVector<unsigned, 2> MinElts;
5035   SmallVector<unsigned, 2> MaxElts;
5036
5037   for (unsigned i = 0; i < NumElts; ++i) {
5038     SDValue V = Op.getOperand(i);
5039     if (V.getOpcode() == ISD::UNDEF)
5040       continue;
5041     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5042       // A shuffle can only come from building a vector from various
5043       // elements of other vectors.
5044       return SDValue();
5045     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5046                VT.getVectorElementType()) {
5047       // This code doesn't know how to handle shuffles where the vector
5048       // element types do not match (this happens because type legalization
5049       // promotes the return type of EXTRACT_VECTOR_ELT).
5050       // FIXME: It might be appropriate to extend this code to handle
5051       // mismatched types.
5052       return SDValue();
5053     }
5054
5055     // Record this extraction against the appropriate vector if possible...
5056     SDValue SourceVec = V.getOperand(0);
5057     // If the element number isn't a constant, we can't effectively
5058     // analyze what's going on.
5059     if (!isa<ConstantSDNode>(V.getOperand(1)))
5060       return SDValue();
5061     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5062     bool FoundSource = false;
5063     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5064       if (SourceVecs[j] == SourceVec) {
5065         if (MinElts[j] > EltNo)
5066           MinElts[j] = EltNo;
5067         if (MaxElts[j] < EltNo)
5068           MaxElts[j] = EltNo;
5069         FoundSource = true;
5070         break;
5071       }
5072     }
5073
5074     // Or record a new source if not...
5075     if (!FoundSource) {
5076       SourceVecs.push_back(SourceVec);
5077       MinElts.push_back(EltNo);
5078       MaxElts.push_back(EltNo);
5079     }
5080   }
5081
5082   // Currently only do something sane when at most two source vectors
5083   // involved.
5084   if (SourceVecs.size() > 2)
5085     return SDValue();
5086
5087   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5088   int VEXTOffsets[2] = {0, 0};
5089
5090   // This loop extracts the usage patterns of the source vectors
5091   // and prepares appropriate SDValues for a shuffle if possible.
5092   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5093     if (SourceVecs[i].getValueType() == VT) {
5094       // No VEXT necessary
5095       ShuffleSrcs[i] = SourceVecs[i];
5096       VEXTOffsets[i] = 0;
5097       continue;
5098     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5099       // It probably isn't worth padding out a smaller vector just to
5100       // break it down again in a shuffle.
5101       return SDValue();
5102     }
5103
5104     // Since only 64-bit and 128-bit vectors are legal on ARM and
5105     // we've eliminated the other cases...
5106     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5107            "unexpected vector sizes in ReconstructShuffle");
5108
5109     if (MaxElts[i] - MinElts[i] >= NumElts) {
5110       // Span too large for a VEXT to cope
5111       return SDValue();
5112     }
5113
5114     if (MinElts[i] >= NumElts) {
5115       // The extraction can just take the second half
5116       VEXTOffsets[i] = NumElts;
5117       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5118                                    SourceVecs[i],
5119                                    DAG.getIntPtrConstant(NumElts));
5120     } else if (MaxElts[i] < NumElts) {
5121       // The extraction can just take the first half
5122       VEXTOffsets[i] = 0;
5123       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5124                                    SourceVecs[i],
5125                                    DAG.getIntPtrConstant(0));
5126     } else {
5127       // An actual VEXT is needed
5128       VEXTOffsets[i] = MinElts[i];
5129       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5130                                      SourceVecs[i],
5131                                      DAG.getIntPtrConstant(0));
5132       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5133                                      SourceVecs[i],
5134                                      DAG.getIntPtrConstant(NumElts));
5135       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5136                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5137     }
5138   }
5139
5140   SmallVector<int, 8> Mask;
5141
5142   for (unsigned i = 0; i < NumElts; ++i) {
5143     SDValue Entry = Op.getOperand(i);
5144     if (Entry.getOpcode() == ISD::UNDEF) {
5145       Mask.push_back(-1);
5146       continue;
5147     }
5148
5149     SDValue ExtractVec = Entry.getOperand(0);
5150     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5151                                           .getOperand(1))->getSExtValue();
5152     if (ExtractVec == SourceVecs[0]) {
5153       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5154     } else {
5155       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5156     }
5157   }
5158
5159   // Final check before we try to produce nonsense...
5160   if (isShuffleMaskLegal(Mask, VT))
5161     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5162                                 &Mask[0]);
5163
5164   return SDValue();
5165 }
5166
5167 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5168 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5169 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5170 /// are assumed to be legal.
5171 bool
5172 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5173                                       EVT VT) const {
5174   if (VT.getVectorNumElements() == 4 &&
5175       (VT.is128BitVector() || VT.is64BitVector())) {
5176     unsigned PFIndexes[4];
5177     for (unsigned i = 0; i != 4; ++i) {
5178       if (M[i] < 0)
5179         PFIndexes[i] = 8;
5180       else
5181         PFIndexes[i] = M[i];
5182     }
5183
5184     // Compute the index in the perfect shuffle table.
5185     unsigned PFTableIndex =
5186       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5187     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5188     unsigned Cost = (PFEntry >> 30);
5189
5190     if (Cost <= 4)
5191       return true;
5192   }
5193
5194   bool ReverseVEXT;
5195   unsigned Imm, WhichResult;
5196
5197   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5198   return (EltSize >= 32 ||
5199           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5200           isVREVMask(M, VT, 64) ||
5201           isVREVMask(M, VT, 32) ||
5202           isVREVMask(M, VT, 16) ||
5203           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5204           isVTBLMask(M, VT) ||
5205           isVTRNMask(M, VT, WhichResult) ||
5206           isVUZPMask(M, VT, WhichResult) ||
5207           isVZIPMask(M, VT, WhichResult) ||
5208           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5209           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5210           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5211           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5212 }
5213
5214 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5215 /// the specified operations to build the shuffle.
5216 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5217                                       SDValue RHS, SelectionDAG &DAG,
5218                                       SDLoc dl) {
5219   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5220   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5221   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5222
5223   enum {
5224     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5225     OP_VREV,
5226     OP_VDUP0,
5227     OP_VDUP1,
5228     OP_VDUP2,
5229     OP_VDUP3,
5230     OP_VEXT1,
5231     OP_VEXT2,
5232     OP_VEXT3,
5233     OP_VUZPL, // VUZP, left result
5234     OP_VUZPR, // VUZP, right result
5235     OP_VZIPL, // VZIP, left result
5236     OP_VZIPR, // VZIP, right result
5237     OP_VTRNL, // VTRN, left result
5238     OP_VTRNR  // VTRN, right result
5239   };
5240
5241   if (OpNum == OP_COPY) {
5242     if (LHSID == (1*9+2)*9+3) return LHS;
5243     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5244     return RHS;
5245   }
5246
5247   SDValue OpLHS, OpRHS;
5248   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5249   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5250   EVT VT = OpLHS.getValueType();
5251
5252   switch (OpNum) {
5253   default: llvm_unreachable("Unknown shuffle opcode!");
5254   case OP_VREV:
5255     // VREV divides the vector in half and swaps within the half.
5256     if (VT.getVectorElementType() == MVT::i32 ||
5257         VT.getVectorElementType() == MVT::f32)
5258       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5259     // vrev <4 x i16> -> VREV32
5260     if (VT.getVectorElementType() == MVT::i16)
5261       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5262     // vrev <4 x i8> -> VREV16
5263     assert(VT.getVectorElementType() == MVT::i8);
5264     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5265   case OP_VDUP0:
5266   case OP_VDUP1:
5267   case OP_VDUP2:
5268   case OP_VDUP3:
5269     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5270                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5271   case OP_VEXT1:
5272   case OP_VEXT2:
5273   case OP_VEXT3:
5274     return DAG.getNode(ARMISD::VEXT, dl, VT,
5275                        OpLHS, OpRHS,
5276                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5277   case OP_VUZPL:
5278   case OP_VUZPR:
5279     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5280                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5281   case OP_VZIPL:
5282   case OP_VZIPR:
5283     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5284                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5285   case OP_VTRNL:
5286   case OP_VTRNR:
5287     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5288                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5289   }
5290 }
5291
5292 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5293                                        ArrayRef<int> ShuffleMask,
5294                                        SelectionDAG &DAG) {
5295   // Check to see if we can use the VTBL instruction.
5296   SDValue V1 = Op.getOperand(0);
5297   SDValue V2 = Op.getOperand(1);
5298   SDLoc DL(Op);
5299
5300   SmallVector<SDValue, 8> VTBLMask;
5301   for (ArrayRef<int>::iterator
5302          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5303     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5304
5305   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5306     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5307                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5308                                    &VTBLMask[0], 8));
5309
5310   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5311                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5312                                  &VTBLMask[0], 8));
5313 }
5314
5315 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5316                                                       SelectionDAG &DAG) {
5317   SDLoc DL(Op);
5318   SDValue OpLHS = Op.getOperand(0);
5319   EVT VT = OpLHS.getValueType();
5320
5321   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5322          "Expect an v8i16/v16i8 type");
5323   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5324   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5325   // extract the first 8 bytes into the top double word and the last 8 bytes
5326   // into the bottom double word. The v8i16 case is similar.
5327   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5328   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5329                      DAG.getConstant(ExtractNum, MVT::i32));
5330 }
5331
5332 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5333   SDValue V1 = Op.getOperand(0);
5334   SDValue V2 = Op.getOperand(1);
5335   SDLoc dl(Op);
5336   EVT VT = Op.getValueType();
5337   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5338
5339   // Convert shuffles that are directly supported on NEON to target-specific
5340   // DAG nodes, instead of keeping them as shuffles and matching them again
5341   // during code selection.  This is more efficient and avoids the possibility
5342   // of inconsistencies between legalization and selection.
5343   // FIXME: floating-point vectors should be canonicalized to integer vectors
5344   // of the same time so that they get CSEd properly.
5345   ArrayRef<int> ShuffleMask = SVN->getMask();
5346
5347   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5348   if (EltSize <= 32) {
5349     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5350       int Lane = SVN->getSplatIndex();
5351       // If this is undef splat, generate it via "just" vdup, if possible.
5352       if (Lane == -1) Lane = 0;
5353
5354       // Test if V1 is a SCALAR_TO_VECTOR.
5355       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5356         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5357       }
5358       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5359       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5360       // reaches it).
5361       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5362           !isa<ConstantSDNode>(V1.getOperand(0))) {
5363         bool IsScalarToVector = true;
5364         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5365           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5366             IsScalarToVector = false;
5367             break;
5368           }
5369         if (IsScalarToVector)
5370           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5371       }
5372       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5373                          DAG.getConstant(Lane, MVT::i32));
5374     }
5375
5376     bool ReverseVEXT;
5377     unsigned Imm;
5378     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5379       if (ReverseVEXT)
5380         std::swap(V1, V2);
5381       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5382                          DAG.getConstant(Imm, MVT::i32));
5383     }
5384
5385     if (isVREVMask(ShuffleMask, VT, 64))
5386       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5387     if (isVREVMask(ShuffleMask, VT, 32))
5388       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5389     if (isVREVMask(ShuffleMask, VT, 16))
5390       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5391
5392     if (V2->getOpcode() == ISD::UNDEF &&
5393         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5394       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5395                          DAG.getConstant(Imm, MVT::i32));
5396     }
5397
5398     // Check for Neon shuffles that modify both input vectors in place.
5399     // If both results are used, i.e., if there are two shuffles with the same
5400     // source operands and with masks corresponding to both results of one of
5401     // these operations, DAG memoization will ensure that a single node is
5402     // used for both shuffles.
5403     unsigned WhichResult;
5404     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5405       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5406                          V1, V2).getValue(WhichResult);
5407     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5408       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5409                          V1, V2).getValue(WhichResult);
5410     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5411       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5412                          V1, V2).getValue(WhichResult);
5413
5414     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5415       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5416                          V1, V1).getValue(WhichResult);
5417     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5418       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5419                          V1, V1).getValue(WhichResult);
5420     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5421       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5422                          V1, V1).getValue(WhichResult);
5423   }
5424
5425   // If the shuffle is not directly supported and it has 4 elements, use
5426   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5427   unsigned NumElts = VT.getVectorNumElements();
5428   if (NumElts == 4) {
5429     unsigned PFIndexes[4];
5430     for (unsigned i = 0; i != 4; ++i) {
5431       if (ShuffleMask[i] < 0)
5432         PFIndexes[i] = 8;
5433       else
5434         PFIndexes[i] = ShuffleMask[i];
5435     }
5436
5437     // Compute the index in the perfect shuffle table.
5438     unsigned PFTableIndex =
5439       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5440     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5441     unsigned Cost = (PFEntry >> 30);
5442
5443     if (Cost <= 4)
5444       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5445   }
5446
5447   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5448   if (EltSize >= 32) {
5449     // Do the expansion with floating-point types, since that is what the VFP
5450     // registers are defined to use, and since i64 is not legal.
5451     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5452     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5453     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5454     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5455     SmallVector<SDValue, 8> Ops;
5456     for (unsigned i = 0; i < NumElts; ++i) {
5457       if (ShuffleMask[i] < 0)
5458         Ops.push_back(DAG.getUNDEF(EltVT));
5459       else
5460         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5461                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5462                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5463                                                   MVT::i32)));
5464     }
5465     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5466     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5467   }
5468
5469   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5470     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5471
5472   if (VT == MVT::v8i8) {
5473     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5474     if (NewOp.getNode())
5475       return NewOp;
5476   }
5477
5478   return SDValue();
5479 }
5480
5481 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5482   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5483   SDValue Lane = Op.getOperand(2);
5484   if (!isa<ConstantSDNode>(Lane))
5485     return SDValue();
5486
5487   return Op;
5488 }
5489
5490 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5491   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5492   SDValue Lane = Op.getOperand(1);
5493   if (!isa<ConstantSDNode>(Lane))
5494     return SDValue();
5495
5496   SDValue Vec = Op.getOperand(0);
5497   if (Op.getValueType() == MVT::i32 &&
5498       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5499     SDLoc dl(Op);
5500     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5501   }
5502
5503   return Op;
5504 }
5505
5506 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5507   // The only time a CONCAT_VECTORS operation can have legal types is when
5508   // two 64-bit vectors are concatenated to a 128-bit vector.
5509   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5510          "unexpected CONCAT_VECTORS");
5511   SDLoc dl(Op);
5512   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5513   SDValue Op0 = Op.getOperand(0);
5514   SDValue Op1 = Op.getOperand(1);
5515   if (Op0.getOpcode() != ISD::UNDEF)
5516     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5517                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5518                       DAG.getIntPtrConstant(0));
5519   if (Op1.getOpcode() != ISD::UNDEF)
5520     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5521                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5522                       DAG.getIntPtrConstant(1));
5523   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5524 }
5525
5526 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5527 /// element has been zero/sign-extended, depending on the isSigned parameter,
5528 /// from an integer type half its size.
5529 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5530                                    bool isSigned) {
5531   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5532   EVT VT = N->getValueType(0);
5533   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5534     SDNode *BVN = N->getOperand(0).getNode();
5535     if (BVN->getValueType(0) != MVT::v4i32 ||
5536         BVN->getOpcode() != ISD::BUILD_VECTOR)
5537       return false;
5538     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5539     unsigned HiElt = 1 - LoElt;
5540     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5541     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5542     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5543     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5544     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5545       return false;
5546     if (isSigned) {
5547       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5548           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5549         return true;
5550     } else {
5551       if (Hi0->isNullValue() && Hi1->isNullValue())
5552         return true;
5553     }
5554     return false;
5555   }
5556
5557   if (N->getOpcode() != ISD::BUILD_VECTOR)
5558     return false;
5559
5560   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5561     SDNode *Elt = N->getOperand(i).getNode();
5562     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5563       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5564       unsigned HalfSize = EltSize / 2;
5565       if (isSigned) {
5566         if (!isIntN(HalfSize, C->getSExtValue()))
5567           return false;
5568       } else {
5569         if (!isUIntN(HalfSize, C->getZExtValue()))
5570           return false;
5571       }
5572       continue;
5573     }
5574     return false;
5575   }
5576
5577   return true;
5578 }
5579
5580 /// isSignExtended - Check if a node is a vector value that is sign-extended
5581 /// or a constant BUILD_VECTOR with sign-extended elements.
5582 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5583   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5584     return true;
5585   if (isExtendedBUILD_VECTOR(N, DAG, true))
5586     return true;
5587   return false;
5588 }
5589
5590 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5591 /// or a constant BUILD_VECTOR with zero-extended elements.
5592 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5593   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5594     return true;
5595   if (isExtendedBUILD_VECTOR(N, DAG, false))
5596     return true;
5597   return false;
5598 }
5599
5600 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5601   if (OrigVT.getSizeInBits() >= 64)
5602     return OrigVT;
5603
5604   assert(OrigVT.isSimple() && "Expecting a simple value type");
5605
5606   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5607   switch (OrigSimpleTy) {
5608   default: llvm_unreachable("Unexpected Vector Type");
5609   case MVT::v2i8:
5610   case MVT::v2i16:
5611      return MVT::v2i32;
5612   case MVT::v4i8:
5613     return  MVT::v4i16;
5614   }
5615 }
5616
5617 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5618 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5619 /// We insert the required extension here to get the vector to fill a D register.
5620 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5621                                             const EVT &OrigTy,
5622                                             const EVT &ExtTy,
5623                                             unsigned ExtOpcode) {
5624   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5625   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5626   // 64-bits we need to insert a new extension so that it will be 64-bits.
5627   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5628   if (OrigTy.getSizeInBits() >= 64)
5629     return N;
5630
5631   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5632   EVT NewVT = getExtensionTo64Bits(OrigTy);
5633
5634   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5635 }
5636
5637 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5638 /// does not do any sign/zero extension. If the original vector is less
5639 /// than 64 bits, an appropriate extension will be added after the load to
5640 /// reach a total size of 64 bits. We have to add the extension separately
5641 /// because ARM does not have a sign/zero extending load for vectors.
5642 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5643   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5644
5645   // The load already has the right type.
5646   if (ExtendedTy == LD->getMemoryVT())
5647     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5648                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5649                 LD->isNonTemporal(), LD->isInvariant(),
5650                 LD->getAlignment());
5651
5652   // We need to create a zextload/sextload. We cannot just create a load
5653   // followed by a zext/zext node because LowerMUL is also run during normal
5654   // operation legalization where we can't create illegal types.
5655   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5656                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5657                         LD->getMemoryVT(), LD->isVolatile(),
5658                         LD->isNonTemporal(), LD->getAlignment());
5659 }
5660
5661 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5662 /// extending load, or BUILD_VECTOR with extended elements, return the
5663 /// unextended value. The unextended vector should be 64 bits so that it can
5664 /// be used as an operand to a VMULL instruction. If the original vector size
5665 /// before extension is less than 64 bits we add a an extension to resize
5666 /// the vector to 64 bits.
5667 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5668   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5669     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5670                                         N->getOperand(0)->getValueType(0),
5671                                         N->getValueType(0),
5672                                         N->getOpcode());
5673
5674   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5675     return SkipLoadExtensionForVMULL(LD, DAG);
5676
5677   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5678   // have been legalized as a BITCAST from v4i32.
5679   if (N->getOpcode() == ISD::BITCAST) {
5680     SDNode *BVN = N->getOperand(0).getNode();
5681     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5682            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5683     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5684     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5685                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5686   }
5687   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5688   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5689   EVT VT = N->getValueType(0);
5690   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5691   unsigned NumElts = VT.getVectorNumElements();
5692   MVT TruncVT = MVT::getIntegerVT(EltSize);
5693   SmallVector<SDValue, 8> Ops;
5694   for (unsigned i = 0; i != NumElts; ++i) {
5695     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5696     const APInt &CInt = C->getAPIntValue();
5697     // Element types smaller than 32 bits are not legal, so use i32 elements.
5698     // The values are implicitly truncated so sext vs. zext doesn't matter.
5699     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5700   }
5701   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5702                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5703 }
5704
5705 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5706   unsigned Opcode = N->getOpcode();
5707   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5708     SDNode *N0 = N->getOperand(0).getNode();
5709     SDNode *N1 = N->getOperand(1).getNode();
5710     return N0->hasOneUse() && N1->hasOneUse() &&
5711       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5712   }
5713   return false;
5714 }
5715
5716 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5717   unsigned Opcode = N->getOpcode();
5718   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5719     SDNode *N0 = N->getOperand(0).getNode();
5720     SDNode *N1 = N->getOperand(1).getNode();
5721     return N0->hasOneUse() && N1->hasOneUse() &&
5722       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5723   }
5724   return false;
5725 }
5726
5727 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5728   // Multiplications are only custom-lowered for 128-bit vectors so that
5729   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5730   EVT VT = Op.getValueType();
5731   assert(VT.is128BitVector() && VT.isInteger() &&
5732          "unexpected type for custom-lowering ISD::MUL");
5733   SDNode *N0 = Op.getOperand(0).getNode();
5734   SDNode *N1 = Op.getOperand(1).getNode();
5735   unsigned NewOpc = 0;
5736   bool isMLA = false;
5737   bool isN0SExt = isSignExtended(N0, DAG);
5738   bool isN1SExt = isSignExtended(N1, DAG);
5739   if (isN0SExt && isN1SExt)
5740     NewOpc = ARMISD::VMULLs;
5741   else {
5742     bool isN0ZExt = isZeroExtended(N0, DAG);
5743     bool isN1ZExt = isZeroExtended(N1, DAG);
5744     if (isN0ZExt && isN1ZExt)
5745       NewOpc = ARMISD::VMULLu;
5746     else if (isN1SExt || isN1ZExt) {
5747       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5748       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5749       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5750         NewOpc = ARMISD::VMULLs;
5751         isMLA = true;
5752       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5753         NewOpc = ARMISD::VMULLu;
5754         isMLA = true;
5755       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5756         std::swap(N0, N1);
5757         NewOpc = ARMISD::VMULLu;
5758         isMLA = true;
5759       }
5760     }
5761
5762     if (!NewOpc) {
5763       if (VT == MVT::v2i64)
5764         // Fall through to expand this.  It is not legal.
5765         return SDValue();
5766       else
5767         // Other vector multiplications are legal.
5768         return Op;
5769     }
5770   }
5771
5772   // Legalize to a VMULL instruction.
5773   SDLoc DL(Op);
5774   SDValue Op0;
5775   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5776   if (!isMLA) {
5777     Op0 = SkipExtensionForVMULL(N0, DAG);
5778     assert(Op0.getValueType().is64BitVector() &&
5779            Op1.getValueType().is64BitVector() &&
5780            "unexpected types for extended operands to VMULL");
5781     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5782   }
5783
5784   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5785   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5786   //   vmull q0, d4, d6
5787   //   vmlal q0, d5, d6
5788   // is faster than
5789   //   vaddl q0, d4, d5
5790   //   vmovl q1, d6
5791   //   vmul  q0, q0, q1
5792   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5793   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5794   EVT Op1VT = Op1.getValueType();
5795   return DAG.getNode(N0->getOpcode(), DL, VT,
5796                      DAG.getNode(NewOpc, DL, VT,
5797                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5798                      DAG.getNode(NewOpc, DL, VT,
5799                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5800 }
5801
5802 static SDValue
5803 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5804   // Convert to float
5805   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5806   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5807   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5808   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5809   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5810   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5811   // Get reciprocal estimate.
5812   // float4 recip = vrecpeq_f32(yf);
5813   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5814                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5815   // Because char has a smaller range than uchar, we can actually get away
5816   // without any newton steps.  This requires that we use a weird bias
5817   // of 0xb000, however (again, this has been exhaustively tested).
5818   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5819   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5820   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5821   Y = DAG.getConstant(0xb000, MVT::i32);
5822   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5823   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5824   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5825   // Convert back to short.
5826   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5827   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5828   return X;
5829 }
5830
5831 static SDValue
5832 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5833   SDValue N2;
5834   // Convert to float.
5835   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5836   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5837   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5838   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5839   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5840   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5841
5842   // Use reciprocal estimate and one refinement step.
5843   // float4 recip = vrecpeq_f32(yf);
5844   // recip *= vrecpsq_f32(yf, recip);
5845   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5846                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5847   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5848                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5849                    N1, N2);
5850   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5851   // Because short has a smaller range than ushort, we can actually get away
5852   // with only a single newton step.  This requires that we use a weird bias
5853   // of 89, however (again, this has been exhaustively tested).
5854   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5855   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5856   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5857   N1 = DAG.getConstant(0x89, MVT::i32);
5858   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5859   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5860   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5861   // Convert back to integer and return.
5862   // return vmovn_s32(vcvt_s32_f32(result));
5863   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5864   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5865   return N0;
5866 }
5867
5868 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5869   EVT VT = Op.getValueType();
5870   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5871          "unexpected type for custom-lowering ISD::SDIV");
5872
5873   SDLoc dl(Op);
5874   SDValue N0 = Op.getOperand(0);
5875   SDValue N1 = Op.getOperand(1);
5876   SDValue N2, N3;
5877
5878   if (VT == MVT::v8i8) {
5879     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5880     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5881
5882     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5883                      DAG.getIntPtrConstant(4));
5884     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5885                      DAG.getIntPtrConstant(4));
5886     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5887                      DAG.getIntPtrConstant(0));
5888     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5889                      DAG.getIntPtrConstant(0));
5890
5891     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5892     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5893
5894     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5895     N0 = LowerCONCAT_VECTORS(N0, DAG);
5896
5897     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5898     return N0;
5899   }
5900   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5901 }
5902
5903 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5904   EVT VT = Op.getValueType();
5905   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5906          "unexpected type for custom-lowering ISD::UDIV");
5907
5908   SDLoc dl(Op);
5909   SDValue N0 = Op.getOperand(0);
5910   SDValue N1 = Op.getOperand(1);
5911   SDValue N2, N3;
5912
5913   if (VT == MVT::v8i8) {
5914     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5915     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5916
5917     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5918                      DAG.getIntPtrConstant(4));
5919     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5920                      DAG.getIntPtrConstant(4));
5921     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5922                      DAG.getIntPtrConstant(0));
5923     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5924                      DAG.getIntPtrConstant(0));
5925
5926     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5927     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5928
5929     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5930     N0 = LowerCONCAT_VECTORS(N0, DAG);
5931
5932     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5933                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5934                      N0);
5935     return N0;
5936   }
5937
5938   // v4i16 sdiv ... Convert to float.
5939   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5940   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5941   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5942   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5943   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5944   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5945
5946   // Use reciprocal estimate and two refinement steps.
5947   // float4 recip = vrecpeq_f32(yf);
5948   // recip *= vrecpsq_f32(yf, recip);
5949   // recip *= vrecpsq_f32(yf, recip);
5950   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5951                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5952   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5953                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5954                    BN1, N2);
5955   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5956   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5957                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5958                    BN1, N2);
5959   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5960   // Simply multiplying by the reciprocal estimate can leave us a few ulps
5961   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5962   // and that it will never cause us to return an answer too large).
5963   // float4 result = as_float4(as_int4(xf*recip) + 2);
5964   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5965   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5966   N1 = DAG.getConstant(2, MVT::i32);
5967   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5968   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5969   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5970   // Convert back to integer and return.
5971   // return vmovn_u32(vcvt_s32_f32(result));
5972   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5973   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5974   return N0;
5975 }
5976
5977 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5978   EVT VT = Op.getNode()->getValueType(0);
5979   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5980
5981   unsigned Opc;
5982   bool ExtraOp = false;
5983   switch (Op.getOpcode()) {
5984   default: llvm_unreachable("Invalid code");
5985   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5986   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5987   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5988   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5989   }
5990
5991   if (!ExtraOp)
5992     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5993                        Op.getOperand(1));
5994   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5995                      Op.getOperand(1), Op.getOperand(2));
5996 }
5997
5998 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5999   // Monotonic load/store is legal for all targets
6000   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6001     return Op;
6002
6003   // Aquire/Release load/store is not legal for targets without a
6004   // dmb or equivalent available.
6005   return SDValue();
6006 }
6007
6008 static void
6009 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
6010                     SelectionDAG &DAG) {
6011   SDLoc dl(Node);
6012   assert (Node->getValueType(0) == MVT::i64 &&
6013           "Only know how to expand i64 atomics");
6014   AtomicSDNode *AN = cast<AtomicSDNode>(Node);
6015
6016   SmallVector<SDValue, 6> Ops;
6017   Ops.push_back(Node->getOperand(0)); // Chain
6018   Ops.push_back(Node->getOperand(1)); // Ptr
6019   for(unsigned i=2; i<Node->getNumOperands(); i++) {
6020     // Low part
6021     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6022                               Node->getOperand(i), DAG.getIntPtrConstant(0)));
6023     // High part
6024     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6025                               Node->getOperand(i), DAG.getIntPtrConstant(1)));
6026   }
6027   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6028   SDValue Result =
6029     DAG.getAtomic(Node->getOpcode(), dl, MVT::i64, Tys, Ops.data(), Ops.size(),
6030                   cast<MemSDNode>(Node)->getMemOperand(), AN->getOrdering(),
6031                   AN->getSynchScope());
6032   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
6033   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6034   Results.push_back(Result.getValue(2));
6035 }
6036
6037 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6038                                     SmallVectorImpl<SDValue> &Results,
6039                                     SelectionDAG &DAG,
6040                                     const ARMSubtarget *Subtarget) {
6041   SDLoc DL(N);
6042   SDValue Cycles32, OutChain;
6043
6044   if (Subtarget->hasPerfMon()) {
6045     // Under Power Management extensions, the cycle-count is:
6046     //    mrc p15, #0, <Rt>, c9, c13, #0
6047     SDValue Ops[] = { N->getOperand(0), // Chain
6048                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6049                       DAG.getConstant(15, MVT::i32),
6050                       DAG.getConstant(0, MVT::i32),
6051                       DAG.getConstant(9, MVT::i32),
6052                       DAG.getConstant(13, MVT::i32),
6053                       DAG.getConstant(0, MVT::i32)
6054     };
6055
6056     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6057                            DAG.getVTList(MVT::i32, MVT::Other), &Ops[0],
6058                            array_lengthof(Ops));
6059     OutChain = Cycles32.getValue(1);
6060   } else {
6061     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6062     // there are older ARM CPUs that have implementation-specific ways of
6063     // obtaining this information (FIXME!).
6064     Cycles32 = DAG.getConstant(0, MVT::i32);
6065     OutChain = DAG.getEntryNode();
6066   }
6067
6068
6069   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6070                                  Cycles32, DAG.getConstant(0, MVT::i32));
6071   Results.push_back(Cycles64);
6072   Results.push_back(OutChain);
6073 }
6074
6075 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6076   switch (Op.getOpcode()) {
6077   default: llvm_unreachable("Don't know how to custom lower this!");
6078   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6079   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6080   case ISD::GlobalAddress:
6081     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
6082       LowerGlobalAddressELF(Op, DAG);
6083   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6084   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6085   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6086   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6087   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6088   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6089   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6090   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6091   case ISD::SINT_TO_FP:
6092   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6093   case ISD::FP_TO_SINT:
6094   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6095   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6096   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6097   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6098   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6099   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6100   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6101   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6102                                                                Subtarget);
6103   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6104   case ISD::SHL:
6105   case ISD::SRL:
6106   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6107   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6108   case ISD::SRL_PARTS:
6109   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6110   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6111   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6112   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6113   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6114   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6115   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6116   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6117   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6118   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6119   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6120   case ISD::MUL:           return LowerMUL(Op, DAG);
6121   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6122   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6123   case ISD::ADDC:
6124   case ISD::ADDE:
6125   case ISD::SUBC:
6126   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6127   case ISD::ATOMIC_LOAD:
6128   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6129   case ISD::SDIVREM:
6130   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6131   }
6132 }
6133
6134 /// ReplaceNodeResults - Replace the results of node with an illegal result
6135 /// type with new values built out of custom code.
6136 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6137                                            SmallVectorImpl<SDValue>&Results,
6138                                            SelectionDAG &DAG) const {
6139   SDValue Res;
6140   switch (N->getOpcode()) {
6141   default:
6142     llvm_unreachable("Don't know how to custom expand this!");
6143   case ISD::BITCAST:
6144     Res = ExpandBITCAST(N, DAG);
6145     break;
6146   case ISD::SIGN_EXTEND:
6147   case ISD::ZERO_EXTEND:
6148     Res = ExpandVectorExtension(N, DAG);
6149     break;
6150   case ISD::SRL:
6151   case ISD::SRA:
6152     Res = Expand64BitShift(N, DAG, Subtarget);
6153     break;
6154   case ISD::READCYCLECOUNTER:
6155     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6156     return;
6157   case ISD::ATOMIC_STORE:
6158   case ISD::ATOMIC_LOAD:
6159   case ISD::ATOMIC_LOAD_ADD:
6160   case ISD::ATOMIC_LOAD_AND:
6161   case ISD::ATOMIC_LOAD_NAND:
6162   case ISD::ATOMIC_LOAD_OR:
6163   case ISD::ATOMIC_LOAD_SUB:
6164   case ISD::ATOMIC_LOAD_XOR:
6165   case ISD::ATOMIC_SWAP:
6166   case ISD::ATOMIC_CMP_SWAP:
6167   case ISD::ATOMIC_LOAD_MIN:
6168   case ISD::ATOMIC_LOAD_UMIN:
6169   case ISD::ATOMIC_LOAD_MAX:
6170   case ISD::ATOMIC_LOAD_UMAX:
6171     ReplaceATOMIC_OP_64(N, Results, DAG);
6172     return;
6173   }
6174   if (Res.getNode())
6175     Results.push_back(Res);
6176 }
6177
6178 //===----------------------------------------------------------------------===//
6179 //                           ARM Scheduler Hooks
6180 //===----------------------------------------------------------------------===//
6181
6182 MachineBasicBlock *
6183 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
6184                                      MachineBasicBlock *BB,
6185                                      unsigned Size) const {
6186   unsigned dest    = MI->getOperand(0).getReg();
6187   unsigned ptr     = MI->getOperand(1).getReg();
6188   unsigned oldval  = MI->getOperand(2).getReg();
6189   unsigned newval  = MI->getOperand(3).getReg();
6190   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6191   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(4).getImm());
6192   DebugLoc dl = MI->getDebugLoc();
6193   bool isThumb2 = Subtarget->isThumb2();
6194
6195   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6196   unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
6197     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6198     (const TargetRegisterClass*)&ARM::GPRRegClass);
6199
6200   if (isThumb2) {
6201     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6202     MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
6203     MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
6204   }
6205
6206   unsigned ldrOpc, strOpc;
6207   getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6208
6209   MachineFunction *MF = BB->getParent();
6210   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6211   MachineFunction::iterator It = BB;
6212   ++It; // insert the new blocks after the current block
6213
6214   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6215   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6216   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6217   MF->insert(It, loop1MBB);
6218   MF->insert(It, loop2MBB);
6219   MF->insert(It, exitMBB);
6220
6221   // Transfer the remainder of BB and its successor edges to exitMBB.
6222   exitMBB->splice(exitMBB->begin(), BB,
6223                   llvm::next(MachineBasicBlock::iterator(MI)),
6224                   BB->end());
6225   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6226
6227   //  thisMBB:
6228   //   ...
6229   //   fallthrough --> loop1MBB
6230   BB->addSuccessor(loop1MBB);
6231
6232   // loop1MBB:
6233   //   ldrex dest, [ptr]
6234   //   cmp dest, oldval
6235   //   bne exitMBB
6236   BB = loop1MBB;
6237   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6238   if (ldrOpc == ARM::t2LDREX)
6239     MIB.addImm(0);
6240   AddDefaultPred(MIB);
6241   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6242                  .addReg(dest).addReg(oldval));
6243   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6244     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6245   BB->addSuccessor(loop2MBB);
6246   BB->addSuccessor(exitMBB);
6247
6248   // loop2MBB:
6249   //   strex scratch, newval, [ptr]
6250   //   cmp scratch, #0
6251   //   bne loop1MBB
6252   BB = loop2MBB;
6253   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
6254   if (strOpc == ARM::t2STREX)
6255     MIB.addImm(0);
6256   AddDefaultPred(MIB);
6257   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6258                  .addReg(scratch).addImm(0));
6259   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6260     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6261   BB->addSuccessor(loop1MBB);
6262   BB->addSuccessor(exitMBB);
6263
6264   //  exitMBB:
6265   //   ...
6266   BB = exitMBB;
6267
6268   MI->eraseFromParent();   // The instruction is gone now.
6269
6270   return BB;
6271 }
6272
6273 MachineBasicBlock *
6274 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6275                                     unsigned Size, unsigned BinOpcode) const {
6276   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6277   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6278
6279   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6280   MachineFunction *MF = BB->getParent();
6281   MachineFunction::iterator It = BB;
6282   ++It;
6283
6284   unsigned dest = MI->getOperand(0).getReg();
6285   unsigned ptr = MI->getOperand(1).getReg();
6286   unsigned incr = MI->getOperand(2).getReg();
6287   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6288   DebugLoc dl = MI->getDebugLoc();
6289   bool isThumb2 = Subtarget->isThumb2();
6290
6291   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6292   if (isThumb2) {
6293     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6294     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6295     MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6296   }
6297
6298   unsigned ldrOpc, strOpc;
6299   getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6300
6301   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6302   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6303   MF->insert(It, loopMBB);
6304   MF->insert(It, exitMBB);
6305
6306   // Transfer the remainder of BB and its successor edges to exitMBB.
6307   exitMBB->splice(exitMBB->begin(), BB,
6308                   llvm::next(MachineBasicBlock::iterator(MI)),
6309                   BB->end());
6310   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6311
6312   const TargetRegisterClass *TRC = isThumb2 ?
6313     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6314     (const TargetRegisterClass*)&ARM::GPRRegClass;
6315   unsigned scratch = MRI.createVirtualRegister(TRC);
6316   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
6317
6318   //  thisMBB:
6319   //   ...
6320   //   fallthrough --> loopMBB
6321   BB->addSuccessor(loopMBB);
6322
6323   //  loopMBB:
6324   //   ldrex dest, ptr
6325   //   <binop> scratch2, dest, incr
6326   //   strex scratch, scratch2, ptr
6327   //   cmp scratch, #0
6328   //   bne- loopMBB
6329   //   fallthrough --> exitMBB
6330   BB = loopMBB;
6331   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6332   if (ldrOpc == ARM::t2LDREX)
6333     MIB.addImm(0);
6334   AddDefaultPred(MIB);
6335   if (BinOpcode) {
6336     // operand order needs to go the other way for NAND
6337     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
6338       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6339                      addReg(incr).addReg(dest)).addReg(0);
6340     else
6341       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6342                      addReg(dest).addReg(incr)).addReg(0);
6343   }
6344
6345   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6346   if (strOpc == ARM::t2STREX)
6347     MIB.addImm(0);
6348   AddDefaultPred(MIB);
6349   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6350                  .addReg(scratch).addImm(0));
6351   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6352     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6353
6354   BB->addSuccessor(loopMBB);
6355   BB->addSuccessor(exitMBB);
6356
6357   //  exitMBB:
6358   //   ...
6359   BB = exitMBB;
6360
6361   MI->eraseFromParent();   // The instruction is gone now.
6362
6363   return BB;
6364 }
6365
6366 MachineBasicBlock *
6367 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
6368                                           MachineBasicBlock *BB,
6369                                           unsigned Size,
6370                                           bool signExtend,
6371                                           ARMCC::CondCodes Cond) const {
6372   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6373
6374   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6375   MachineFunction *MF = BB->getParent();
6376   MachineFunction::iterator It = BB;
6377   ++It;
6378
6379   unsigned dest = MI->getOperand(0).getReg();
6380   unsigned ptr = MI->getOperand(1).getReg();
6381   unsigned incr = MI->getOperand(2).getReg();
6382   unsigned oldval = dest;
6383   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6384   DebugLoc dl = MI->getDebugLoc();
6385   bool isThumb2 = Subtarget->isThumb2();
6386
6387   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6388   if (isThumb2) {
6389     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6390     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6391     MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6392   }
6393
6394   unsigned ldrOpc, strOpc, extendOpc;
6395   getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6396   switch (Size) {
6397   default: llvm_unreachable("unsupported size for AtomicBinaryMinMax!");
6398   case 1:
6399     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
6400     break;
6401   case 2:
6402     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
6403     break;
6404   case 4:
6405     extendOpc = 0;
6406     break;
6407   }
6408
6409   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6410   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6411   MF->insert(It, loopMBB);
6412   MF->insert(It, exitMBB);
6413
6414   // Transfer the remainder of BB and its successor edges to exitMBB.
6415   exitMBB->splice(exitMBB->begin(), BB,
6416                   llvm::next(MachineBasicBlock::iterator(MI)),
6417                   BB->end());
6418   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6419
6420   const TargetRegisterClass *TRC = isThumb2 ?
6421     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6422     (const TargetRegisterClass*)&ARM::GPRRegClass;
6423   unsigned scratch = MRI.createVirtualRegister(TRC);
6424   unsigned scratch2 = MRI.createVirtualRegister(TRC);
6425
6426   //  thisMBB:
6427   //   ...
6428   //   fallthrough --> loopMBB
6429   BB->addSuccessor(loopMBB);
6430
6431   //  loopMBB:
6432   //   ldrex dest, ptr
6433   //   (sign extend dest, if required)
6434   //   cmp dest, incr
6435   //   cmov.cond scratch2, incr, dest
6436   //   strex scratch, scratch2, ptr
6437   //   cmp scratch, #0
6438   //   bne- loopMBB
6439   //   fallthrough --> exitMBB
6440   BB = loopMBB;
6441   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6442   if (ldrOpc == ARM::t2LDREX)
6443     MIB.addImm(0);
6444   AddDefaultPred(MIB);
6445
6446   // Sign extend the value, if necessary.
6447   if (signExtend && extendOpc) {
6448     oldval = MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass
6449                                                 : &ARM::GPRnopcRegClass);
6450     if (!isThumb2)
6451       MRI.constrainRegClass(dest, &ARM::GPRnopcRegClass);
6452     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
6453                      .addReg(dest)
6454                      .addImm(0));
6455   }
6456
6457   // Build compare and cmov instructions.
6458   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6459                  .addReg(oldval).addReg(incr));
6460   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
6461          .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
6462
6463   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6464   if (strOpc == ARM::t2STREX)
6465     MIB.addImm(0);
6466   AddDefaultPred(MIB);
6467   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6468                  .addReg(scratch).addImm(0));
6469   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6470     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6471
6472   BB->addSuccessor(loopMBB);
6473   BB->addSuccessor(exitMBB);
6474
6475   //  exitMBB:
6476   //   ...
6477   BB = exitMBB;
6478
6479   MI->eraseFromParent();   // The instruction is gone now.
6480
6481   return BB;
6482 }
6483
6484 MachineBasicBlock *
6485 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
6486                                       unsigned Op1, unsigned Op2,
6487                                       bool NeedsCarry, bool IsCmpxchg,
6488                                       bool IsMinMax, ARMCC::CondCodes CC) const {
6489   // This also handles ATOMIC_SWAP and ATOMIC_STORE, indicated by Op1==0.
6490   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6491
6492   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6493   MachineFunction *MF = BB->getParent();
6494   MachineFunction::iterator It = BB;
6495   ++It;
6496
6497   bool isStore = (MI->getOpcode() == ARM::ATOMIC_STORE_I64);
6498   unsigned offset = (isStore ? -2 : 0);
6499   unsigned destlo = MI->getOperand(0).getReg();
6500   unsigned desthi = MI->getOperand(1).getReg();
6501   unsigned ptr = MI->getOperand(offset+2).getReg();
6502   unsigned vallo = MI->getOperand(offset+3).getReg();
6503   unsigned valhi = MI->getOperand(offset+4).getReg();
6504   unsigned OrdIdx = offset + (IsCmpxchg ? 7 : 5);
6505   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(OrdIdx).getImm());
6506   DebugLoc dl = MI->getDebugLoc();
6507   bool isThumb2 = Subtarget->isThumb2();
6508
6509   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6510   if (isThumb2) {
6511     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6512     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6513     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6514     MRI.constrainRegClass(vallo, &ARM::rGPRRegClass);
6515     MRI.constrainRegClass(valhi, &ARM::rGPRRegClass);
6516   }
6517
6518   unsigned ldrOpc, strOpc;
6519   getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6520
6521   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6522   MachineBasicBlock *contBB = 0, *cont2BB = 0;
6523   if (IsCmpxchg || IsMinMax)
6524     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
6525   if (IsCmpxchg)
6526     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
6527   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6528
6529   MF->insert(It, loopMBB);
6530   if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6531   if (IsCmpxchg) MF->insert(It, cont2BB);
6532   MF->insert(It, exitMBB);
6533
6534   // Transfer the remainder of BB and its successor edges to exitMBB.
6535   exitMBB->splice(exitMBB->begin(), BB,
6536                   llvm::next(MachineBasicBlock::iterator(MI)),
6537                   BB->end());
6538   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6539
6540   const TargetRegisterClass *TRC = isThumb2 ?
6541     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6542     (const TargetRegisterClass*)&ARM::GPRRegClass;
6543   unsigned storesuccess = MRI.createVirtualRegister(TRC);
6544
6545   //  thisMBB:
6546   //   ...
6547   //   fallthrough --> loopMBB
6548   BB->addSuccessor(loopMBB);
6549
6550   //  loopMBB:
6551   //   ldrexd r2, r3, ptr
6552   //   <binopa> r0, r2, incr
6553   //   <binopb> r1, r3, incr
6554   //   strexd storesuccess, r0, r1, ptr
6555   //   cmp storesuccess, #0
6556   //   bne- loopMBB
6557   //   fallthrough --> exitMBB
6558   BB = loopMBB;
6559
6560   if (!isStore) {
6561     // Load
6562     if (isThumb2) {
6563       AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6564                      .addReg(destlo, RegState::Define)
6565                      .addReg(desthi, RegState::Define)
6566                      .addReg(ptr));
6567     } else {
6568       unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6569       AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6570                      .addReg(GPRPair0, RegState::Define).addReg(ptr));
6571       // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
6572       BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6573         .addReg(GPRPair0, 0, ARM::gsub_0);
6574       BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6575         .addReg(GPRPair0, 0, ARM::gsub_1);
6576     }
6577   }
6578
6579   unsigned StoreLo, StoreHi;
6580   if (IsCmpxchg) {
6581     // Add early exit
6582     for (unsigned i = 0; i < 2; i++) {
6583       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6584                                                          ARM::CMPrr))
6585                      .addReg(i == 0 ? destlo : desthi)
6586                      .addReg(i == 0 ? vallo : valhi));
6587       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6588         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6589       BB->addSuccessor(exitMBB);
6590       BB->addSuccessor(i == 0 ? contBB : cont2BB);
6591       BB = (i == 0 ? contBB : cont2BB);
6592     }
6593
6594     // Copy to physregs for strexd
6595     StoreLo = MI->getOperand(5).getReg();
6596     StoreHi = MI->getOperand(6).getReg();
6597   } else if (Op1) {
6598     // Perform binary operation
6599     unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6600     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6601                    .addReg(destlo).addReg(vallo))
6602         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6603     unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6604     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6605                    .addReg(desthi).addReg(valhi))
6606         .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6607
6608     StoreLo = tmpRegLo;
6609     StoreHi = tmpRegHi;
6610   } else {
6611     // Copy to physregs for strexd
6612     StoreLo = vallo;
6613     StoreHi = valhi;
6614   }
6615   if (IsMinMax) {
6616     // Compare and branch to exit block.
6617     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6618       .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6619     BB->addSuccessor(exitMBB);
6620     BB->addSuccessor(contBB);
6621     BB = contBB;
6622     StoreLo = vallo;
6623     StoreHi = valhi;
6624   }
6625
6626   // Store
6627   if (isThumb2) {
6628     MRI.constrainRegClass(StoreLo, &ARM::rGPRRegClass);
6629     MRI.constrainRegClass(StoreHi, &ARM::rGPRRegClass);
6630     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6631                    .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6632   } else {
6633     // Marshal a pair...
6634     unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6635     unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6636     unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6637     BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6638     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6639       .addReg(UndefPair)
6640       .addReg(StoreLo)
6641       .addImm(ARM::gsub_0);
6642     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6643       .addReg(r1)
6644       .addReg(StoreHi)
6645       .addImm(ARM::gsub_1);
6646
6647     // ...and store it
6648     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6649                    .addReg(StorePair).addReg(ptr));
6650   }
6651   // Cmp+jump
6652   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6653                  .addReg(storesuccess).addImm(0));
6654   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6655     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6656
6657   BB->addSuccessor(loopMBB);
6658   BB->addSuccessor(exitMBB);
6659
6660   //  exitMBB:
6661   //   ...
6662   BB = exitMBB;
6663
6664   MI->eraseFromParent();   // The instruction is gone now.
6665
6666   return BB;
6667 }
6668
6669 MachineBasicBlock *
6670 ARMTargetLowering::EmitAtomicLoad64(MachineInstr *MI, MachineBasicBlock *BB) const {
6671
6672   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6673
6674   unsigned destlo = MI->getOperand(0).getReg();
6675   unsigned desthi = MI->getOperand(1).getReg();
6676   unsigned ptr = MI->getOperand(2).getReg();
6677   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6678   DebugLoc dl = MI->getDebugLoc();
6679   bool isThumb2 = Subtarget->isThumb2();
6680
6681   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6682   if (isThumb2) {
6683     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6684     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6685     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6686   }
6687   unsigned ldrOpc, strOpc;
6688   getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6689
6690   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(ldrOpc));
6691
6692   if (isThumb2) {
6693     MIB.addReg(destlo, RegState::Define)
6694        .addReg(desthi, RegState::Define)
6695        .addReg(ptr);
6696
6697   } else {
6698     unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6699     MIB.addReg(GPRPair0, RegState::Define).addReg(ptr);
6700
6701     // Copy GPRPair0 into dest.  (This copy will normally be coalesced.)
6702     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), destlo)
6703       .addReg(GPRPair0, 0, ARM::gsub_0);
6704     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), desthi)
6705       .addReg(GPRPair0, 0, ARM::gsub_1);
6706   }
6707   AddDefaultPred(MIB);
6708
6709   MI->eraseFromParent();   // The instruction is gone now.
6710
6711   return BB;
6712 }
6713
6714 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6715 /// registers the function context.
6716 void ARMTargetLowering::
6717 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6718                        MachineBasicBlock *DispatchBB, int FI) const {
6719   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6720   DebugLoc dl = MI->getDebugLoc();
6721   MachineFunction *MF = MBB->getParent();
6722   MachineRegisterInfo *MRI = &MF->getRegInfo();
6723   MachineConstantPool *MCP = MF->getConstantPool();
6724   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6725   const Function *F = MF->getFunction();
6726
6727   bool isThumb = Subtarget->isThumb();
6728   bool isThumb2 = Subtarget->isThumb2();
6729
6730   unsigned PCLabelId = AFI->createPICLabelUId();
6731   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6732   ARMConstantPoolValue *CPV =
6733     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6734   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6735
6736   const TargetRegisterClass *TRC = isThumb ?
6737     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6738     (const TargetRegisterClass*)&ARM::GPRRegClass;
6739
6740   // Grab constant pool and fixed stack memory operands.
6741   MachineMemOperand *CPMMO =
6742     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6743                              MachineMemOperand::MOLoad, 4, 4);
6744
6745   MachineMemOperand *FIMMOSt =
6746     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6747                              MachineMemOperand::MOStore, 4, 4);
6748
6749   // Load the address of the dispatch MBB into the jump buffer.
6750   if (isThumb2) {
6751     // Incoming value: jbuf
6752     //   ldr.n  r5, LCPI1_1
6753     //   orr    r5, r5, #1
6754     //   add    r5, pc
6755     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6756     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6757     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6758                    .addConstantPoolIndex(CPI)
6759                    .addMemOperand(CPMMO));
6760     // Set the low bit because of thumb mode.
6761     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6762     AddDefaultCC(
6763       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6764                      .addReg(NewVReg1, RegState::Kill)
6765                      .addImm(0x01)));
6766     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6767     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6768       .addReg(NewVReg2, RegState::Kill)
6769       .addImm(PCLabelId);
6770     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6771                    .addReg(NewVReg3, RegState::Kill)
6772                    .addFrameIndex(FI)
6773                    .addImm(36)  // &jbuf[1] :: pc
6774                    .addMemOperand(FIMMOSt));
6775   } else if (isThumb) {
6776     // Incoming value: jbuf
6777     //   ldr.n  r1, LCPI1_4
6778     //   add    r1, pc
6779     //   mov    r2, #1
6780     //   orrs   r1, r2
6781     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6782     //   str    r1, [r2]
6783     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6784     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6785                    .addConstantPoolIndex(CPI)
6786                    .addMemOperand(CPMMO));
6787     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6788     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6789       .addReg(NewVReg1, RegState::Kill)
6790       .addImm(PCLabelId);
6791     // Set the low bit because of thumb mode.
6792     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6793     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6794                    .addReg(ARM::CPSR, RegState::Define)
6795                    .addImm(1));
6796     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6797     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6798                    .addReg(ARM::CPSR, RegState::Define)
6799                    .addReg(NewVReg2, RegState::Kill)
6800                    .addReg(NewVReg3, RegState::Kill));
6801     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6802     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6803                    .addFrameIndex(FI)
6804                    .addImm(36)); // &jbuf[1] :: pc
6805     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6806                    .addReg(NewVReg4, RegState::Kill)
6807                    .addReg(NewVReg5, RegState::Kill)
6808                    .addImm(0)
6809                    .addMemOperand(FIMMOSt));
6810   } else {
6811     // Incoming value: jbuf
6812     //   ldr  r1, LCPI1_1
6813     //   add  r1, pc, r1
6814     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6815     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6816     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6817                    .addConstantPoolIndex(CPI)
6818                    .addImm(0)
6819                    .addMemOperand(CPMMO));
6820     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6821     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6822                    .addReg(NewVReg1, RegState::Kill)
6823                    .addImm(PCLabelId));
6824     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6825                    .addReg(NewVReg2, RegState::Kill)
6826                    .addFrameIndex(FI)
6827                    .addImm(36)  // &jbuf[1] :: pc
6828                    .addMemOperand(FIMMOSt));
6829   }
6830 }
6831
6832 MachineBasicBlock *ARMTargetLowering::
6833 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6834   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6835   DebugLoc dl = MI->getDebugLoc();
6836   MachineFunction *MF = MBB->getParent();
6837   MachineRegisterInfo *MRI = &MF->getRegInfo();
6838   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6839   MachineFrameInfo *MFI = MF->getFrameInfo();
6840   int FI = MFI->getFunctionContextIndex();
6841
6842   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6843     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6844     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6845
6846   // Get a mapping of the call site numbers to all of the landing pads they're
6847   // associated with.
6848   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6849   unsigned MaxCSNum = 0;
6850   MachineModuleInfo &MMI = MF->getMMI();
6851   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6852        ++BB) {
6853     if (!BB->isLandingPad()) continue;
6854
6855     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6856     // pad.
6857     for (MachineBasicBlock::iterator
6858            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6859       if (!II->isEHLabel()) continue;
6860
6861       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6862       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6863
6864       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6865       for (SmallVectorImpl<unsigned>::iterator
6866              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6867            CSI != CSE; ++CSI) {
6868         CallSiteNumToLPad[*CSI].push_back(BB);
6869         MaxCSNum = std::max(MaxCSNum, *CSI);
6870       }
6871       break;
6872     }
6873   }
6874
6875   // Get an ordered list of the machine basic blocks for the jump table.
6876   std::vector<MachineBasicBlock*> LPadList;
6877   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6878   LPadList.reserve(CallSiteNumToLPad.size());
6879   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6880     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6881     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6882            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6883       LPadList.push_back(*II);
6884       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6885     }
6886   }
6887
6888   assert(!LPadList.empty() &&
6889          "No landing pad destinations for the dispatch jump table!");
6890
6891   // Create the jump table and associated information.
6892   MachineJumpTableInfo *JTI =
6893     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6894   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6895   unsigned UId = AFI->createJumpTableUId();
6896   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6897
6898   // Create the MBBs for the dispatch code.
6899
6900   // Shove the dispatch's address into the return slot in the function context.
6901   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6902   DispatchBB->setIsLandingPad();
6903
6904   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6905   unsigned trap_opcode;
6906   if (Subtarget->isThumb())
6907     trap_opcode = ARM::tTRAP;
6908   else
6909     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6910
6911   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6912   DispatchBB->addSuccessor(TrapBB);
6913
6914   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6915   DispatchBB->addSuccessor(DispContBB);
6916
6917   // Insert and MBBs.
6918   MF->insert(MF->end(), DispatchBB);
6919   MF->insert(MF->end(), DispContBB);
6920   MF->insert(MF->end(), TrapBB);
6921
6922   // Insert code into the entry block that creates and registers the function
6923   // context.
6924   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6925
6926   MachineMemOperand *FIMMOLd =
6927     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6928                              MachineMemOperand::MOLoad |
6929                              MachineMemOperand::MOVolatile, 4, 4);
6930
6931   MachineInstrBuilder MIB;
6932   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6933
6934   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6935   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6936
6937   // Add a register mask with no preserved registers.  This results in all
6938   // registers being marked as clobbered.
6939   MIB.addRegMask(RI.getNoPreservedMask());
6940
6941   unsigned NumLPads = LPadList.size();
6942   if (Subtarget->isThumb2()) {
6943     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6944     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6945                    .addFrameIndex(FI)
6946                    .addImm(4)
6947                    .addMemOperand(FIMMOLd));
6948
6949     if (NumLPads < 256) {
6950       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6951                      .addReg(NewVReg1)
6952                      .addImm(LPadList.size()));
6953     } else {
6954       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6955       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6956                      .addImm(NumLPads & 0xFFFF));
6957
6958       unsigned VReg2 = VReg1;
6959       if ((NumLPads & 0xFFFF0000) != 0) {
6960         VReg2 = MRI->createVirtualRegister(TRC);
6961         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6962                        .addReg(VReg1)
6963                        .addImm(NumLPads >> 16));
6964       }
6965
6966       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6967                      .addReg(NewVReg1)
6968                      .addReg(VReg2));
6969     }
6970
6971     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6972       .addMBB(TrapBB)
6973       .addImm(ARMCC::HI)
6974       .addReg(ARM::CPSR);
6975
6976     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6977     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6978                    .addJumpTableIndex(MJTI)
6979                    .addImm(UId));
6980
6981     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6982     AddDefaultCC(
6983       AddDefaultPred(
6984         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6985         .addReg(NewVReg3, RegState::Kill)
6986         .addReg(NewVReg1)
6987         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6988
6989     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6990       .addReg(NewVReg4, RegState::Kill)
6991       .addReg(NewVReg1)
6992       .addJumpTableIndex(MJTI)
6993       .addImm(UId);
6994   } else if (Subtarget->isThumb()) {
6995     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6996     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6997                    .addFrameIndex(FI)
6998                    .addImm(1)
6999                    .addMemOperand(FIMMOLd));
7000
7001     if (NumLPads < 256) {
7002       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7003                      .addReg(NewVReg1)
7004                      .addImm(NumLPads));
7005     } else {
7006       MachineConstantPool *ConstantPool = MF->getConstantPool();
7007       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7008       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7009
7010       // MachineConstantPool wants an explicit alignment.
7011       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7012       if (Align == 0)
7013         Align = getDataLayout()->getTypeAllocSize(C->getType());
7014       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7015
7016       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7017       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7018                      .addReg(VReg1, RegState::Define)
7019                      .addConstantPoolIndex(Idx));
7020       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7021                      .addReg(NewVReg1)
7022                      .addReg(VReg1));
7023     }
7024
7025     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7026       .addMBB(TrapBB)
7027       .addImm(ARMCC::HI)
7028       .addReg(ARM::CPSR);
7029
7030     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7031     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7032                    .addReg(ARM::CPSR, RegState::Define)
7033                    .addReg(NewVReg1)
7034                    .addImm(2));
7035
7036     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7037     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7038                    .addJumpTableIndex(MJTI)
7039                    .addImm(UId));
7040
7041     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7042     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7043                    .addReg(ARM::CPSR, RegState::Define)
7044                    .addReg(NewVReg2, RegState::Kill)
7045                    .addReg(NewVReg3));
7046
7047     MachineMemOperand *JTMMOLd =
7048       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7049                                MachineMemOperand::MOLoad, 4, 4);
7050
7051     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7052     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7053                    .addReg(NewVReg4, RegState::Kill)
7054                    .addImm(0)
7055                    .addMemOperand(JTMMOLd));
7056
7057     unsigned NewVReg6 = NewVReg5;
7058     if (RelocM == Reloc::PIC_) {
7059       NewVReg6 = MRI->createVirtualRegister(TRC);
7060       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7061                      .addReg(ARM::CPSR, RegState::Define)
7062                      .addReg(NewVReg5, RegState::Kill)
7063                      .addReg(NewVReg3));
7064     }
7065
7066     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7067       .addReg(NewVReg6, RegState::Kill)
7068       .addJumpTableIndex(MJTI)
7069       .addImm(UId);
7070   } else {
7071     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7072     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7073                    .addFrameIndex(FI)
7074                    .addImm(4)
7075                    .addMemOperand(FIMMOLd));
7076
7077     if (NumLPads < 256) {
7078       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7079                      .addReg(NewVReg1)
7080                      .addImm(NumLPads));
7081     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7082       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7083       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7084                      .addImm(NumLPads & 0xFFFF));
7085
7086       unsigned VReg2 = VReg1;
7087       if ((NumLPads & 0xFFFF0000) != 0) {
7088         VReg2 = MRI->createVirtualRegister(TRC);
7089         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7090                        .addReg(VReg1)
7091                        .addImm(NumLPads >> 16));
7092       }
7093
7094       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7095                      .addReg(NewVReg1)
7096                      .addReg(VReg2));
7097     } else {
7098       MachineConstantPool *ConstantPool = MF->getConstantPool();
7099       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7100       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7101
7102       // MachineConstantPool wants an explicit alignment.
7103       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7104       if (Align == 0)
7105         Align = getDataLayout()->getTypeAllocSize(C->getType());
7106       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7107
7108       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7109       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7110                      .addReg(VReg1, RegState::Define)
7111                      .addConstantPoolIndex(Idx)
7112                      .addImm(0));
7113       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7114                      .addReg(NewVReg1)
7115                      .addReg(VReg1, RegState::Kill));
7116     }
7117
7118     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7119       .addMBB(TrapBB)
7120       .addImm(ARMCC::HI)
7121       .addReg(ARM::CPSR);
7122
7123     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7124     AddDefaultCC(
7125       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7126                      .addReg(NewVReg1)
7127                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7128     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7129     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7130                    .addJumpTableIndex(MJTI)
7131                    .addImm(UId));
7132
7133     MachineMemOperand *JTMMOLd =
7134       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7135                                MachineMemOperand::MOLoad, 4, 4);
7136     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7137     AddDefaultPred(
7138       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7139       .addReg(NewVReg3, RegState::Kill)
7140       .addReg(NewVReg4)
7141       .addImm(0)
7142       .addMemOperand(JTMMOLd));
7143
7144     if (RelocM == Reloc::PIC_) {
7145       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7146         .addReg(NewVReg5, RegState::Kill)
7147         .addReg(NewVReg4)
7148         .addJumpTableIndex(MJTI)
7149         .addImm(UId);
7150     } else {
7151       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7152         .addReg(NewVReg5, RegState::Kill)
7153         .addJumpTableIndex(MJTI)
7154         .addImm(UId);
7155     }
7156   }
7157
7158   // Add the jump table entries as successors to the MBB.
7159   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7160   for (std::vector<MachineBasicBlock*>::iterator
7161          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7162     MachineBasicBlock *CurMBB = *I;
7163     if (SeenMBBs.insert(CurMBB))
7164       DispContBB->addSuccessor(CurMBB);
7165   }
7166
7167   // N.B. the order the invoke BBs are processed in doesn't matter here.
7168   const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
7169   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7170   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
7171          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
7172     MachineBasicBlock *BB = *I;
7173
7174     // Remove the landing pad successor from the invoke block and replace it
7175     // with the new dispatch block.
7176     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7177                                                   BB->succ_end());
7178     while (!Successors.empty()) {
7179       MachineBasicBlock *SMBB = Successors.pop_back_val();
7180       if (SMBB->isLandingPad()) {
7181         BB->removeSuccessor(SMBB);
7182         MBBLPads.push_back(SMBB);
7183       }
7184     }
7185
7186     BB->addSuccessor(DispatchBB);
7187
7188     // Find the invoke call and mark all of the callee-saved registers as
7189     // 'implicit defined' so that they're spilled. This prevents code from
7190     // moving instructions to before the EH block, where they will never be
7191     // executed.
7192     for (MachineBasicBlock::reverse_iterator
7193            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7194       if (!II->isCall()) continue;
7195
7196       DenseMap<unsigned, bool> DefRegs;
7197       for (MachineInstr::mop_iterator
7198              OI = II->operands_begin(), OE = II->operands_end();
7199            OI != OE; ++OI) {
7200         if (!OI->isReg()) continue;
7201         DefRegs[OI->getReg()] = true;
7202       }
7203
7204       MachineInstrBuilder MIB(*MF, &*II);
7205
7206       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7207         unsigned Reg = SavedRegs[i];
7208         if (Subtarget->isThumb2() &&
7209             !ARM::tGPRRegClass.contains(Reg) &&
7210             !ARM::hGPRRegClass.contains(Reg))
7211           continue;
7212         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7213           continue;
7214         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7215           continue;
7216         if (!DefRegs[Reg])
7217           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7218       }
7219
7220       break;
7221     }
7222   }
7223
7224   // Mark all former landing pads as non-landing pads. The dispatch is the only
7225   // landing pad now.
7226   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7227          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7228     (*I)->setIsLandingPad(false);
7229
7230   // The instruction is gone now.
7231   MI->eraseFromParent();
7232
7233   return MBB;
7234 }
7235
7236 static
7237 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7238   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7239        E = MBB->succ_end(); I != E; ++I)
7240     if (*I != Succ)
7241       return *I;
7242   llvm_unreachable("Expecting a BB with two successors!");
7243 }
7244
7245 MachineBasicBlock *ARMTargetLowering::
7246 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
7247   // This pseudo instruction has 3 operands: dst, src, size
7248   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7249   // Otherwise, we will generate unrolled scalar copies.
7250   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7251   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7252   MachineFunction::iterator It = BB;
7253   ++It;
7254
7255   unsigned dest = MI->getOperand(0).getReg();
7256   unsigned src = MI->getOperand(1).getReg();
7257   unsigned SizeVal = MI->getOperand(2).getImm();
7258   unsigned Align = MI->getOperand(3).getImm();
7259   DebugLoc dl = MI->getDebugLoc();
7260
7261   bool isThumb2 = Subtarget->isThumb2();
7262   MachineFunction *MF = BB->getParent();
7263   MachineRegisterInfo &MRI = MF->getRegInfo();
7264   unsigned ldrOpc, strOpc, UnitSize = 0;
7265
7266   const TargetRegisterClass *TRC = isThumb2 ?
7267     (const TargetRegisterClass*)&ARM::tGPRRegClass :
7268     (const TargetRegisterClass*)&ARM::GPRRegClass;
7269   const TargetRegisterClass *TRC_Vec = 0;
7270
7271   if (Align & 1) {
7272     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
7273     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
7274     UnitSize = 1;
7275   } else if (Align & 2) {
7276     ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
7277     strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
7278     UnitSize = 2;
7279   } else {
7280     // Check whether we can use NEON instructions.
7281     if (!MF->getFunction()->getAttributes().
7282           hasAttribute(AttributeSet::FunctionIndex,
7283                        Attribute::NoImplicitFloat) &&
7284         Subtarget->hasNEON()) {
7285       if ((Align % 16 == 0) && SizeVal >= 16) {
7286         ldrOpc = ARM::VLD1q32wb_fixed;
7287         strOpc = ARM::VST1q32wb_fixed;
7288         UnitSize = 16;
7289         TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
7290       }
7291       else if ((Align % 8 == 0) && SizeVal >= 8) {
7292         ldrOpc = ARM::VLD1d32wb_fixed;
7293         strOpc = ARM::VST1d32wb_fixed;
7294         UnitSize = 8;
7295         TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
7296       }
7297     }
7298     // Can't use NEON instructions.
7299     if (UnitSize == 0) {
7300       ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
7301       strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
7302       UnitSize = 4;
7303     }
7304   }
7305
7306   unsigned BytesLeft = SizeVal % UnitSize;
7307   unsigned LoopSize = SizeVal - BytesLeft;
7308
7309   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7310     // Use LDR and STR to copy.
7311     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7312     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7313     unsigned srcIn = src;
7314     unsigned destIn = dest;
7315     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7316       unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
7317       unsigned srcOut = MRI.createVirtualRegister(TRC);
7318       unsigned destOut = MRI.createVirtualRegister(TRC);
7319       if (UnitSize >= 8) {
7320         AddDefaultPred(BuildMI(*BB, MI, dl,
7321           TII->get(ldrOpc), scratch)
7322           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
7323
7324         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7325           .addReg(destIn).addImm(0).addReg(scratch));
7326       } else if (isThumb2) {
7327         AddDefaultPred(BuildMI(*BB, MI, dl,
7328           TII->get(ldrOpc), scratch)
7329           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
7330
7331         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7332           .addReg(scratch).addReg(destIn)
7333           .addImm(UnitSize));
7334       } else {
7335         AddDefaultPred(BuildMI(*BB, MI, dl,
7336           TII->get(ldrOpc), scratch)
7337           .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
7338           .addImm(UnitSize));
7339
7340         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7341           .addReg(scratch).addReg(destIn)
7342           .addReg(0).addImm(UnitSize));
7343       }
7344       srcIn = srcOut;
7345       destIn = destOut;
7346     }
7347
7348     // Handle the leftover bytes with LDRB and STRB.
7349     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7350     // [destOut] = STRB_POST(scratch, destIn, 1)
7351     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
7352     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
7353     for (unsigned i = 0; i < BytesLeft; i++) {
7354       unsigned scratch = MRI.createVirtualRegister(TRC);
7355       unsigned srcOut = MRI.createVirtualRegister(TRC);
7356       unsigned destOut = MRI.createVirtualRegister(TRC);
7357       if (isThumb2) {
7358         AddDefaultPred(BuildMI(*BB, MI, dl,
7359           TII->get(ldrOpc),scratch)
7360           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
7361
7362         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7363           .addReg(scratch).addReg(destIn)
7364           .addReg(0).addImm(1));
7365       } else {
7366         AddDefaultPred(BuildMI(*BB, MI, dl,
7367           TII->get(ldrOpc),scratch)
7368           .addReg(srcOut, RegState::Define).addReg(srcIn)
7369           .addReg(0).addImm(1));
7370
7371         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7372           .addReg(scratch).addReg(destIn)
7373           .addReg(0).addImm(1));
7374       }
7375       srcIn = srcOut;
7376       destIn = destOut;
7377     }
7378     MI->eraseFromParent();   // The instruction is gone now.
7379     return BB;
7380   }
7381
7382   // Expand the pseudo op to a loop.
7383   // thisMBB:
7384   //   ...
7385   //   movw varEnd, # --> with thumb2
7386   //   movt varEnd, #
7387   //   ldrcp varEnd, idx --> without thumb2
7388   //   fallthrough --> loopMBB
7389   // loopMBB:
7390   //   PHI varPhi, varEnd, varLoop
7391   //   PHI srcPhi, src, srcLoop
7392   //   PHI destPhi, dst, destLoop
7393   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7394   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7395   //   subs varLoop, varPhi, #UnitSize
7396   //   bne loopMBB
7397   //   fallthrough --> exitMBB
7398   // exitMBB:
7399   //   epilogue to handle left-over bytes
7400   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7401   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7402   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7403   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7404   MF->insert(It, loopMBB);
7405   MF->insert(It, exitMBB);
7406
7407   // Transfer the remainder of BB and its successor edges to exitMBB.
7408   exitMBB->splice(exitMBB->begin(), BB,
7409                   llvm::next(MachineBasicBlock::iterator(MI)),
7410                   BB->end());
7411   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7412
7413   // Load an immediate to varEnd.
7414   unsigned varEnd = MRI.createVirtualRegister(TRC);
7415   if (isThumb2) {
7416     unsigned VReg1 = varEnd;
7417     if ((LoopSize & 0xFFFF0000) != 0)
7418       VReg1 = MRI.createVirtualRegister(TRC);
7419     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
7420                    .addImm(LoopSize & 0xFFFF));
7421
7422     if ((LoopSize & 0xFFFF0000) != 0)
7423       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7424                      .addReg(VReg1)
7425                      .addImm(LoopSize >> 16));
7426   } else {
7427     MachineConstantPool *ConstantPool = MF->getConstantPool();
7428     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7429     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7430
7431     // MachineConstantPool wants an explicit alignment.
7432     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7433     if (Align == 0)
7434       Align = getDataLayout()->getTypeAllocSize(C->getType());
7435     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7436
7437     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
7438                    .addReg(varEnd, RegState::Define)
7439                    .addConstantPoolIndex(Idx)
7440                    .addImm(0));
7441   }
7442   BB->addSuccessor(loopMBB);
7443
7444   // Generate the loop body:
7445   //   varPhi = PHI(varLoop, varEnd)
7446   //   srcPhi = PHI(srcLoop, src)
7447   //   destPhi = PHI(destLoop, dst)
7448   MachineBasicBlock *entryBB = BB;
7449   BB = loopMBB;
7450   unsigned varLoop = MRI.createVirtualRegister(TRC);
7451   unsigned varPhi = MRI.createVirtualRegister(TRC);
7452   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7453   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7454   unsigned destLoop = MRI.createVirtualRegister(TRC);
7455   unsigned destPhi = MRI.createVirtualRegister(TRC);
7456
7457   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7458     .addReg(varLoop).addMBB(loopMBB)
7459     .addReg(varEnd).addMBB(entryBB);
7460   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7461     .addReg(srcLoop).addMBB(loopMBB)
7462     .addReg(src).addMBB(entryBB);
7463   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7464     .addReg(destLoop).addMBB(loopMBB)
7465     .addReg(dest).addMBB(entryBB);
7466
7467   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7468   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7469   unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
7470   if (UnitSize >= 8) {
7471     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7472       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
7473
7474     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7475       .addReg(destPhi).addImm(0).addReg(scratch));
7476   } else if (isThumb2) {
7477     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7478       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
7479
7480     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7481       .addReg(scratch).addReg(destPhi)
7482       .addImm(UnitSize));
7483   } else {
7484     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7485       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
7486       .addImm(UnitSize));
7487
7488     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7489       .addReg(scratch).addReg(destPhi)
7490       .addReg(0).addImm(UnitSize));
7491   }
7492
7493   // Decrement loop variable by UnitSize.
7494   MachineInstrBuilder MIB = BuildMI(BB, dl,
7495     TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7496   AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7497   MIB->getOperand(5).setReg(ARM::CPSR);
7498   MIB->getOperand(5).setIsDef(true);
7499
7500   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7501     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7502
7503   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7504   BB->addSuccessor(loopMBB);
7505   BB->addSuccessor(exitMBB);
7506
7507   // Add epilogue to handle BytesLeft.
7508   BB = exitMBB;
7509   MachineInstr *StartOfExit = exitMBB->begin();
7510   ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
7511   strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
7512
7513   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7514   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7515   unsigned srcIn = srcLoop;
7516   unsigned destIn = destLoop;
7517   for (unsigned i = 0; i < BytesLeft; i++) {
7518     unsigned scratch = MRI.createVirtualRegister(TRC);
7519     unsigned srcOut = MRI.createVirtualRegister(TRC);
7520     unsigned destOut = MRI.createVirtualRegister(TRC);
7521     if (isThumb2) {
7522       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
7523         TII->get(ldrOpc),scratch)
7524         .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
7525
7526       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
7527         .addReg(scratch).addReg(destIn)
7528         .addImm(1));
7529     } else {
7530       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
7531         TII->get(ldrOpc),scratch)
7532         .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
7533
7534       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
7535         .addReg(scratch).addReg(destIn)
7536         .addReg(0).addImm(1));
7537     }
7538     srcIn = srcOut;
7539     destIn = destOut;
7540   }
7541
7542   MI->eraseFromParent();   // The instruction is gone now.
7543   return BB;
7544 }
7545
7546 MachineBasicBlock *
7547 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7548                                                MachineBasicBlock *BB) const {
7549   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7550   DebugLoc dl = MI->getDebugLoc();
7551   bool isThumb2 = Subtarget->isThumb2();
7552   switch (MI->getOpcode()) {
7553   default: {
7554     MI->dump();
7555     llvm_unreachable("Unexpected instr type to insert");
7556   }
7557   // The Thumb2 pre-indexed stores have the same MI operands, they just
7558   // define them differently in the .td files from the isel patterns, so
7559   // they need pseudos.
7560   case ARM::t2STR_preidx:
7561     MI->setDesc(TII->get(ARM::t2STR_PRE));
7562     return BB;
7563   case ARM::t2STRB_preidx:
7564     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7565     return BB;
7566   case ARM::t2STRH_preidx:
7567     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7568     return BB;
7569
7570   case ARM::STRi_preidx:
7571   case ARM::STRBi_preidx: {
7572     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7573       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7574     // Decode the offset.
7575     unsigned Offset = MI->getOperand(4).getImm();
7576     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7577     Offset = ARM_AM::getAM2Offset(Offset);
7578     if (isSub)
7579       Offset = -Offset;
7580
7581     MachineMemOperand *MMO = *MI->memoperands_begin();
7582     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7583       .addOperand(MI->getOperand(0))  // Rn_wb
7584       .addOperand(MI->getOperand(1))  // Rt
7585       .addOperand(MI->getOperand(2))  // Rn
7586       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7587       .addOperand(MI->getOperand(5))  // pred
7588       .addOperand(MI->getOperand(6))
7589       .addMemOperand(MMO);
7590     MI->eraseFromParent();
7591     return BB;
7592   }
7593   case ARM::STRr_preidx:
7594   case ARM::STRBr_preidx:
7595   case ARM::STRH_preidx: {
7596     unsigned NewOpc;
7597     switch (MI->getOpcode()) {
7598     default: llvm_unreachable("unexpected opcode!");
7599     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7600     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7601     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7602     }
7603     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7604     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7605       MIB.addOperand(MI->getOperand(i));
7606     MI->eraseFromParent();
7607     return BB;
7608   }
7609   case ARM::ATOMIC_LOAD_ADD_I8:
7610      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7611   case ARM::ATOMIC_LOAD_ADD_I16:
7612      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7613   case ARM::ATOMIC_LOAD_ADD_I32:
7614      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7615
7616   case ARM::ATOMIC_LOAD_AND_I8:
7617      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7618   case ARM::ATOMIC_LOAD_AND_I16:
7619      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7620   case ARM::ATOMIC_LOAD_AND_I32:
7621      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7622
7623   case ARM::ATOMIC_LOAD_OR_I8:
7624      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7625   case ARM::ATOMIC_LOAD_OR_I16:
7626      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7627   case ARM::ATOMIC_LOAD_OR_I32:
7628      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7629
7630   case ARM::ATOMIC_LOAD_XOR_I8:
7631      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7632   case ARM::ATOMIC_LOAD_XOR_I16:
7633      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7634   case ARM::ATOMIC_LOAD_XOR_I32:
7635      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7636
7637   case ARM::ATOMIC_LOAD_NAND_I8:
7638      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7639   case ARM::ATOMIC_LOAD_NAND_I16:
7640      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7641   case ARM::ATOMIC_LOAD_NAND_I32:
7642      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7643
7644   case ARM::ATOMIC_LOAD_SUB_I8:
7645      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7646   case ARM::ATOMIC_LOAD_SUB_I16:
7647      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7648   case ARM::ATOMIC_LOAD_SUB_I32:
7649      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7650
7651   case ARM::ATOMIC_LOAD_MIN_I8:
7652      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7653   case ARM::ATOMIC_LOAD_MIN_I16:
7654      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7655   case ARM::ATOMIC_LOAD_MIN_I32:
7656      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7657
7658   case ARM::ATOMIC_LOAD_MAX_I8:
7659      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7660   case ARM::ATOMIC_LOAD_MAX_I16:
7661      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7662   case ARM::ATOMIC_LOAD_MAX_I32:
7663      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7664
7665   case ARM::ATOMIC_LOAD_UMIN_I8:
7666      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7667   case ARM::ATOMIC_LOAD_UMIN_I16:
7668      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7669   case ARM::ATOMIC_LOAD_UMIN_I32:
7670      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7671
7672   case ARM::ATOMIC_LOAD_UMAX_I8:
7673      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7674   case ARM::ATOMIC_LOAD_UMAX_I16:
7675      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7676   case ARM::ATOMIC_LOAD_UMAX_I32:
7677      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7678
7679   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
7680   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7681   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7682
7683   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
7684   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7685   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7686
7687   case ARM::ATOMIC_LOAD_I64:
7688     return EmitAtomicLoad64(MI, BB);
7689
7690   case ARM::ATOMIC_LOAD_ADD_I64:
7691     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7692                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7693                               /*NeedsCarry*/ true);
7694   case ARM::ATOMIC_LOAD_SUB_I64:
7695     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7696                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7697                               /*NeedsCarry*/ true);
7698   case ARM::ATOMIC_LOAD_OR_I64:
7699     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7700                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7701   case ARM::ATOMIC_LOAD_XOR_I64:
7702     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7703                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7704   case ARM::ATOMIC_LOAD_AND_I64:
7705     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7706                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7707   case ARM::ATOMIC_STORE_I64:
7708   case ARM::ATOMIC_SWAP_I64:
7709     return EmitAtomicBinary64(MI, BB, 0, 0, false);
7710   case ARM::ATOMIC_CMP_SWAP_I64:
7711     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7712                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7713                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7714   case ARM::ATOMIC_LOAD_MIN_I64:
7715     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7716                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7717                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7718                               /*IsMinMax*/ true, ARMCC::LT);
7719   case ARM::ATOMIC_LOAD_MAX_I64:
7720     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7721                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7722                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7723                               /*IsMinMax*/ true, ARMCC::GE);
7724   case ARM::ATOMIC_LOAD_UMIN_I64:
7725     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7726                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7727                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7728                               /*IsMinMax*/ true, ARMCC::LO);
7729   case ARM::ATOMIC_LOAD_UMAX_I64:
7730     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7731                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7732                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7733                               /*IsMinMax*/ true, ARMCC::HS);
7734
7735   case ARM::tMOVCCr_pseudo: {
7736     // To "insert" a SELECT_CC instruction, we actually have to insert the
7737     // diamond control-flow pattern.  The incoming instruction knows the
7738     // destination vreg to set, the condition code register to branch on, the
7739     // true/false values to select between, and a branch opcode to use.
7740     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7741     MachineFunction::iterator It = BB;
7742     ++It;
7743
7744     //  thisMBB:
7745     //  ...
7746     //   TrueVal = ...
7747     //   cmpTY ccX, r1, r2
7748     //   bCC copy1MBB
7749     //   fallthrough --> copy0MBB
7750     MachineBasicBlock *thisMBB  = BB;
7751     MachineFunction *F = BB->getParent();
7752     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7753     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7754     F->insert(It, copy0MBB);
7755     F->insert(It, sinkMBB);
7756
7757     // Transfer the remainder of BB and its successor edges to sinkMBB.
7758     sinkMBB->splice(sinkMBB->begin(), BB,
7759                     llvm::next(MachineBasicBlock::iterator(MI)),
7760                     BB->end());
7761     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7762
7763     BB->addSuccessor(copy0MBB);
7764     BB->addSuccessor(sinkMBB);
7765
7766     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7767       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7768
7769     //  copy0MBB:
7770     //   %FalseValue = ...
7771     //   # fallthrough to sinkMBB
7772     BB = copy0MBB;
7773
7774     // Update machine-CFG edges
7775     BB->addSuccessor(sinkMBB);
7776
7777     //  sinkMBB:
7778     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7779     //  ...
7780     BB = sinkMBB;
7781     BuildMI(*BB, BB->begin(), dl,
7782             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7783       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7784       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7785
7786     MI->eraseFromParent();   // The pseudo instruction is gone now.
7787     return BB;
7788   }
7789
7790   case ARM::BCCi64:
7791   case ARM::BCCZi64: {
7792     // If there is an unconditional branch to the other successor, remove it.
7793     BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
7794
7795     // Compare both parts that make up the double comparison separately for
7796     // equality.
7797     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7798
7799     unsigned LHS1 = MI->getOperand(1).getReg();
7800     unsigned LHS2 = MI->getOperand(2).getReg();
7801     if (RHSisZero) {
7802       AddDefaultPred(BuildMI(BB, dl,
7803                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7804                      .addReg(LHS1).addImm(0));
7805       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7806         .addReg(LHS2).addImm(0)
7807         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7808     } else {
7809       unsigned RHS1 = MI->getOperand(3).getReg();
7810       unsigned RHS2 = MI->getOperand(4).getReg();
7811       AddDefaultPred(BuildMI(BB, dl,
7812                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7813                      .addReg(LHS1).addReg(RHS1));
7814       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7815         .addReg(LHS2).addReg(RHS2)
7816         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7817     }
7818
7819     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7820     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7821     if (MI->getOperand(0).getImm() == ARMCC::NE)
7822       std::swap(destMBB, exitMBB);
7823
7824     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7825       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7826     if (isThumb2)
7827       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7828     else
7829       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7830
7831     MI->eraseFromParent();   // The pseudo instruction is gone now.
7832     return BB;
7833   }
7834
7835   case ARM::Int_eh_sjlj_setjmp:
7836   case ARM::Int_eh_sjlj_setjmp_nofp:
7837   case ARM::tInt_eh_sjlj_setjmp:
7838   case ARM::t2Int_eh_sjlj_setjmp:
7839   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7840     EmitSjLjDispatchBlock(MI, BB);
7841     return BB;
7842
7843   case ARM::ABS:
7844   case ARM::t2ABS: {
7845     // To insert an ABS instruction, we have to insert the
7846     // diamond control-flow pattern.  The incoming instruction knows the
7847     // source vreg to test against 0, the destination vreg to set,
7848     // the condition code register to branch on, the
7849     // true/false values to select between, and a branch opcode to use.
7850     // It transforms
7851     //     V1 = ABS V0
7852     // into
7853     //     V2 = MOVS V0
7854     //     BCC                      (branch to SinkBB if V0 >= 0)
7855     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7856     //     SinkBB: V1 = PHI(V2, V3)
7857     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7858     MachineFunction::iterator BBI = BB;
7859     ++BBI;
7860     MachineFunction *Fn = BB->getParent();
7861     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7862     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7863     Fn->insert(BBI, RSBBB);
7864     Fn->insert(BBI, SinkBB);
7865
7866     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7867     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7868     bool isThumb2 = Subtarget->isThumb2();
7869     MachineRegisterInfo &MRI = Fn->getRegInfo();
7870     // In Thumb mode S must not be specified if source register is the SP or
7871     // PC and if destination register is the SP, so restrict register class
7872     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7873       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7874       (const TargetRegisterClass*)&ARM::GPRRegClass);
7875
7876     // Transfer the remainder of BB and its successor edges to sinkMBB.
7877     SinkBB->splice(SinkBB->begin(), BB,
7878       llvm::next(MachineBasicBlock::iterator(MI)),
7879       BB->end());
7880     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7881
7882     BB->addSuccessor(RSBBB);
7883     BB->addSuccessor(SinkBB);
7884
7885     // fall through to SinkMBB
7886     RSBBB->addSuccessor(SinkBB);
7887
7888     // insert a cmp at the end of BB
7889     AddDefaultPred(BuildMI(BB, dl,
7890                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7891                    .addReg(ABSSrcReg).addImm(0));
7892
7893     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7894     BuildMI(BB, dl,
7895       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7896       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7897
7898     // insert rsbri in RSBBB
7899     // Note: BCC and rsbri will be converted into predicated rsbmi
7900     // by if-conversion pass
7901     BuildMI(*RSBBB, RSBBB->begin(), dl,
7902       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7903       .addReg(ABSSrcReg, RegState::Kill)
7904       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7905
7906     // insert PHI in SinkBB,
7907     // reuse ABSDstReg to not change uses of ABS instruction
7908     BuildMI(*SinkBB, SinkBB->begin(), dl,
7909       TII->get(ARM::PHI), ABSDstReg)
7910       .addReg(NewRsbDstReg).addMBB(RSBBB)
7911       .addReg(ABSSrcReg).addMBB(BB);
7912
7913     // remove ABS instruction
7914     MI->eraseFromParent();
7915
7916     // return last added BB
7917     return SinkBB;
7918   }
7919   case ARM::COPY_STRUCT_BYVAL_I32:
7920     ++NumLoopByVals;
7921     return EmitStructByval(MI, BB);
7922   }
7923 }
7924
7925 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7926                                                       SDNode *Node) const {
7927   if (!MI->hasPostISelHook()) {
7928     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7929            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7930     return;
7931   }
7932
7933   const MCInstrDesc *MCID = &MI->getDesc();
7934   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7935   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7936   // operand is still set to noreg. If needed, set the optional operand's
7937   // register to CPSR, and remove the redundant implicit def.
7938   //
7939   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7940
7941   // Rename pseudo opcodes.
7942   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7943   if (NewOpc) {
7944     const ARMBaseInstrInfo *TII =
7945       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7946     MCID = &TII->get(NewOpc);
7947
7948     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7949            "converted opcode should be the same except for cc_out");
7950
7951     MI->setDesc(*MCID);
7952
7953     // Add the optional cc_out operand
7954     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7955   }
7956   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7957
7958   // Any ARM instruction that sets the 's' bit should specify an optional
7959   // "cc_out" operand in the last operand position.
7960   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7961     assert(!NewOpc && "Optional cc_out operand required");
7962     return;
7963   }
7964   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7965   // since we already have an optional CPSR def.
7966   bool definesCPSR = false;
7967   bool deadCPSR = false;
7968   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7969        i != e; ++i) {
7970     const MachineOperand &MO = MI->getOperand(i);
7971     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7972       definesCPSR = true;
7973       if (MO.isDead())
7974         deadCPSR = true;
7975       MI->RemoveOperand(i);
7976       break;
7977     }
7978   }
7979   if (!definesCPSR) {
7980     assert(!NewOpc && "Optional cc_out operand required");
7981     return;
7982   }
7983   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7984   if (deadCPSR) {
7985     assert(!MI->getOperand(ccOutIdx).getReg() &&
7986            "expect uninitialized optional cc_out operand");
7987     return;
7988   }
7989
7990   // If this instruction was defined with an optional CPSR def and its dag node
7991   // had a live implicit CPSR def, then activate the optional CPSR def.
7992   MachineOperand &MO = MI->getOperand(ccOutIdx);
7993   MO.setReg(ARM::CPSR);
7994   MO.setIsDef(true);
7995 }
7996
7997 //===----------------------------------------------------------------------===//
7998 //                           ARM Optimization Hooks
7999 //===----------------------------------------------------------------------===//
8000
8001 // Helper function that checks if N is a null or all ones constant.
8002 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8003   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8004   if (!C)
8005     return false;
8006   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8007 }
8008
8009 // Return true if N is conditionally 0 or all ones.
8010 // Detects these expressions where cc is an i1 value:
8011 //
8012 //   (select cc 0, y)   [AllOnes=0]
8013 //   (select cc y, 0)   [AllOnes=0]
8014 //   (zext cc)          [AllOnes=0]
8015 //   (sext cc)          [AllOnes=0/1]
8016 //   (select cc -1, y)  [AllOnes=1]
8017 //   (select cc y, -1)  [AllOnes=1]
8018 //
8019 // Invert is set when N is the null/all ones constant when CC is false.
8020 // OtherOp is set to the alternative value of N.
8021 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8022                                        SDValue &CC, bool &Invert,
8023                                        SDValue &OtherOp,
8024                                        SelectionDAG &DAG) {
8025   switch (N->getOpcode()) {
8026   default: return false;
8027   case ISD::SELECT: {
8028     CC = N->getOperand(0);
8029     SDValue N1 = N->getOperand(1);
8030     SDValue N2 = N->getOperand(2);
8031     if (isZeroOrAllOnes(N1, AllOnes)) {
8032       Invert = false;
8033       OtherOp = N2;
8034       return true;
8035     }
8036     if (isZeroOrAllOnes(N2, AllOnes)) {
8037       Invert = true;
8038       OtherOp = N1;
8039       return true;
8040     }
8041     return false;
8042   }
8043   case ISD::ZERO_EXTEND:
8044     // (zext cc) can never be the all ones value.
8045     if (AllOnes)
8046       return false;
8047     // Fall through.
8048   case ISD::SIGN_EXTEND: {
8049     EVT VT = N->getValueType(0);
8050     CC = N->getOperand(0);
8051     if (CC.getValueType() != MVT::i1)
8052       return false;
8053     Invert = !AllOnes;
8054     if (AllOnes)
8055       // When looking for an AllOnes constant, N is an sext, and the 'other'
8056       // value is 0.
8057       OtherOp = DAG.getConstant(0, VT);
8058     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8059       // When looking for a 0 constant, N can be zext or sext.
8060       OtherOp = DAG.getConstant(1, VT);
8061     else
8062       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
8063     return true;
8064   }
8065   }
8066 }
8067
8068 // Combine a constant select operand into its use:
8069 //
8070 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
8071 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
8072 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
8073 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
8074 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
8075 //
8076 // The transform is rejected if the select doesn't have a constant operand that
8077 // is null, or all ones when AllOnes is set.
8078 //
8079 // Also recognize sext/zext from i1:
8080 //
8081 //   (add (zext cc), x) -> (select cc (add x, 1), x)
8082 //   (add (sext cc), x) -> (select cc (add x, -1), x)
8083 //
8084 // These transformations eventually create predicated instructions.
8085 //
8086 // @param N       The node to transform.
8087 // @param Slct    The N operand that is a select.
8088 // @param OtherOp The other N operand (x above).
8089 // @param DCI     Context.
8090 // @param AllOnes Require the select constant to be all ones instead of null.
8091 // @returns The new node, or SDValue() on failure.
8092 static
8093 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8094                             TargetLowering::DAGCombinerInfo &DCI,
8095                             bool AllOnes = false) {
8096   SelectionDAG &DAG = DCI.DAG;
8097   EVT VT = N->getValueType(0);
8098   SDValue NonConstantVal;
8099   SDValue CCOp;
8100   bool SwapSelectOps;
8101   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8102                                   NonConstantVal, DAG))
8103     return SDValue();
8104
8105   // Slct is now know to be the desired identity constant when CC is true.
8106   SDValue TrueVal = OtherOp;
8107   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8108                                  OtherOp, NonConstantVal);
8109   // Unless SwapSelectOps says CC should be false.
8110   if (SwapSelectOps)
8111     std::swap(TrueVal, FalseVal);
8112
8113   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8114                      CCOp, TrueVal, FalseVal);
8115 }
8116
8117 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8118 static
8119 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8120                                        TargetLowering::DAGCombinerInfo &DCI) {
8121   SDValue N0 = N->getOperand(0);
8122   SDValue N1 = N->getOperand(1);
8123   if (N0.getNode()->hasOneUse()) {
8124     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8125     if (Result.getNode())
8126       return Result;
8127   }
8128   if (N1.getNode()->hasOneUse()) {
8129     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8130     if (Result.getNode())
8131       return Result;
8132   }
8133   return SDValue();
8134 }
8135
8136 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8137 // (only after legalization).
8138 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8139                                  TargetLowering::DAGCombinerInfo &DCI,
8140                                  const ARMSubtarget *Subtarget) {
8141
8142   // Only perform optimization if after legalize, and if NEON is available. We
8143   // also expected both operands to be BUILD_VECTORs.
8144   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8145       || N0.getOpcode() != ISD::BUILD_VECTOR
8146       || N1.getOpcode() != ISD::BUILD_VECTOR)
8147     return SDValue();
8148
8149   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8150   EVT VT = N->getValueType(0);
8151   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8152     return SDValue();
8153
8154   // Check that the vector operands are of the right form.
8155   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8156   // operands, where N is the size of the formed vector.
8157   // Each EXTRACT_VECTOR should have the same input vector and odd or even
8158   // index such that we have a pair wise add pattern.
8159
8160   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8161   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8162     return SDValue();
8163   SDValue Vec = N0->getOperand(0)->getOperand(0);
8164   SDNode *V = Vec.getNode();
8165   unsigned nextIndex = 0;
8166
8167   // For each operands to the ADD which are BUILD_VECTORs,
8168   // check to see if each of their operands are an EXTRACT_VECTOR with
8169   // the same vector and appropriate index.
8170   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8171     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8172         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8173
8174       SDValue ExtVec0 = N0->getOperand(i);
8175       SDValue ExtVec1 = N1->getOperand(i);
8176
8177       // First operand is the vector, verify its the same.
8178       if (V != ExtVec0->getOperand(0).getNode() ||
8179           V != ExtVec1->getOperand(0).getNode())
8180         return SDValue();
8181
8182       // Second is the constant, verify its correct.
8183       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8184       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8185
8186       // For the constant, we want to see all the even or all the odd.
8187       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8188           || C1->getZExtValue() != nextIndex+1)
8189         return SDValue();
8190
8191       // Increment index.
8192       nextIndex+=2;
8193     } else
8194       return SDValue();
8195   }
8196
8197   // Create VPADDL node.
8198   SelectionDAG &DAG = DCI.DAG;
8199   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8200
8201   // Build operand list.
8202   SmallVector<SDValue, 8> Ops;
8203   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
8204                                 TLI.getPointerTy()));
8205
8206   // Input is the vector.
8207   Ops.push_back(Vec);
8208
8209   // Get widened type and narrowed type.
8210   MVT widenType;
8211   unsigned numElem = VT.getVectorNumElements();
8212   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8213     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8214     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8215     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8216     default:
8217       llvm_unreachable("Invalid vector element type for padd optimization.");
8218   }
8219
8220   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
8221                             widenType, &Ops[0], Ops.size());
8222   return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, tmp);
8223 }
8224
8225 static SDValue findMUL_LOHI(SDValue V) {
8226   if (V->getOpcode() == ISD::UMUL_LOHI ||
8227       V->getOpcode() == ISD::SMUL_LOHI)
8228     return V;
8229   return SDValue();
8230 }
8231
8232 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8233                                      TargetLowering::DAGCombinerInfo &DCI,
8234                                      const ARMSubtarget *Subtarget) {
8235
8236   if (Subtarget->isThumb1Only()) return SDValue();
8237
8238   // Only perform the checks after legalize when the pattern is available.
8239   if (DCI.isBeforeLegalize()) return SDValue();
8240
8241   // Look for multiply add opportunities.
8242   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8243   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8244   // a glue link from the first add to the second add.
8245   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8246   // a S/UMLAL instruction.
8247   //          loAdd   UMUL_LOHI
8248   //            \    / :lo    \ :hi
8249   //             \  /          \          [no multiline comment]
8250   //              ADDC         |  hiAdd
8251   //                 \ :glue  /  /
8252   //                  \      /  /
8253   //                    ADDE
8254   //
8255   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8256   SDValue AddcOp0 = AddcNode->getOperand(0);
8257   SDValue AddcOp1 = AddcNode->getOperand(1);
8258
8259   // Check if the two operands are from the same mul_lohi node.
8260   if (AddcOp0.getNode() == AddcOp1.getNode())
8261     return SDValue();
8262
8263   assert(AddcNode->getNumValues() == 2 &&
8264          AddcNode->getValueType(0) == MVT::i32 &&
8265          "Expect ADDC with two result values. First: i32");
8266
8267   // Check that we have a glued ADDC node.
8268   if (AddcNode->getValueType(1) != MVT::Glue)
8269     return SDValue();
8270
8271   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8272   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8273       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8274       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8275       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8276     return SDValue();
8277
8278   // Look for the glued ADDE.
8279   SDNode* AddeNode = AddcNode->getGluedUser();
8280   if (AddeNode == NULL)
8281     return SDValue();
8282
8283   // Make sure it is really an ADDE.
8284   if (AddeNode->getOpcode() != ISD::ADDE)
8285     return SDValue();
8286
8287   assert(AddeNode->getNumOperands() == 3 &&
8288          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8289          "ADDE node has the wrong inputs");
8290
8291   // Check for the triangle shape.
8292   SDValue AddeOp0 = AddeNode->getOperand(0);
8293   SDValue AddeOp1 = AddeNode->getOperand(1);
8294
8295   // Make sure that the ADDE operands are not coming from the same node.
8296   if (AddeOp0.getNode() == AddeOp1.getNode())
8297     return SDValue();
8298
8299   // Find the MUL_LOHI node walking up ADDE's operands.
8300   bool IsLeftOperandMUL = false;
8301   SDValue MULOp = findMUL_LOHI(AddeOp0);
8302   if (MULOp == SDValue())
8303    MULOp = findMUL_LOHI(AddeOp1);
8304   else
8305     IsLeftOperandMUL = true;
8306   if (MULOp == SDValue())
8307      return SDValue();
8308
8309   // Figure out the right opcode.
8310   unsigned Opc = MULOp->getOpcode();
8311   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8312
8313   // Figure out the high and low input values to the MLAL node.
8314   SDValue* HiMul = &MULOp;
8315   SDValue* HiAdd = NULL;
8316   SDValue* LoMul = NULL;
8317   SDValue* LowAdd = NULL;
8318
8319   if (IsLeftOperandMUL)
8320     HiAdd = &AddeOp1;
8321   else
8322     HiAdd = &AddeOp0;
8323
8324
8325   if (AddcOp0->getOpcode() == Opc) {
8326     LoMul = &AddcOp0;
8327     LowAdd = &AddcOp1;
8328   }
8329   if (AddcOp1->getOpcode() == Opc) {
8330     LoMul = &AddcOp1;
8331     LowAdd = &AddcOp0;
8332   }
8333
8334   if (LoMul == NULL)
8335     return SDValue();
8336
8337   if (LoMul->getNode() != HiMul->getNode())
8338     return SDValue();
8339
8340   // Create the merged node.
8341   SelectionDAG &DAG = DCI.DAG;
8342
8343   // Build operand list.
8344   SmallVector<SDValue, 8> Ops;
8345   Ops.push_back(LoMul->getOperand(0));
8346   Ops.push_back(LoMul->getOperand(1));
8347   Ops.push_back(*LowAdd);
8348   Ops.push_back(*HiAdd);
8349
8350   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8351                                  DAG.getVTList(MVT::i32, MVT::i32),
8352                                  &Ops[0], Ops.size());
8353
8354   // Replace the ADDs' nodes uses by the MLA node's values.
8355   SDValue HiMLALResult(MLALNode.getNode(), 1);
8356   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8357
8358   SDValue LoMLALResult(MLALNode.getNode(), 0);
8359   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8360
8361   // Return original node to notify the driver to stop replacing.
8362   SDValue resNode(AddcNode, 0);
8363   return resNode;
8364 }
8365
8366 /// PerformADDCCombine - Target-specific dag combine transform from
8367 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8368 static SDValue PerformADDCCombine(SDNode *N,
8369                                  TargetLowering::DAGCombinerInfo &DCI,
8370                                  const ARMSubtarget *Subtarget) {
8371
8372   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8373
8374 }
8375
8376 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8377 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8378 /// called with the default operands, and if that fails, with commuted
8379 /// operands.
8380 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8381                                           TargetLowering::DAGCombinerInfo &DCI,
8382                                           const ARMSubtarget *Subtarget){
8383
8384   // Attempt to create vpaddl for this add.
8385   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8386   if (Result.getNode())
8387     return Result;
8388
8389   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8390   if (N0.getNode()->hasOneUse()) {
8391     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8392     if (Result.getNode()) return Result;
8393   }
8394   return SDValue();
8395 }
8396
8397 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8398 ///
8399 static SDValue PerformADDCombine(SDNode *N,
8400                                  TargetLowering::DAGCombinerInfo &DCI,
8401                                  const ARMSubtarget *Subtarget) {
8402   SDValue N0 = N->getOperand(0);
8403   SDValue N1 = N->getOperand(1);
8404
8405   // First try with the default operand order.
8406   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8407   if (Result.getNode())
8408     return Result;
8409
8410   // If that didn't work, try again with the operands commuted.
8411   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8412 }
8413
8414 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8415 ///
8416 static SDValue PerformSUBCombine(SDNode *N,
8417                                  TargetLowering::DAGCombinerInfo &DCI) {
8418   SDValue N0 = N->getOperand(0);
8419   SDValue N1 = N->getOperand(1);
8420
8421   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8422   if (N1.getNode()->hasOneUse()) {
8423     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8424     if (Result.getNode()) return Result;
8425   }
8426
8427   return SDValue();
8428 }
8429
8430 /// PerformVMULCombine
8431 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8432 /// special multiplier accumulator forwarding.
8433 ///   vmul d3, d0, d2
8434 ///   vmla d3, d1, d2
8435 /// is faster than
8436 ///   vadd d3, d0, d1
8437 ///   vmul d3, d3, d2
8438 //  However, for (A + B) * (A + B),
8439 //    vadd d2, d0, d1
8440 //    vmul d3, d0, d2
8441 //    vmla d3, d1, d2
8442 //  is slower than
8443 //    vadd d2, d0, d1
8444 //    vmul d3, d2, d2
8445 static SDValue PerformVMULCombine(SDNode *N,
8446                                   TargetLowering::DAGCombinerInfo &DCI,
8447                                   const ARMSubtarget *Subtarget) {
8448   if (!Subtarget->hasVMLxForwarding())
8449     return SDValue();
8450
8451   SelectionDAG &DAG = DCI.DAG;
8452   SDValue N0 = N->getOperand(0);
8453   SDValue N1 = N->getOperand(1);
8454   unsigned Opcode = N0.getOpcode();
8455   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8456       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8457     Opcode = N1.getOpcode();
8458     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8459         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8460       return SDValue();
8461     std::swap(N0, N1);
8462   }
8463
8464   if (N0 == N1)
8465     return SDValue();
8466
8467   EVT VT = N->getValueType(0);
8468   SDLoc DL(N);
8469   SDValue N00 = N0->getOperand(0);
8470   SDValue N01 = N0->getOperand(1);
8471   return DAG.getNode(Opcode, DL, VT,
8472                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8473                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8474 }
8475
8476 static SDValue PerformMULCombine(SDNode *N,
8477                                  TargetLowering::DAGCombinerInfo &DCI,
8478                                  const ARMSubtarget *Subtarget) {
8479   SelectionDAG &DAG = DCI.DAG;
8480
8481   if (Subtarget->isThumb1Only())
8482     return SDValue();
8483
8484   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8485     return SDValue();
8486
8487   EVT VT = N->getValueType(0);
8488   if (VT.is64BitVector() || VT.is128BitVector())
8489     return PerformVMULCombine(N, DCI, Subtarget);
8490   if (VT != MVT::i32)
8491     return SDValue();
8492
8493   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8494   if (!C)
8495     return SDValue();
8496
8497   int64_t MulAmt = C->getSExtValue();
8498   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8499
8500   ShiftAmt = ShiftAmt & (32 - 1);
8501   SDValue V = N->getOperand(0);
8502   SDLoc DL(N);
8503
8504   SDValue Res;
8505   MulAmt >>= ShiftAmt;
8506
8507   if (MulAmt >= 0) {
8508     if (isPowerOf2_32(MulAmt - 1)) {
8509       // (mul x, 2^N + 1) => (add (shl x, N), x)
8510       Res = DAG.getNode(ISD::ADD, DL, VT,
8511                         V,
8512                         DAG.getNode(ISD::SHL, DL, VT,
8513                                     V,
8514                                     DAG.getConstant(Log2_32(MulAmt - 1),
8515                                                     MVT::i32)));
8516     } else if (isPowerOf2_32(MulAmt + 1)) {
8517       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8518       Res = DAG.getNode(ISD::SUB, DL, VT,
8519                         DAG.getNode(ISD::SHL, DL, VT,
8520                                     V,
8521                                     DAG.getConstant(Log2_32(MulAmt + 1),
8522                                                     MVT::i32)),
8523                         V);
8524     } else
8525       return SDValue();
8526   } else {
8527     uint64_t MulAmtAbs = -MulAmt;
8528     if (isPowerOf2_32(MulAmtAbs + 1)) {
8529       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8530       Res = DAG.getNode(ISD::SUB, DL, VT,
8531                         V,
8532                         DAG.getNode(ISD::SHL, DL, VT,
8533                                     V,
8534                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8535                                                     MVT::i32)));
8536     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8537       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8538       Res = DAG.getNode(ISD::ADD, DL, VT,
8539                         V,
8540                         DAG.getNode(ISD::SHL, DL, VT,
8541                                     V,
8542                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8543                                                     MVT::i32)));
8544       Res = DAG.getNode(ISD::SUB, DL, VT,
8545                         DAG.getConstant(0, MVT::i32),Res);
8546
8547     } else
8548       return SDValue();
8549   }
8550
8551   if (ShiftAmt != 0)
8552     Res = DAG.getNode(ISD::SHL, DL, VT,
8553                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8554
8555   // Do not add new nodes to DAG combiner worklist.
8556   DCI.CombineTo(N, Res, false);
8557   return SDValue();
8558 }
8559
8560 static SDValue PerformANDCombine(SDNode *N,
8561                                  TargetLowering::DAGCombinerInfo &DCI,
8562                                  const ARMSubtarget *Subtarget) {
8563
8564   // Attempt to use immediate-form VBIC
8565   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8566   SDLoc dl(N);
8567   EVT VT = N->getValueType(0);
8568   SelectionDAG &DAG = DCI.DAG;
8569
8570   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8571     return SDValue();
8572
8573   APInt SplatBits, SplatUndef;
8574   unsigned SplatBitSize;
8575   bool HasAnyUndefs;
8576   if (BVN &&
8577       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8578     if (SplatBitSize <= 64) {
8579       EVT VbicVT;
8580       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8581                                       SplatUndef.getZExtValue(), SplatBitSize,
8582                                       DAG, VbicVT, VT.is128BitVector(),
8583                                       OtherModImm);
8584       if (Val.getNode()) {
8585         SDValue Input =
8586           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8587         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8588         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8589       }
8590     }
8591   }
8592
8593   if (!Subtarget->isThumb1Only()) {
8594     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8595     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8596     if (Result.getNode())
8597       return Result;
8598   }
8599
8600   return SDValue();
8601 }
8602
8603 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8604 static SDValue PerformORCombine(SDNode *N,
8605                                 TargetLowering::DAGCombinerInfo &DCI,
8606                                 const ARMSubtarget *Subtarget) {
8607   // Attempt to use immediate-form VORR
8608   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8609   SDLoc dl(N);
8610   EVT VT = N->getValueType(0);
8611   SelectionDAG &DAG = DCI.DAG;
8612
8613   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8614     return SDValue();
8615
8616   APInt SplatBits, SplatUndef;
8617   unsigned SplatBitSize;
8618   bool HasAnyUndefs;
8619   if (BVN && Subtarget->hasNEON() &&
8620       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8621     if (SplatBitSize <= 64) {
8622       EVT VorrVT;
8623       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8624                                       SplatUndef.getZExtValue(), SplatBitSize,
8625                                       DAG, VorrVT, VT.is128BitVector(),
8626                                       OtherModImm);
8627       if (Val.getNode()) {
8628         SDValue Input =
8629           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8630         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8631         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8632       }
8633     }
8634   }
8635
8636   if (!Subtarget->isThumb1Only()) {
8637     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8638     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8639     if (Result.getNode())
8640       return Result;
8641   }
8642
8643   // The code below optimizes (or (and X, Y), Z).
8644   // The AND operand needs to have a single user to make these optimizations
8645   // profitable.
8646   SDValue N0 = N->getOperand(0);
8647   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8648     return SDValue();
8649   SDValue N1 = N->getOperand(1);
8650
8651   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8652   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8653       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8654     APInt SplatUndef;
8655     unsigned SplatBitSize;
8656     bool HasAnyUndefs;
8657
8658     APInt SplatBits0, SplatBits1;
8659     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8660     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8661     // Ensure that the second operand of both ands are constants
8662     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8663                                       HasAnyUndefs) && !HasAnyUndefs) {
8664         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8665                                           HasAnyUndefs) && !HasAnyUndefs) {
8666             // Ensure that the bit width of the constants are the same and that
8667             // the splat arguments are logical inverses as per the pattern we
8668             // are trying to simplify.
8669             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8670                 SplatBits0 == ~SplatBits1) {
8671                 // Canonicalize the vector type to make instruction selection
8672                 // simpler.
8673                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8674                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8675                                              N0->getOperand(1),
8676                                              N0->getOperand(0),
8677                                              N1->getOperand(0));
8678                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8679             }
8680         }
8681     }
8682   }
8683
8684   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8685   // reasonable.
8686
8687   // BFI is only available on V6T2+
8688   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8689     return SDValue();
8690
8691   SDLoc DL(N);
8692   // 1) or (and A, mask), val => ARMbfi A, val, mask
8693   //      iff (val & mask) == val
8694   //
8695   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8696   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8697   //          && mask == ~mask2
8698   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8699   //          && ~mask == mask2
8700   //  (i.e., copy a bitfield value into another bitfield of the same width)
8701
8702   if (VT != MVT::i32)
8703     return SDValue();
8704
8705   SDValue N00 = N0.getOperand(0);
8706
8707   // The value and the mask need to be constants so we can verify this is
8708   // actually a bitfield set. If the mask is 0xffff, we can do better
8709   // via a movt instruction, so don't use BFI in that case.
8710   SDValue MaskOp = N0.getOperand(1);
8711   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8712   if (!MaskC)
8713     return SDValue();
8714   unsigned Mask = MaskC->getZExtValue();
8715   if (Mask == 0xffff)
8716     return SDValue();
8717   SDValue Res;
8718   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8719   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8720   if (N1C) {
8721     unsigned Val = N1C->getZExtValue();
8722     if ((Val & ~Mask) != Val)
8723       return SDValue();
8724
8725     if (ARM::isBitFieldInvertedMask(Mask)) {
8726       Val >>= countTrailingZeros(~Mask);
8727
8728       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8729                         DAG.getConstant(Val, MVT::i32),
8730                         DAG.getConstant(Mask, MVT::i32));
8731
8732       // Do not add new nodes to DAG combiner worklist.
8733       DCI.CombineTo(N, Res, false);
8734       return SDValue();
8735     }
8736   } else if (N1.getOpcode() == ISD::AND) {
8737     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8738     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8739     if (!N11C)
8740       return SDValue();
8741     unsigned Mask2 = N11C->getZExtValue();
8742
8743     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8744     // as is to match.
8745     if (ARM::isBitFieldInvertedMask(Mask) &&
8746         (Mask == ~Mask2)) {
8747       // The pack halfword instruction works better for masks that fit it,
8748       // so use that when it's available.
8749       if (Subtarget->hasT2ExtractPack() &&
8750           (Mask == 0xffff || Mask == 0xffff0000))
8751         return SDValue();
8752       // 2a
8753       unsigned amt = countTrailingZeros(Mask2);
8754       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8755                         DAG.getConstant(amt, MVT::i32));
8756       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8757                         DAG.getConstant(Mask, MVT::i32));
8758       // Do not add new nodes to DAG combiner worklist.
8759       DCI.CombineTo(N, Res, false);
8760       return SDValue();
8761     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8762                (~Mask == Mask2)) {
8763       // The pack halfword instruction works better for masks that fit it,
8764       // so use that when it's available.
8765       if (Subtarget->hasT2ExtractPack() &&
8766           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8767         return SDValue();
8768       // 2b
8769       unsigned lsb = countTrailingZeros(Mask);
8770       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8771                         DAG.getConstant(lsb, MVT::i32));
8772       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8773                         DAG.getConstant(Mask2, MVT::i32));
8774       // Do not add new nodes to DAG combiner worklist.
8775       DCI.CombineTo(N, Res, false);
8776       return SDValue();
8777     }
8778   }
8779
8780   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8781       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8782       ARM::isBitFieldInvertedMask(~Mask)) {
8783     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8784     // where lsb(mask) == #shamt and masked bits of B are known zero.
8785     SDValue ShAmt = N00.getOperand(1);
8786     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8787     unsigned LSB = countTrailingZeros(Mask);
8788     if (ShAmtC != LSB)
8789       return SDValue();
8790
8791     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8792                       DAG.getConstant(~Mask, MVT::i32));
8793
8794     // Do not add new nodes to DAG combiner worklist.
8795     DCI.CombineTo(N, Res, false);
8796   }
8797
8798   return SDValue();
8799 }
8800
8801 static SDValue PerformXORCombine(SDNode *N,
8802                                  TargetLowering::DAGCombinerInfo &DCI,
8803                                  const ARMSubtarget *Subtarget) {
8804   EVT VT = N->getValueType(0);
8805   SelectionDAG &DAG = DCI.DAG;
8806
8807   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8808     return SDValue();
8809
8810   if (!Subtarget->isThumb1Only()) {
8811     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8812     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8813     if (Result.getNode())
8814       return Result;
8815   }
8816
8817   return SDValue();
8818 }
8819
8820 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8821 /// the bits being cleared by the AND are not demanded by the BFI.
8822 static SDValue PerformBFICombine(SDNode *N,
8823                                  TargetLowering::DAGCombinerInfo &DCI) {
8824   SDValue N1 = N->getOperand(1);
8825   if (N1.getOpcode() == ISD::AND) {
8826     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8827     if (!N11C)
8828       return SDValue();
8829     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8830     unsigned LSB = countTrailingZeros(~InvMask);
8831     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8832     unsigned Mask = (1 << Width)-1;
8833     unsigned Mask2 = N11C->getZExtValue();
8834     if ((Mask & (~Mask2)) == 0)
8835       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8836                              N->getOperand(0), N1.getOperand(0),
8837                              N->getOperand(2));
8838   }
8839   return SDValue();
8840 }
8841
8842 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8843 /// ARMISD::VMOVRRD.
8844 static SDValue PerformVMOVRRDCombine(SDNode *N,
8845                                      TargetLowering::DAGCombinerInfo &DCI) {
8846   // vmovrrd(vmovdrr x, y) -> x,y
8847   SDValue InDouble = N->getOperand(0);
8848   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8849     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8850
8851   // vmovrrd(load f64) -> (load i32), (load i32)
8852   SDNode *InNode = InDouble.getNode();
8853   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8854       InNode->getValueType(0) == MVT::f64 &&
8855       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8856       !cast<LoadSDNode>(InNode)->isVolatile()) {
8857     // TODO: Should this be done for non-FrameIndex operands?
8858     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8859
8860     SelectionDAG &DAG = DCI.DAG;
8861     SDLoc DL(LD);
8862     SDValue BasePtr = LD->getBasePtr();
8863     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8864                                  LD->getPointerInfo(), LD->isVolatile(),
8865                                  LD->isNonTemporal(), LD->isInvariant(),
8866                                  LD->getAlignment());
8867
8868     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8869                                     DAG.getConstant(4, MVT::i32));
8870     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8871                                  LD->getPointerInfo(), LD->isVolatile(),
8872                                  LD->isNonTemporal(), LD->isInvariant(),
8873                                  std::min(4U, LD->getAlignment() / 2));
8874
8875     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8876     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8877     DCI.RemoveFromWorklist(LD);
8878     DAG.DeleteNode(LD);
8879     return Result;
8880   }
8881
8882   return SDValue();
8883 }
8884
8885 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8886 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8887 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8888   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8889   SDValue Op0 = N->getOperand(0);
8890   SDValue Op1 = N->getOperand(1);
8891   if (Op0.getOpcode() == ISD::BITCAST)
8892     Op0 = Op0.getOperand(0);
8893   if (Op1.getOpcode() == ISD::BITCAST)
8894     Op1 = Op1.getOperand(0);
8895   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8896       Op0.getNode() == Op1.getNode() &&
8897       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8898     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8899                        N->getValueType(0), Op0.getOperand(0));
8900   return SDValue();
8901 }
8902
8903 /// PerformSTORECombine - Target-specific dag combine xforms for
8904 /// ISD::STORE.
8905 static SDValue PerformSTORECombine(SDNode *N,
8906                                    TargetLowering::DAGCombinerInfo &DCI) {
8907   StoreSDNode *St = cast<StoreSDNode>(N);
8908   if (St->isVolatile())
8909     return SDValue();
8910
8911   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8912   // pack all of the elements in one place.  Next, store to memory in fewer
8913   // chunks.
8914   SDValue StVal = St->getValue();
8915   EVT VT = StVal.getValueType();
8916   if (St->isTruncatingStore() && VT.isVector()) {
8917     SelectionDAG &DAG = DCI.DAG;
8918     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8919     EVT StVT = St->getMemoryVT();
8920     unsigned NumElems = VT.getVectorNumElements();
8921     assert(StVT != VT && "Cannot truncate to the same type");
8922     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8923     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8924
8925     // From, To sizes and ElemCount must be pow of two
8926     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8927
8928     // We are going to use the original vector elt for storing.
8929     // Accumulated smaller vector elements must be a multiple of the store size.
8930     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8931
8932     unsigned SizeRatio  = FromEltSz / ToEltSz;
8933     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8934
8935     // Create a type on which we perform the shuffle.
8936     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8937                                      NumElems*SizeRatio);
8938     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8939
8940     SDLoc DL(St);
8941     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8942     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8943     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8944
8945     // Can't shuffle using an illegal type.
8946     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8947
8948     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8949                                 DAG.getUNDEF(WideVec.getValueType()),
8950                                 ShuffleVec.data());
8951     // At this point all of the data is stored at the bottom of the
8952     // register. We now need to save it to mem.
8953
8954     // Find the largest store unit
8955     MVT StoreType = MVT::i8;
8956     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8957          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8958       MVT Tp = (MVT::SimpleValueType)tp;
8959       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8960         StoreType = Tp;
8961     }
8962     // Didn't find a legal store type.
8963     if (!TLI.isTypeLegal(StoreType))
8964       return SDValue();
8965
8966     // Bitcast the original vector into a vector of store-size units
8967     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8968             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8969     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8970     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8971     SmallVector<SDValue, 8> Chains;
8972     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8973                                         TLI.getPointerTy());
8974     SDValue BasePtr = St->getBasePtr();
8975
8976     // Perform one or more big stores into memory.
8977     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8978     for (unsigned I = 0; I < E; I++) {
8979       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8980                                    StoreType, ShuffWide,
8981                                    DAG.getIntPtrConstant(I));
8982       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8983                                 St->getPointerInfo(), St->isVolatile(),
8984                                 St->isNonTemporal(), St->getAlignment());
8985       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8986                             Increment);
8987       Chains.push_back(Ch);
8988     }
8989     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
8990                        Chains.size());
8991   }
8992
8993   if (!ISD::isNormalStore(St))
8994     return SDValue();
8995
8996   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8997   // ARM stores of arguments in the same cache line.
8998   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8999       StVal.getNode()->hasOneUse()) {
9000     SelectionDAG  &DAG = DCI.DAG;
9001     SDLoc DL(St);
9002     SDValue BasePtr = St->getBasePtr();
9003     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9004                                   StVal.getNode()->getOperand(0), BasePtr,
9005                                   St->getPointerInfo(), St->isVolatile(),
9006                                   St->isNonTemporal(), St->getAlignment());
9007
9008     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9009                                     DAG.getConstant(4, MVT::i32));
9010     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
9011                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9012                         St->isNonTemporal(),
9013                         std::min(4U, St->getAlignment() / 2));
9014   }
9015
9016   if (StVal.getValueType() != MVT::i64 ||
9017       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9018     return SDValue();
9019
9020   // Bitcast an i64 store extracted from a vector to f64.
9021   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9022   SelectionDAG &DAG = DCI.DAG;
9023   SDLoc dl(StVal);
9024   SDValue IntVec = StVal.getOperand(0);
9025   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9026                                  IntVec.getValueType().getVectorNumElements());
9027   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9028   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9029                                Vec, StVal.getOperand(1));
9030   dl = SDLoc(N);
9031   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9032   // Make the DAGCombiner fold the bitcasts.
9033   DCI.AddToWorklist(Vec.getNode());
9034   DCI.AddToWorklist(ExtElt.getNode());
9035   DCI.AddToWorklist(V.getNode());
9036   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9037                       St->getPointerInfo(), St->isVolatile(),
9038                       St->isNonTemporal(), St->getAlignment(),
9039                       St->getTBAAInfo());
9040 }
9041
9042 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9043 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
9044 /// i64 vector to have f64 elements, since the value can then be loaded
9045 /// directly into a VFP register.
9046 static bool hasNormalLoadOperand(SDNode *N) {
9047   unsigned NumElts = N->getValueType(0).getVectorNumElements();
9048   for (unsigned i = 0; i < NumElts; ++i) {
9049     SDNode *Elt = N->getOperand(i).getNode();
9050     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9051       return true;
9052   }
9053   return false;
9054 }
9055
9056 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9057 /// ISD::BUILD_VECTOR.
9058 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9059                                           TargetLowering::DAGCombinerInfo &DCI){
9060   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9061   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
9062   // into a pair of GPRs, which is fine when the value is used as a scalar,
9063   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9064   SelectionDAG &DAG = DCI.DAG;
9065   if (N->getNumOperands() == 2) {
9066     SDValue RV = PerformVMOVDRRCombine(N, DAG);
9067     if (RV.getNode())
9068       return RV;
9069   }
9070
9071   // Load i64 elements as f64 values so that type legalization does not split
9072   // them up into i32 values.
9073   EVT VT = N->getValueType(0);
9074   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9075     return SDValue();
9076   SDLoc dl(N);
9077   SmallVector<SDValue, 8> Ops;
9078   unsigned NumElts = VT.getVectorNumElements();
9079   for (unsigned i = 0; i < NumElts; ++i) {
9080     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9081     Ops.push_back(V);
9082     // Make the DAGCombiner fold the bitcast.
9083     DCI.AddToWorklist(V.getNode());
9084   }
9085   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9086   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
9087   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9088 }
9089
9090 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9091 static SDValue
9092 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9093   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9094   // At that time, we may have inserted bitcasts from integer to float.
9095   // If these bitcasts have survived DAGCombine, change the lowering of this
9096   // BUILD_VECTOR in something more vector friendly, i.e., that does not
9097   // force to use floating point types.
9098
9099   // Make sure we can change the type of the vector.
9100   // This is possible iff:
9101   // 1. The vector is only used in a bitcast to a integer type. I.e.,
9102   //    1.1. Vector is used only once.
9103   //    1.2. Use is a bit convert to an integer type.
9104   // 2. The size of its operands are 32-bits (64-bits are not legal).
9105   EVT VT = N->getValueType(0);
9106   EVT EltVT = VT.getVectorElementType();
9107
9108   // Check 1.1. and 2.
9109   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9110     return SDValue();
9111
9112   // By construction, the input type must be float.
9113   assert(EltVT == MVT::f32 && "Unexpected type!");
9114
9115   // Check 1.2.
9116   SDNode *Use = *N->use_begin();
9117   if (Use->getOpcode() != ISD::BITCAST ||
9118       Use->getValueType(0).isFloatingPoint())
9119     return SDValue();
9120
9121   // Check profitability.
9122   // Model is, if more than half of the relevant operands are bitcast from
9123   // i32, turn the build_vector into a sequence of insert_vector_elt.
9124   // Relevant operands are everything that is not statically
9125   // (i.e., at compile time) bitcasted.
9126   unsigned NumOfBitCastedElts = 0;
9127   unsigned NumElts = VT.getVectorNumElements();
9128   unsigned NumOfRelevantElts = NumElts;
9129   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9130     SDValue Elt = N->getOperand(Idx);
9131     if (Elt->getOpcode() == ISD::BITCAST) {
9132       // Assume only bit cast to i32 will go away.
9133       if (Elt->getOperand(0).getValueType() == MVT::i32)
9134         ++NumOfBitCastedElts;
9135     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9136       // Constants are statically casted, thus do not count them as
9137       // relevant operands.
9138       --NumOfRelevantElts;
9139   }
9140
9141   // Check if more than half of the elements require a non-free bitcast.
9142   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9143     return SDValue();
9144
9145   SelectionDAG &DAG = DCI.DAG;
9146   // Create the new vector type.
9147   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9148   // Check if the type is legal.
9149   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9150   if (!TLI.isTypeLegal(VecVT))
9151     return SDValue();
9152
9153   // Combine:
9154   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9155   // => BITCAST INSERT_VECTOR_ELT
9156   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9157   //                      (BITCAST EN), N.
9158   SDValue Vec = DAG.getUNDEF(VecVT);
9159   SDLoc dl(N);
9160   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9161     SDValue V = N->getOperand(Idx);
9162     if (V.getOpcode() == ISD::UNDEF)
9163       continue;
9164     if (V.getOpcode() == ISD::BITCAST &&
9165         V->getOperand(0).getValueType() == MVT::i32)
9166       // Fold obvious case.
9167       V = V.getOperand(0);
9168     else {
9169       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 
9170       // Make the DAGCombiner fold the bitcasts.
9171       DCI.AddToWorklist(V.getNode());
9172     }
9173     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
9174     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9175   }
9176   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9177   // Make the DAGCombiner fold the bitcasts.
9178   DCI.AddToWorklist(Vec.getNode());
9179   return Vec;
9180 }
9181
9182 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9183 /// ISD::INSERT_VECTOR_ELT.
9184 static SDValue PerformInsertEltCombine(SDNode *N,
9185                                        TargetLowering::DAGCombinerInfo &DCI) {
9186   // Bitcast an i64 load inserted into a vector to f64.
9187   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9188   EVT VT = N->getValueType(0);
9189   SDNode *Elt = N->getOperand(1).getNode();
9190   if (VT.getVectorElementType() != MVT::i64 ||
9191       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9192     return SDValue();
9193
9194   SelectionDAG &DAG = DCI.DAG;
9195   SDLoc dl(N);
9196   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9197                                  VT.getVectorNumElements());
9198   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9199   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9200   // Make the DAGCombiner fold the bitcasts.
9201   DCI.AddToWorklist(Vec.getNode());
9202   DCI.AddToWorklist(V.getNode());
9203   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9204                                Vec, V, N->getOperand(2));
9205   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9206 }
9207
9208 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9209 /// ISD::VECTOR_SHUFFLE.
9210 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9211   // The LLVM shufflevector instruction does not require the shuffle mask
9212   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9213   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
9214   // operands do not match the mask length, they are extended by concatenating
9215   // them with undef vectors.  That is probably the right thing for other
9216   // targets, but for NEON it is better to concatenate two double-register
9217   // size vector operands into a single quad-register size vector.  Do that
9218   // transformation here:
9219   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
9220   //   shuffle(concat(v1, v2), undef)
9221   SDValue Op0 = N->getOperand(0);
9222   SDValue Op1 = N->getOperand(1);
9223   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9224       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9225       Op0.getNumOperands() != 2 ||
9226       Op1.getNumOperands() != 2)
9227     return SDValue();
9228   SDValue Concat0Op1 = Op0.getOperand(1);
9229   SDValue Concat1Op1 = Op1.getOperand(1);
9230   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9231       Concat1Op1.getOpcode() != ISD::UNDEF)
9232     return SDValue();
9233   // Skip the transformation if any of the types are illegal.
9234   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9235   EVT VT = N->getValueType(0);
9236   if (!TLI.isTypeLegal(VT) ||
9237       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9238       !TLI.isTypeLegal(Concat1Op1.getValueType()))
9239     return SDValue();
9240
9241   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9242                                   Op0.getOperand(0), Op1.getOperand(0));
9243   // Translate the shuffle mask.
9244   SmallVector<int, 16> NewMask;
9245   unsigned NumElts = VT.getVectorNumElements();
9246   unsigned HalfElts = NumElts/2;
9247   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9248   for (unsigned n = 0; n < NumElts; ++n) {
9249     int MaskElt = SVN->getMaskElt(n);
9250     int NewElt = -1;
9251     if (MaskElt < (int)HalfElts)
9252       NewElt = MaskElt;
9253     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9254       NewElt = HalfElts + MaskElt - NumElts;
9255     NewMask.push_back(NewElt);
9256   }
9257   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9258                               DAG.getUNDEF(VT), NewMask.data());
9259 }
9260
9261 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
9262 /// NEON load/store intrinsics to merge base address updates.
9263 static SDValue CombineBaseUpdate(SDNode *N,
9264                                  TargetLowering::DAGCombinerInfo &DCI) {
9265   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9266     return SDValue();
9267
9268   SelectionDAG &DAG = DCI.DAG;
9269   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9270                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9271   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
9272   SDValue Addr = N->getOperand(AddrOpIdx);
9273
9274   // Search for a use of the address operand that is an increment.
9275   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9276          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9277     SDNode *User = *UI;
9278     if (User->getOpcode() != ISD::ADD ||
9279         UI.getUse().getResNo() != Addr.getResNo())
9280       continue;
9281
9282     // Check that the add is independent of the load/store.  Otherwise, folding
9283     // it would create a cycle.
9284     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9285       continue;
9286
9287     // Find the new opcode for the updating load/store.
9288     bool isLoad = true;
9289     bool isLaneOp = false;
9290     unsigned NewOpc = 0;
9291     unsigned NumVecs = 0;
9292     if (isIntrinsic) {
9293       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9294       switch (IntNo) {
9295       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9296       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9297         NumVecs = 1; break;
9298       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9299         NumVecs = 2; break;
9300       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9301         NumVecs = 3; break;
9302       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9303         NumVecs = 4; break;
9304       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9305         NumVecs = 2; isLaneOp = true; break;
9306       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9307         NumVecs = 3; isLaneOp = true; break;
9308       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9309         NumVecs = 4; isLaneOp = true; break;
9310       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9311         NumVecs = 1; isLoad = false; break;
9312       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9313         NumVecs = 2; isLoad = false; break;
9314       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9315         NumVecs = 3; isLoad = false; break;
9316       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9317         NumVecs = 4; isLoad = false; break;
9318       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9319         NumVecs = 2; isLoad = false; isLaneOp = true; break;
9320       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9321         NumVecs = 3; isLoad = false; isLaneOp = true; break;
9322       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9323         NumVecs = 4; isLoad = false; isLaneOp = true; break;
9324       }
9325     } else {
9326       isLaneOp = true;
9327       switch (N->getOpcode()) {
9328       default: llvm_unreachable("unexpected opcode for Neon base update");
9329       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9330       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9331       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9332       }
9333     }
9334
9335     // Find the size of memory referenced by the load/store.
9336     EVT VecTy;
9337     if (isLoad)
9338       VecTy = N->getValueType(0);
9339     else
9340       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9341     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9342     if (isLaneOp)
9343       NumBytes /= VecTy.getVectorNumElements();
9344
9345     // If the increment is a constant, it must match the memory ref size.
9346     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9347     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9348       uint64_t IncVal = CInc->getZExtValue();
9349       if (IncVal != NumBytes)
9350         continue;
9351     } else if (NumBytes >= 3 * 16) {
9352       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9353       // separate instructions that make it harder to use a non-constant update.
9354       continue;
9355     }
9356
9357     // Create the new updating load/store node.
9358     EVT Tys[6];
9359     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
9360     unsigned n;
9361     for (n = 0; n < NumResultVecs; ++n)
9362       Tys[n] = VecTy;
9363     Tys[n++] = MVT::i32;
9364     Tys[n] = MVT::Other;
9365     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
9366     SmallVector<SDValue, 8> Ops;
9367     Ops.push_back(N->getOperand(0)); // incoming chain
9368     Ops.push_back(N->getOperand(AddrOpIdx));
9369     Ops.push_back(Inc);
9370     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
9371       Ops.push_back(N->getOperand(i));
9372     }
9373     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9374     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9375                                            Ops.data(), Ops.size(),
9376                                            MemInt->getMemoryVT(),
9377                                            MemInt->getMemOperand());
9378
9379     // Update the uses.
9380     std::vector<SDValue> NewResults;
9381     for (unsigned i = 0; i < NumResultVecs; ++i) {
9382       NewResults.push_back(SDValue(UpdN.getNode(), i));
9383     }
9384     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9385     DCI.CombineTo(N, NewResults);
9386     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9387
9388     break;
9389   }
9390   return SDValue();
9391 }
9392
9393 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9394 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9395 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9396 /// return true.
9397 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9398   SelectionDAG &DAG = DCI.DAG;
9399   EVT VT = N->getValueType(0);
9400   // vldN-dup instructions only support 64-bit vectors for N > 1.
9401   if (!VT.is64BitVector())
9402     return false;
9403
9404   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9405   SDNode *VLD = N->getOperand(0).getNode();
9406   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9407     return false;
9408   unsigned NumVecs = 0;
9409   unsigned NewOpc = 0;
9410   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9411   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9412     NumVecs = 2;
9413     NewOpc = ARMISD::VLD2DUP;
9414   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9415     NumVecs = 3;
9416     NewOpc = ARMISD::VLD3DUP;
9417   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9418     NumVecs = 4;
9419     NewOpc = ARMISD::VLD4DUP;
9420   } else {
9421     return false;
9422   }
9423
9424   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9425   // numbers match the load.
9426   unsigned VLDLaneNo =
9427     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9428   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9429        UI != UE; ++UI) {
9430     // Ignore uses of the chain result.
9431     if (UI.getUse().getResNo() == NumVecs)
9432       continue;
9433     SDNode *User = *UI;
9434     if (User->getOpcode() != ARMISD::VDUPLANE ||
9435         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9436       return false;
9437   }
9438
9439   // Create the vldN-dup node.
9440   EVT Tys[5];
9441   unsigned n;
9442   for (n = 0; n < NumVecs; ++n)
9443     Tys[n] = VT;
9444   Tys[n] = MVT::Other;
9445   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
9446   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9447   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9448   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9449                                            Ops, 2, VLDMemInt->getMemoryVT(),
9450                                            VLDMemInt->getMemOperand());
9451
9452   // Update the uses.
9453   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9454        UI != UE; ++UI) {
9455     unsigned ResNo = UI.getUse().getResNo();
9456     // Ignore uses of the chain result.
9457     if (ResNo == NumVecs)
9458       continue;
9459     SDNode *User = *UI;
9460     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9461   }
9462
9463   // Now the vldN-lane intrinsic is dead except for its chain result.
9464   // Update uses of the chain.
9465   std::vector<SDValue> VLDDupResults;
9466   for (unsigned n = 0; n < NumVecs; ++n)
9467     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9468   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9469   DCI.CombineTo(VLD, VLDDupResults);
9470
9471   return true;
9472 }
9473
9474 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9475 /// ARMISD::VDUPLANE.
9476 static SDValue PerformVDUPLANECombine(SDNode *N,
9477                                       TargetLowering::DAGCombinerInfo &DCI) {
9478   SDValue Op = N->getOperand(0);
9479
9480   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9481   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9482   if (CombineVLDDUP(N, DCI))
9483     return SDValue(N, 0);
9484
9485   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9486   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9487   while (Op.getOpcode() == ISD::BITCAST)
9488     Op = Op.getOperand(0);
9489   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9490     return SDValue();
9491
9492   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9493   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9494   // The canonical VMOV for a zero vector uses a 32-bit element size.
9495   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9496   unsigned EltBits;
9497   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9498     EltSize = 8;
9499   EVT VT = N->getValueType(0);
9500   if (EltSize > VT.getVectorElementType().getSizeInBits())
9501     return SDValue();
9502
9503   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9504 }
9505
9506 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9507 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9508 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9509 {
9510   integerPart cN;
9511   integerPart c0 = 0;
9512   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9513        I != E; I++) {
9514     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9515     if (!C)
9516       return false;
9517
9518     bool isExact;
9519     APFloat APF = C->getValueAPF();
9520     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9521         != APFloat::opOK || !isExact)
9522       return false;
9523
9524     c0 = (I == 0) ? cN : c0;
9525     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9526       return false;
9527   }
9528   C = c0;
9529   return true;
9530 }
9531
9532 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9533 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9534 /// when the VMUL has a constant operand that is a power of 2.
9535 ///
9536 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9537 ///  vmul.f32        d16, d17, d16
9538 ///  vcvt.s32.f32    d16, d16
9539 /// becomes:
9540 ///  vcvt.s32.f32    d16, d16, #3
9541 static SDValue PerformVCVTCombine(SDNode *N,
9542                                   TargetLowering::DAGCombinerInfo &DCI,
9543                                   const ARMSubtarget *Subtarget) {
9544   SelectionDAG &DAG = DCI.DAG;
9545   SDValue Op = N->getOperand(0);
9546
9547   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9548       Op.getOpcode() != ISD::FMUL)
9549     return SDValue();
9550
9551   uint64_t C;
9552   SDValue N0 = Op->getOperand(0);
9553   SDValue ConstVec = Op->getOperand(1);
9554   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9555
9556   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9557       !isConstVecPow2(ConstVec, isSigned, C))
9558     return SDValue();
9559
9560   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9561   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9562   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9563     // These instructions only exist converting from f32 to i32. We can handle
9564     // smaller integers by generating an extra truncate, but larger ones would
9565     // be lossy.
9566     return SDValue();
9567   }
9568
9569   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9570     Intrinsic::arm_neon_vcvtfp2fxu;
9571   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9572   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9573                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9574                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9575                                  DAG.getConstant(Log2_64(C), MVT::i32));
9576
9577   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9578     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9579
9580   return FixConv;
9581 }
9582
9583 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9584 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9585 /// when the VDIV has a constant operand that is a power of 2.
9586 ///
9587 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9588 ///  vcvt.f32.s32    d16, d16
9589 ///  vdiv.f32        d16, d17, d16
9590 /// becomes:
9591 ///  vcvt.f32.s32    d16, d16, #3
9592 static SDValue PerformVDIVCombine(SDNode *N,
9593                                   TargetLowering::DAGCombinerInfo &DCI,
9594                                   const ARMSubtarget *Subtarget) {
9595   SelectionDAG &DAG = DCI.DAG;
9596   SDValue Op = N->getOperand(0);
9597   unsigned OpOpcode = Op.getNode()->getOpcode();
9598
9599   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9600       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9601     return SDValue();
9602
9603   uint64_t C;
9604   SDValue ConstVec = N->getOperand(1);
9605   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9606
9607   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9608       !isConstVecPow2(ConstVec, isSigned, C))
9609     return SDValue();
9610
9611   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9612   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9613   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9614     // These instructions only exist converting from i32 to f32. We can handle
9615     // smaller integers by generating an extra extend, but larger ones would
9616     // be lossy.
9617     return SDValue();
9618   }
9619
9620   SDValue ConvInput = Op.getOperand(0);
9621   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9622   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9623     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9624                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9625                             ConvInput);
9626
9627   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9628     Intrinsic::arm_neon_vcvtfxu2fp;
9629   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9630                      Op.getValueType(),
9631                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9632                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9633 }
9634
9635 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9636 /// operand of a vector shift operation, where all the elements of the
9637 /// build_vector must have the same constant integer value.
9638 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9639   // Ignore bit_converts.
9640   while (Op.getOpcode() == ISD::BITCAST)
9641     Op = Op.getOperand(0);
9642   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9643   APInt SplatBits, SplatUndef;
9644   unsigned SplatBitSize;
9645   bool HasAnyUndefs;
9646   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9647                                       HasAnyUndefs, ElementBits) ||
9648       SplatBitSize > ElementBits)
9649     return false;
9650   Cnt = SplatBits.getSExtValue();
9651   return true;
9652 }
9653
9654 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9655 /// operand of a vector shift left operation.  That value must be in the range:
9656 ///   0 <= Value < ElementBits for a left shift; or
9657 ///   0 <= Value <= ElementBits for a long left shift.
9658 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9659   assert(VT.isVector() && "vector shift count is not a vector type");
9660   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9661   if (! getVShiftImm(Op, ElementBits, Cnt))
9662     return false;
9663   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9664 }
9665
9666 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9667 /// operand of a vector shift right operation.  For a shift opcode, the value
9668 /// is positive, but for an intrinsic the value count must be negative. The
9669 /// absolute value must be in the range:
9670 ///   1 <= |Value| <= ElementBits for a right shift; or
9671 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9672 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9673                          int64_t &Cnt) {
9674   assert(VT.isVector() && "vector shift count is not a vector type");
9675   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9676   if (! getVShiftImm(Op, ElementBits, Cnt))
9677     return false;
9678   if (isIntrinsic)
9679     Cnt = -Cnt;
9680   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9681 }
9682
9683 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9684 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9685   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9686   switch (IntNo) {
9687   default:
9688     // Don't do anything for most intrinsics.
9689     break;
9690
9691   // Vector shifts: check for immediate versions and lower them.
9692   // Note: This is done during DAG combining instead of DAG legalizing because
9693   // the build_vectors for 64-bit vector element shift counts are generally
9694   // not legal, and it is hard to see their values after they get legalized to
9695   // loads from a constant pool.
9696   case Intrinsic::arm_neon_vshifts:
9697   case Intrinsic::arm_neon_vshiftu:
9698   case Intrinsic::arm_neon_vshiftls:
9699   case Intrinsic::arm_neon_vshiftlu:
9700   case Intrinsic::arm_neon_vshiftn:
9701   case Intrinsic::arm_neon_vrshifts:
9702   case Intrinsic::arm_neon_vrshiftu:
9703   case Intrinsic::arm_neon_vrshiftn:
9704   case Intrinsic::arm_neon_vqshifts:
9705   case Intrinsic::arm_neon_vqshiftu:
9706   case Intrinsic::arm_neon_vqshiftsu:
9707   case Intrinsic::arm_neon_vqshiftns:
9708   case Intrinsic::arm_neon_vqshiftnu:
9709   case Intrinsic::arm_neon_vqshiftnsu:
9710   case Intrinsic::arm_neon_vqrshiftns:
9711   case Intrinsic::arm_neon_vqrshiftnu:
9712   case Intrinsic::arm_neon_vqrshiftnsu: {
9713     EVT VT = N->getOperand(1).getValueType();
9714     int64_t Cnt;
9715     unsigned VShiftOpc = 0;
9716
9717     switch (IntNo) {
9718     case Intrinsic::arm_neon_vshifts:
9719     case Intrinsic::arm_neon_vshiftu:
9720       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9721         VShiftOpc = ARMISD::VSHL;
9722         break;
9723       }
9724       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9725         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9726                      ARMISD::VSHRs : ARMISD::VSHRu);
9727         break;
9728       }
9729       return SDValue();
9730
9731     case Intrinsic::arm_neon_vshiftls:
9732     case Intrinsic::arm_neon_vshiftlu:
9733       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
9734         break;
9735       llvm_unreachable("invalid shift count for vshll intrinsic");
9736
9737     case Intrinsic::arm_neon_vrshifts:
9738     case Intrinsic::arm_neon_vrshiftu:
9739       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9740         break;
9741       return SDValue();
9742
9743     case Intrinsic::arm_neon_vqshifts:
9744     case Intrinsic::arm_neon_vqshiftu:
9745       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9746         break;
9747       return SDValue();
9748
9749     case Intrinsic::arm_neon_vqshiftsu:
9750       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9751         break;
9752       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9753
9754     case Intrinsic::arm_neon_vshiftn:
9755     case Intrinsic::arm_neon_vrshiftn:
9756     case Intrinsic::arm_neon_vqshiftns:
9757     case Intrinsic::arm_neon_vqshiftnu:
9758     case Intrinsic::arm_neon_vqshiftnsu:
9759     case Intrinsic::arm_neon_vqrshiftns:
9760     case Intrinsic::arm_neon_vqrshiftnu:
9761     case Intrinsic::arm_neon_vqrshiftnsu:
9762       // Narrowing shifts require an immediate right shift.
9763       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9764         break;
9765       llvm_unreachable("invalid shift count for narrowing vector shift "
9766                        "intrinsic");
9767
9768     default:
9769       llvm_unreachable("unhandled vector shift");
9770     }
9771
9772     switch (IntNo) {
9773     case Intrinsic::arm_neon_vshifts:
9774     case Intrinsic::arm_neon_vshiftu:
9775       // Opcode already set above.
9776       break;
9777     case Intrinsic::arm_neon_vshiftls:
9778     case Intrinsic::arm_neon_vshiftlu:
9779       if (Cnt == VT.getVectorElementType().getSizeInBits())
9780         VShiftOpc = ARMISD::VSHLLi;
9781       else
9782         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
9783                      ARMISD::VSHLLs : ARMISD::VSHLLu);
9784       break;
9785     case Intrinsic::arm_neon_vshiftn:
9786       VShiftOpc = ARMISD::VSHRN; break;
9787     case Intrinsic::arm_neon_vrshifts:
9788       VShiftOpc = ARMISD::VRSHRs; break;
9789     case Intrinsic::arm_neon_vrshiftu:
9790       VShiftOpc = ARMISD::VRSHRu; break;
9791     case Intrinsic::arm_neon_vrshiftn:
9792       VShiftOpc = ARMISD::VRSHRN; break;
9793     case Intrinsic::arm_neon_vqshifts:
9794       VShiftOpc = ARMISD::VQSHLs; break;
9795     case Intrinsic::arm_neon_vqshiftu:
9796       VShiftOpc = ARMISD::VQSHLu; break;
9797     case Intrinsic::arm_neon_vqshiftsu:
9798       VShiftOpc = ARMISD::VQSHLsu; break;
9799     case Intrinsic::arm_neon_vqshiftns:
9800       VShiftOpc = ARMISD::VQSHRNs; break;
9801     case Intrinsic::arm_neon_vqshiftnu:
9802       VShiftOpc = ARMISD::VQSHRNu; break;
9803     case Intrinsic::arm_neon_vqshiftnsu:
9804       VShiftOpc = ARMISD::VQSHRNsu; break;
9805     case Intrinsic::arm_neon_vqrshiftns:
9806       VShiftOpc = ARMISD::VQRSHRNs; break;
9807     case Intrinsic::arm_neon_vqrshiftnu:
9808       VShiftOpc = ARMISD::VQRSHRNu; break;
9809     case Intrinsic::arm_neon_vqrshiftnsu:
9810       VShiftOpc = ARMISD::VQRSHRNsu; break;
9811     }
9812
9813     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9814                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9815   }
9816
9817   case Intrinsic::arm_neon_vshiftins: {
9818     EVT VT = N->getOperand(1).getValueType();
9819     int64_t Cnt;
9820     unsigned VShiftOpc = 0;
9821
9822     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9823       VShiftOpc = ARMISD::VSLI;
9824     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9825       VShiftOpc = ARMISD::VSRI;
9826     else {
9827       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9828     }
9829
9830     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9831                        N->getOperand(1), N->getOperand(2),
9832                        DAG.getConstant(Cnt, MVT::i32));
9833   }
9834
9835   case Intrinsic::arm_neon_vqrshifts:
9836   case Intrinsic::arm_neon_vqrshiftu:
9837     // No immediate versions of these to check for.
9838     break;
9839   }
9840
9841   return SDValue();
9842 }
9843
9844 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9845 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9846 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9847 /// vector element shift counts are generally not legal, and it is hard to see
9848 /// their values after they get legalized to loads from a constant pool.
9849 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9850                                    const ARMSubtarget *ST) {
9851   EVT VT = N->getValueType(0);
9852   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9853     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9854     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9855     SDValue N1 = N->getOperand(1);
9856     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9857       SDValue N0 = N->getOperand(0);
9858       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9859           DAG.MaskedValueIsZero(N0.getOperand(0),
9860                                 APInt::getHighBitsSet(32, 16)))
9861         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9862     }
9863   }
9864
9865   // Nothing to be done for scalar shifts.
9866   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9867   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9868     return SDValue();
9869
9870   assert(ST->hasNEON() && "unexpected vector shift");
9871   int64_t Cnt;
9872
9873   switch (N->getOpcode()) {
9874   default: llvm_unreachable("unexpected shift opcode");
9875
9876   case ISD::SHL:
9877     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9878       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9879                          DAG.getConstant(Cnt, MVT::i32));
9880     break;
9881
9882   case ISD::SRA:
9883   case ISD::SRL:
9884     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9885       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9886                             ARMISD::VSHRs : ARMISD::VSHRu);
9887       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9888                          DAG.getConstant(Cnt, MVT::i32));
9889     }
9890   }
9891   return SDValue();
9892 }
9893
9894 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9895 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9896 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9897                                     const ARMSubtarget *ST) {
9898   SDValue N0 = N->getOperand(0);
9899
9900   // Check for sign- and zero-extensions of vector extract operations of 8-
9901   // and 16-bit vector elements.  NEON supports these directly.  They are
9902   // handled during DAG combining because type legalization will promote them
9903   // to 32-bit types and it is messy to recognize the operations after that.
9904   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9905     SDValue Vec = N0.getOperand(0);
9906     SDValue Lane = N0.getOperand(1);
9907     EVT VT = N->getValueType(0);
9908     EVT EltVT = N0.getValueType();
9909     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9910
9911     if (VT == MVT::i32 &&
9912         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9913         TLI.isTypeLegal(Vec.getValueType()) &&
9914         isa<ConstantSDNode>(Lane)) {
9915
9916       unsigned Opc = 0;
9917       switch (N->getOpcode()) {
9918       default: llvm_unreachable("unexpected opcode");
9919       case ISD::SIGN_EXTEND:
9920         Opc = ARMISD::VGETLANEs;
9921         break;
9922       case ISD::ZERO_EXTEND:
9923       case ISD::ANY_EXTEND:
9924         Opc = ARMISD::VGETLANEu;
9925         break;
9926       }
9927       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9928     }
9929   }
9930
9931   return SDValue();
9932 }
9933
9934 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9935 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9936 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9937                                        const ARMSubtarget *ST) {
9938   // If the target supports NEON, try to use vmax/vmin instructions for f32
9939   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9940   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9941   // a NaN; only do the transformation when it matches that behavior.
9942
9943   // For now only do this when using NEON for FP operations; if using VFP, it
9944   // is not obvious that the benefit outweighs the cost of switching to the
9945   // NEON pipeline.
9946   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9947       N->getValueType(0) != MVT::f32)
9948     return SDValue();
9949
9950   SDValue CondLHS = N->getOperand(0);
9951   SDValue CondRHS = N->getOperand(1);
9952   SDValue LHS = N->getOperand(2);
9953   SDValue RHS = N->getOperand(3);
9954   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9955
9956   unsigned Opcode = 0;
9957   bool IsReversed;
9958   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9959     IsReversed = false; // x CC y ? x : y
9960   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9961     IsReversed = true ; // x CC y ? y : x
9962   } else {
9963     return SDValue();
9964   }
9965
9966   bool IsUnordered;
9967   switch (CC) {
9968   default: break;
9969   case ISD::SETOLT:
9970   case ISD::SETOLE:
9971   case ISD::SETLT:
9972   case ISD::SETLE:
9973   case ISD::SETULT:
9974   case ISD::SETULE:
9975     // If LHS is NaN, an ordered comparison will be false and the result will
9976     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9977     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9978     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9979     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9980       break;
9981     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9982     // will return -0, so vmin can only be used for unsafe math or if one of
9983     // the operands is known to be nonzero.
9984     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9985         !DAG.getTarget().Options.UnsafeFPMath &&
9986         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9987       break;
9988     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9989     break;
9990
9991   case ISD::SETOGT:
9992   case ISD::SETOGE:
9993   case ISD::SETGT:
9994   case ISD::SETGE:
9995   case ISD::SETUGT:
9996   case ISD::SETUGE:
9997     // If LHS is NaN, an ordered comparison will be false and the result will
9998     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9999     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
10000     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
10001     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10002       break;
10003     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
10004     // will return +0, so vmax can only be used for unsafe math or if one of
10005     // the operands is known to be nonzero.
10006     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
10007         !DAG.getTarget().Options.UnsafeFPMath &&
10008         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10009       break;
10010     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
10011     break;
10012   }
10013
10014   if (!Opcode)
10015     return SDValue();
10016   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
10017 }
10018
10019 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10020 SDValue
10021 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10022   SDValue Cmp = N->getOperand(4);
10023   if (Cmp.getOpcode() != ARMISD::CMPZ)
10024     // Only looking at EQ and NE cases.
10025     return SDValue();
10026
10027   EVT VT = N->getValueType(0);
10028   SDLoc dl(N);
10029   SDValue LHS = Cmp.getOperand(0);
10030   SDValue RHS = Cmp.getOperand(1);
10031   SDValue FalseVal = N->getOperand(0);
10032   SDValue TrueVal = N->getOperand(1);
10033   SDValue ARMcc = N->getOperand(2);
10034   ARMCC::CondCodes CC =
10035     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10036
10037   // Simplify
10038   //   mov     r1, r0
10039   //   cmp     r1, x
10040   //   mov     r0, y
10041   //   moveq   r0, x
10042   // to
10043   //   cmp     r0, x
10044   //   movne   r0, y
10045   //
10046   //   mov     r1, r0
10047   //   cmp     r1, x
10048   //   mov     r0, x
10049   //   movne   r0, y
10050   // to
10051   //   cmp     r0, x
10052   //   movne   r0, y
10053   /// FIXME: Turn this into a target neutral optimization?
10054   SDValue Res;
10055   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10056     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10057                       N->getOperand(3), Cmp);
10058   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10059     SDValue ARMcc;
10060     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10061     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10062                       N->getOperand(3), NewCmp);
10063   }
10064
10065   if (Res.getNode()) {
10066     APInt KnownZero, KnownOne;
10067     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
10068     // Capture demanded bits information that would be otherwise lost.
10069     if (KnownZero == 0xfffffffe)
10070       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10071                         DAG.getValueType(MVT::i1));
10072     else if (KnownZero == 0xffffff00)
10073       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10074                         DAG.getValueType(MVT::i8));
10075     else if (KnownZero == 0xffff0000)
10076       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10077                         DAG.getValueType(MVT::i16));
10078   }
10079
10080   return Res;
10081 }
10082
10083 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10084                                              DAGCombinerInfo &DCI) const {
10085   switch (N->getOpcode()) {
10086   default: break;
10087   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
10088   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
10089   case ISD::SUB:        return PerformSUBCombine(N, DCI);
10090   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
10091   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
10092   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
10093   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
10094   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
10095   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
10096   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10097   case ISD::STORE:      return PerformSTORECombine(N, DCI);
10098   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
10099   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10100   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10101   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10102   case ISD::FP_TO_SINT:
10103   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10104   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
10105   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10106   case ISD::SHL:
10107   case ISD::SRA:
10108   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10109   case ISD::SIGN_EXTEND:
10110   case ISD::ZERO_EXTEND:
10111   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10112   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
10113   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10114   case ARMISD::VLD2DUP:
10115   case ARMISD::VLD3DUP:
10116   case ARMISD::VLD4DUP:
10117     return CombineBaseUpdate(N, DCI);
10118   case ARMISD::BUILD_VECTOR:
10119     return PerformARMBUILD_VECTORCombine(N, DCI);
10120   case ISD::INTRINSIC_VOID:
10121   case ISD::INTRINSIC_W_CHAIN:
10122     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10123     case Intrinsic::arm_neon_vld1:
10124     case Intrinsic::arm_neon_vld2:
10125     case Intrinsic::arm_neon_vld3:
10126     case Intrinsic::arm_neon_vld4:
10127     case Intrinsic::arm_neon_vld2lane:
10128     case Intrinsic::arm_neon_vld3lane:
10129     case Intrinsic::arm_neon_vld4lane:
10130     case Intrinsic::arm_neon_vst1:
10131     case Intrinsic::arm_neon_vst2:
10132     case Intrinsic::arm_neon_vst3:
10133     case Intrinsic::arm_neon_vst4:
10134     case Intrinsic::arm_neon_vst2lane:
10135     case Intrinsic::arm_neon_vst3lane:
10136     case Intrinsic::arm_neon_vst4lane:
10137       return CombineBaseUpdate(N, DCI);
10138     default: break;
10139     }
10140     break;
10141   }
10142   return SDValue();
10143 }
10144
10145 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10146                                                           EVT VT) const {
10147   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10148 }
10149
10150 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
10151   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10152   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10153
10154   switch (VT.getSimpleVT().SimpleTy) {
10155   default:
10156     return false;
10157   case MVT::i8:
10158   case MVT::i16:
10159   case MVT::i32: {
10160     // Unaligned access can use (for example) LRDB, LRDH, LDR
10161     if (AllowsUnaligned) {
10162       if (Fast)
10163         *Fast = Subtarget->hasV7Ops();
10164       return true;
10165     }
10166     return false;
10167   }
10168   case MVT::f64:
10169   case MVT::v2f64: {
10170     // For any little-endian targets with neon, we can support unaligned ld/st
10171     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10172     // A big-endian target may also explictly support unaligned accesses
10173     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
10174       if (Fast)
10175         *Fast = true;
10176       return true;
10177     }
10178     return false;
10179   }
10180   }
10181 }
10182
10183 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10184                        unsigned AlignCheck) {
10185   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10186           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10187 }
10188
10189 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10190                                            unsigned DstAlign, unsigned SrcAlign,
10191                                            bool IsMemset, bool ZeroMemset,
10192                                            bool MemcpyStrSrc,
10193                                            MachineFunction &MF) const {
10194   const Function *F = MF.getFunction();
10195
10196   // See if we can use NEON instructions for this...
10197   if ((!IsMemset || ZeroMemset) &&
10198       Subtarget->hasNEON() &&
10199       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
10200                                        Attribute::NoImplicitFloat)) {
10201     bool Fast;
10202     if (Size >= 16 &&
10203         (memOpAlign(SrcAlign, DstAlign, 16) ||
10204          (allowsUnalignedMemoryAccesses(MVT::v2f64, &Fast) && Fast))) {
10205       return MVT::v2f64;
10206     } else if (Size >= 8 &&
10207                (memOpAlign(SrcAlign, DstAlign, 8) ||
10208                 (allowsUnalignedMemoryAccesses(MVT::f64, &Fast) && Fast))) {
10209       return MVT::f64;
10210     }
10211   }
10212
10213   // Lowering to i32/i16 if the size permits.
10214   if (Size >= 4)
10215     return MVT::i32;
10216   else if (Size >= 2)
10217     return MVT::i16;
10218
10219   // Let the target-independent logic figure it out.
10220   return MVT::Other;
10221 }
10222
10223 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10224   if (Val.getOpcode() != ISD::LOAD)
10225     return false;
10226
10227   EVT VT1 = Val.getValueType();
10228   if (!VT1.isSimple() || !VT1.isInteger() ||
10229       !VT2.isSimple() || !VT2.isInteger())
10230     return false;
10231
10232   switch (VT1.getSimpleVT().SimpleTy) {
10233   default: break;
10234   case MVT::i1:
10235   case MVT::i8:
10236   case MVT::i16:
10237     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10238     return true;
10239   }
10240
10241   return false;
10242 }
10243
10244 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10245   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10246     return false;
10247
10248   if (!isTypeLegal(EVT::getEVT(Ty1)))
10249     return false;
10250
10251   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10252
10253   // Assuming the caller doesn't have a zeroext or signext return parameter,
10254   // truncation all the way down to i1 is valid.
10255   return true;
10256 }
10257
10258
10259 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10260   if (V < 0)
10261     return false;
10262
10263   unsigned Scale = 1;
10264   switch (VT.getSimpleVT().SimpleTy) {
10265   default: return false;
10266   case MVT::i1:
10267   case MVT::i8:
10268     // Scale == 1;
10269     break;
10270   case MVT::i16:
10271     // Scale == 2;
10272     Scale = 2;
10273     break;
10274   case MVT::i32:
10275     // Scale == 4;
10276     Scale = 4;
10277     break;
10278   }
10279
10280   if ((V & (Scale - 1)) != 0)
10281     return false;
10282   V /= Scale;
10283   return V == (V & ((1LL << 5) - 1));
10284 }
10285
10286 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10287                                       const ARMSubtarget *Subtarget) {
10288   bool isNeg = false;
10289   if (V < 0) {
10290     isNeg = true;
10291     V = - V;
10292   }
10293
10294   switch (VT.getSimpleVT().SimpleTy) {
10295   default: return false;
10296   case MVT::i1:
10297   case MVT::i8:
10298   case MVT::i16:
10299   case MVT::i32:
10300     // + imm12 or - imm8
10301     if (isNeg)
10302       return V == (V & ((1LL << 8) - 1));
10303     return V == (V & ((1LL << 12) - 1));
10304   case MVT::f32:
10305   case MVT::f64:
10306     // Same as ARM mode. FIXME: NEON?
10307     if (!Subtarget->hasVFP2())
10308       return false;
10309     if ((V & 3) != 0)
10310       return false;
10311     V >>= 2;
10312     return V == (V & ((1LL << 8) - 1));
10313   }
10314 }
10315
10316 /// isLegalAddressImmediate - Return true if the integer value can be used
10317 /// as the offset of the target addressing mode for load / store of the
10318 /// given type.
10319 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10320                                     const ARMSubtarget *Subtarget) {
10321   if (V == 0)
10322     return true;
10323
10324   if (!VT.isSimple())
10325     return false;
10326
10327   if (Subtarget->isThumb1Only())
10328     return isLegalT1AddressImmediate(V, VT);
10329   else if (Subtarget->isThumb2())
10330     return isLegalT2AddressImmediate(V, VT, Subtarget);
10331
10332   // ARM mode.
10333   if (V < 0)
10334     V = - V;
10335   switch (VT.getSimpleVT().SimpleTy) {
10336   default: return false;
10337   case MVT::i1:
10338   case MVT::i8:
10339   case MVT::i32:
10340     // +- imm12
10341     return V == (V & ((1LL << 12) - 1));
10342   case MVT::i16:
10343     // +- imm8
10344     return V == (V & ((1LL << 8) - 1));
10345   case MVT::f32:
10346   case MVT::f64:
10347     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10348       return false;
10349     if ((V & 3) != 0)
10350       return false;
10351     V >>= 2;
10352     return V == (V & ((1LL << 8) - 1));
10353   }
10354 }
10355
10356 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10357                                                       EVT VT) const {
10358   int Scale = AM.Scale;
10359   if (Scale < 0)
10360     return false;
10361
10362   switch (VT.getSimpleVT().SimpleTy) {
10363   default: return false;
10364   case MVT::i1:
10365   case MVT::i8:
10366   case MVT::i16:
10367   case MVT::i32:
10368     if (Scale == 1)
10369       return true;
10370     // r + r << imm
10371     Scale = Scale & ~1;
10372     return Scale == 2 || Scale == 4 || Scale == 8;
10373   case MVT::i64:
10374     // r + r
10375     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10376       return true;
10377     return false;
10378   case MVT::isVoid:
10379     // Note, we allow "void" uses (basically, uses that aren't loads or
10380     // stores), because arm allows folding a scale into many arithmetic
10381     // operations.  This should be made more precise and revisited later.
10382
10383     // Allow r << imm, but the imm has to be a multiple of two.
10384     if (Scale & 1) return false;
10385     return isPowerOf2_32(Scale);
10386   }
10387 }
10388
10389 /// isLegalAddressingMode - Return true if the addressing mode represented
10390 /// by AM is legal for this target, for a load/store of the specified type.
10391 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10392                                               Type *Ty) const {
10393   EVT VT = getValueType(Ty, true);
10394   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10395     return false;
10396
10397   // Can never fold addr of global into load/store.
10398   if (AM.BaseGV)
10399     return false;
10400
10401   switch (AM.Scale) {
10402   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10403     break;
10404   case 1:
10405     if (Subtarget->isThumb1Only())
10406       return false;
10407     // FALL THROUGH.
10408   default:
10409     // ARM doesn't support any R+R*scale+imm addr modes.
10410     if (AM.BaseOffs)
10411       return false;
10412
10413     if (!VT.isSimple())
10414       return false;
10415
10416     if (Subtarget->isThumb2())
10417       return isLegalT2ScaledAddressingMode(AM, VT);
10418
10419     int Scale = AM.Scale;
10420     switch (VT.getSimpleVT().SimpleTy) {
10421     default: return false;
10422     case MVT::i1:
10423     case MVT::i8:
10424     case MVT::i32:
10425       if (Scale < 0) Scale = -Scale;
10426       if (Scale == 1)
10427         return true;
10428       // r + r << imm
10429       return isPowerOf2_32(Scale & ~1);
10430     case MVT::i16:
10431     case MVT::i64:
10432       // r + r
10433       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10434         return true;
10435       return false;
10436
10437     case MVT::isVoid:
10438       // Note, we allow "void" uses (basically, uses that aren't loads or
10439       // stores), because arm allows folding a scale into many arithmetic
10440       // operations.  This should be made more precise and revisited later.
10441
10442       // Allow r << imm, but the imm has to be a multiple of two.
10443       if (Scale & 1) return false;
10444       return isPowerOf2_32(Scale);
10445     }
10446   }
10447   return true;
10448 }
10449
10450 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10451 /// icmp immediate, that is the target has icmp instructions which can compare
10452 /// a register against the immediate without having to materialize the
10453 /// immediate into a register.
10454 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10455   // Thumb2 and ARM modes can use cmn for negative immediates.
10456   if (!Subtarget->isThumb())
10457     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10458   if (Subtarget->isThumb2())
10459     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10460   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10461   return Imm >= 0 && Imm <= 255;
10462 }
10463
10464 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10465 /// *or sub* immediate, that is the target has add or sub instructions which can
10466 /// add a register with the immediate without having to materialize the
10467 /// immediate into a register.
10468 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10469   // Same encoding for add/sub, just flip the sign.
10470   int64_t AbsImm = llvm::abs64(Imm);
10471   if (!Subtarget->isThumb())
10472     return ARM_AM::getSOImmVal(AbsImm) != -1;
10473   if (Subtarget->isThumb2())
10474     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10475   // Thumb1 only has 8-bit unsigned immediate.
10476   return AbsImm >= 0 && AbsImm <= 255;
10477 }
10478
10479 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10480                                       bool isSEXTLoad, SDValue &Base,
10481                                       SDValue &Offset, bool &isInc,
10482                                       SelectionDAG &DAG) {
10483   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10484     return false;
10485
10486   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10487     // AddressingMode 3
10488     Base = Ptr->getOperand(0);
10489     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10490       int RHSC = (int)RHS->getZExtValue();
10491       if (RHSC < 0 && RHSC > -256) {
10492         assert(Ptr->getOpcode() == ISD::ADD);
10493         isInc = false;
10494         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10495         return true;
10496       }
10497     }
10498     isInc = (Ptr->getOpcode() == ISD::ADD);
10499     Offset = Ptr->getOperand(1);
10500     return true;
10501   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10502     // AddressingMode 2
10503     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10504       int RHSC = (int)RHS->getZExtValue();
10505       if (RHSC < 0 && RHSC > -0x1000) {
10506         assert(Ptr->getOpcode() == ISD::ADD);
10507         isInc = false;
10508         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10509         Base = Ptr->getOperand(0);
10510         return true;
10511       }
10512     }
10513
10514     if (Ptr->getOpcode() == ISD::ADD) {
10515       isInc = true;
10516       ARM_AM::ShiftOpc ShOpcVal=
10517         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10518       if (ShOpcVal != ARM_AM::no_shift) {
10519         Base = Ptr->getOperand(1);
10520         Offset = Ptr->getOperand(0);
10521       } else {
10522         Base = Ptr->getOperand(0);
10523         Offset = Ptr->getOperand(1);
10524       }
10525       return true;
10526     }
10527
10528     isInc = (Ptr->getOpcode() == ISD::ADD);
10529     Base = Ptr->getOperand(0);
10530     Offset = Ptr->getOperand(1);
10531     return true;
10532   }
10533
10534   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10535   return false;
10536 }
10537
10538 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10539                                      bool isSEXTLoad, SDValue &Base,
10540                                      SDValue &Offset, bool &isInc,
10541                                      SelectionDAG &DAG) {
10542   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10543     return false;
10544
10545   Base = Ptr->getOperand(0);
10546   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10547     int RHSC = (int)RHS->getZExtValue();
10548     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10549       assert(Ptr->getOpcode() == ISD::ADD);
10550       isInc = false;
10551       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10552       return true;
10553     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10554       isInc = Ptr->getOpcode() == ISD::ADD;
10555       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10556       return true;
10557     }
10558   }
10559
10560   return false;
10561 }
10562
10563 /// getPreIndexedAddressParts - returns true by value, base pointer and
10564 /// offset pointer and addressing mode by reference if the node's address
10565 /// can be legally represented as pre-indexed load / store address.
10566 bool
10567 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10568                                              SDValue &Offset,
10569                                              ISD::MemIndexedMode &AM,
10570                                              SelectionDAG &DAG) const {
10571   if (Subtarget->isThumb1Only())
10572     return false;
10573
10574   EVT VT;
10575   SDValue Ptr;
10576   bool isSEXTLoad = false;
10577   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10578     Ptr = LD->getBasePtr();
10579     VT  = LD->getMemoryVT();
10580     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10581   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10582     Ptr = ST->getBasePtr();
10583     VT  = ST->getMemoryVT();
10584   } else
10585     return false;
10586
10587   bool isInc;
10588   bool isLegal = false;
10589   if (Subtarget->isThumb2())
10590     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10591                                        Offset, isInc, DAG);
10592   else
10593     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10594                                         Offset, isInc, DAG);
10595   if (!isLegal)
10596     return false;
10597
10598   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10599   return true;
10600 }
10601
10602 /// getPostIndexedAddressParts - returns true by value, base pointer and
10603 /// offset pointer and addressing mode by reference if this node can be
10604 /// combined with a load / store to form a post-indexed load / store.
10605 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10606                                                    SDValue &Base,
10607                                                    SDValue &Offset,
10608                                                    ISD::MemIndexedMode &AM,
10609                                                    SelectionDAG &DAG) const {
10610   if (Subtarget->isThumb1Only())
10611     return false;
10612
10613   EVT VT;
10614   SDValue Ptr;
10615   bool isSEXTLoad = false;
10616   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10617     VT  = LD->getMemoryVT();
10618     Ptr = LD->getBasePtr();
10619     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10620   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10621     VT  = ST->getMemoryVT();
10622     Ptr = ST->getBasePtr();
10623   } else
10624     return false;
10625
10626   bool isInc;
10627   bool isLegal = false;
10628   if (Subtarget->isThumb2())
10629     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10630                                        isInc, DAG);
10631   else
10632     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10633                                         isInc, DAG);
10634   if (!isLegal)
10635     return false;
10636
10637   if (Ptr != Base) {
10638     // Swap base ptr and offset to catch more post-index load / store when
10639     // it's legal. In Thumb2 mode, offset must be an immediate.
10640     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10641         !Subtarget->isThumb2())
10642       std::swap(Base, Offset);
10643
10644     // Post-indexed load / store update the base pointer.
10645     if (Ptr != Base)
10646       return false;
10647   }
10648
10649   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10650   return true;
10651 }
10652
10653 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10654                                                        APInt &KnownZero,
10655                                                        APInt &KnownOne,
10656                                                        const SelectionDAG &DAG,
10657                                                        unsigned Depth) const {
10658   unsigned BitWidth = KnownOne.getBitWidth();
10659   KnownZero = KnownOne = APInt(BitWidth, 0);
10660   switch (Op.getOpcode()) {
10661   default: break;
10662   case ARMISD::ADDC:
10663   case ARMISD::ADDE:
10664   case ARMISD::SUBC:
10665   case ARMISD::SUBE:
10666     // These nodes' second result is a boolean
10667     if (Op.getResNo() == 0)
10668       break;
10669     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10670     break;
10671   case ARMISD::CMOV: {
10672     // Bits are known zero/one if known on the LHS and RHS.
10673     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10674     if (KnownZero == 0 && KnownOne == 0) return;
10675
10676     APInt KnownZeroRHS, KnownOneRHS;
10677     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10678     KnownZero &= KnownZeroRHS;
10679     KnownOne  &= KnownOneRHS;
10680     return;
10681   }
10682   }
10683 }
10684
10685 //===----------------------------------------------------------------------===//
10686 //                           ARM Inline Assembly Support
10687 //===----------------------------------------------------------------------===//
10688
10689 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10690   // Looking for "rev" which is V6+.
10691   if (!Subtarget->hasV6Ops())
10692     return false;
10693
10694   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10695   std::string AsmStr = IA->getAsmString();
10696   SmallVector<StringRef, 4> AsmPieces;
10697   SplitString(AsmStr, AsmPieces, ";\n");
10698
10699   switch (AsmPieces.size()) {
10700   default: return false;
10701   case 1:
10702     AsmStr = AsmPieces[0];
10703     AsmPieces.clear();
10704     SplitString(AsmStr, AsmPieces, " \t,");
10705
10706     // rev $0, $1
10707     if (AsmPieces.size() == 3 &&
10708         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10709         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10710       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10711       if (Ty && Ty->getBitWidth() == 32)
10712         return IntrinsicLowering::LowerToByteSwap(CI);
10713     }
10714     break;
10715   }
10716
10717   return false;
10718 }
10719
10720 /// getConstraintType - Given a constraint letter, return the type of
10721 /// constraint it is for this target.
10722 ARMTargetLowering::ConstraintType
10723 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10724   if (Constraint.size() == 1) {
10725     switch (Constraint[0]) {
10726     default:  break;
10727     case 'l': return C_RegisterClass;
10728     case 'w': return C_RegisterClass;
10729     case 'h': return C_RegisterClass;
10730     case 'x': return C_RegisterClass;
10731     case 't': return C_RegisterClass;
10732     case 'j': return C_Other; // Constant for movw.
10733       // An address with a single base register. Due to the way we
10734       // currently handle addresses it is the same as an 'r' memory constraint.
10735     case 'Q': return C_Memory;
10736     }
10737   } else if (Constraint.size() == 2) {
10738     switch (Constraint[0]) {
10739     default: break;
10740     // All 'U+' constraints are addresses.
10741     case 'U': return C_Memory;
10742     }
10743   }
10744   return TargetLowering::getConstraintType(Constraint);
10745 }
10746
10747 /// Examine constraint type and operand type and determine a weight value.
10748 /// This object must already have been set up with the operand type
10749 /// and the current alternative constraint selected.
10750 TargetLowering::ConstraintWeight
10751 ARMTargetLowering::getSingleConstraintMatchWeight(
10752     AsmOperandInfo &info, const char *constraint) const {
10753   ConstraintWeight weight = CW_Invalid;
10754   Value *CallOperandVal = info.CallOperandVal;
10755     // If we don't have a value, we can't do a match,
10756     // but allow it at the lowest weight.
10757   if (CallOperandVal == NULL)
10758     return CW_Default;
10759   Type *type = CallOperandVal->getType();
10760   // Look at the constraint type.
10761   switch (*constraint) {
10762   default:
10763     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10764     break;
10765   case 'l':
10766     if (type->isIntegerTy()) {
10767       if (Subtarget->isThumb())
10768         weight = CW_SpecificReg;
10769       else
10770         weight = CW_Register;
10771     }
10772     break;
10773   case 'w':
10774     if (type->isFloatingPointTy())
10775       weight = CW_Register;
10776     break;
10777   }
10778   return weight;
10779 }
10780
10781 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10782 RCPair
10783 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10784                                                 MVT VT) const {
10785   if (Constraint.size() == 1) {
10786     // GCC ARM Constraint Letters
10787     switch (Constraint[0]) {
10788     case 'l': // Low regs or general regs.
10789       if (Subtarget->isThumb())
10790         return RCPair(0U, &ARM::tGPRRegClass);
10791       return RCPair(0U, &ARM::GPRRegClass);
10792     case 'h': // High regs or no regs.
10793       if (Subtarget->isThumb())
10794         return RCPair(0U, &ARM::hGPRRegClass);
10795       break;
10796     case 'r':
10797       return RCPair(0U, &ARM::GPRRegClass);
10798     case 'w':
10799       if (VT == MVT::f32)
10800         return RCPair(0U, &ARM::SPRRegClass);
10801       if (VT.getSizeInBits() == 64)
10802         return RCPair(0U, &ARM::DPRRegClass);
10803       if (VT.getSizeInBits() == 128)
10804         return RCPair(0U, &ARM::QPRRegClass);
10805       break;
10806     case 'x':
10807       if (VT == MVT::f32)
10808         return RCPair(0U, &ARM::SPR_8RegClass);
10809       if (VT.getSizeInBits() == 64)
10810         return RCPair(0U, &ARM::DPR_8RegClass);
10811       if (VT.getSizeInBits() == 128)
10812         return RCPair(0U, &ARM::QPR_8RegClass);
10813       break;
10814     case 't':
10815       if (VT == MVT::f32)
10816         return RCPair(0U, &ARM::SPRRegClass);
10817       break;
10818     }
10819   }
10820   if (StringRef("{cc}").equals_lower(Constraint))
10821     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10822
10823   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10824 }
10825
10826 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10827 /// vector.  If it is invalid, don't add anything to Ops.
10828 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10829                                                      std::string &Constraint,
10830                                                      std::vector<SDValue>&Ops,
10831                                                      SelectionDAG &DAG) const {
10832   SDValue Result(0, 0);
10833
10834   // Currently only support length 1 constraints.
10835   if (Constraint.length() != 1) return;
10836
10837   char ConstraintLetter = Constraint[0];
10838   switch (ConstraintLetter) {
10839   default: break;
10840   case 'j':
10841   case 'I': case 'J': case 'K': case 'L':
10842   case 'M': case 'N': case 'O':
10843     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10844     if (!C)
10845       return;
10846
10847     int64_t CVal64 = C->getSExtValue();
10848     int CVal = (int) CVal64;
10849     // None of these constraints allow values larger than 32 bits.  Check
10850     // that the value fits in an int.
10851     if (CVal != CVal64)
10852       return;
10853
10854     switch (ConstraintLetter) {
10855       case 'j':
10856         // Constant suitable for movw, must be between 0 and
10857         // 65535.
10858         if (Subtarget->hasV6T2Ops())
10859           if (CVal >= 0 && CVal <= 65535)
10860             break;
10861         return;
10862       case 'I':
10863         if (Subtarget->isThumb1Only()) {
10864           // This must be a constant between 0 and 255, for ADD
10865           // immediates.
10866           if (CVal >= 0 && CVal <= 255)
10867             break;
10868         } else if (Subtarget->isThumb2()) {
10869           // A constant that can be used as an immediate value in a
10870           // data-processing instruction.
10871           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10872             break;
10873         } else {
10874           // A constant that can be used as an immediate value in a
10875           // data-processing instruction.
10876           if (ARM_AM::getSOImmVal(CVal) != -1)
10877             break;
10878         }
10879         return;
10880
10881       case 'J':
10882         if (Subtarget->isThumb()) {  // FIXME thumb2
10883           // This must be a constant between -255 and -1, for negated ADD
10884           // immediates. This can be used in GCC with an "n" modifier that
10885           // prints the negated value, for use with SUB instructions. It is
10886           // not useful otherwise but is implemented for compatibility.
10887           if (CVal >= -255 && CVal <= -1)
10888             break;
10889         } else {
10890           // This must be a constant between -4095 and 4095. It is not clear
10891           // what this constraint is intended for. Implemented for
10892           // compatibility with GCC.
10893           if (CVal >= -4095 && CVal <= 4095)
10894             break;
10895         }
10896         return;
10897
10898       case 'K':
10899         if (Subtarget->isThumb1Only()) {
10900           // A 32-bit value where only one byte has a nonzero value. Exclude
10901           // zero to match GCC. This constraint is used by GCC internally for
10902           // constants that can be loaded with a move/shift combination.
10903           // It is not useful otherwise but is implemented for compatibility.
10904           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10905             break;
10906         } else if (Subtarget->isThumb2()) {
10907           // A constant whose bitwise inverse can be used as an immediate
10908           // value in a data-processing instruction. This can be used in GCC
10909           // with a "B" modifier that prints the inverted value, for use with
10910           // BIC and MVN instructions. It is not useful otherwise but is
10911           // implemented for compatibility.
10912           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10913             break;
10914         } else {
10915           // A constant whose bitwise inverse can be used as an immediate
10916           // value in a data-processing instruction. This can be used in GCC
10917           // with a "B" modifier that prints the inverted value, for use with
10918           // BIC and MVN instructions. It is not useful otherwise but is
10919           // implemented for compatibility.
10920           if (ARM_AM::getSOImmVal(~CVal) != -1)
10921             break;
10922         }
10923         return;
10924
10925       case 'L':
10926         if (Subtarget->isThumb1Only()) {
10927           // This must be a constant between -7 and 7,
10928           // for 3-operand ADD/SUB immediate instructions.
10929           if (CVal >= -7 && CVal < 7)
10930             break;
10931         } else if (Subtarget->isThumb2()) {
10932           // A constant whose negation can be used as an immediate value in a
10933           // data-processing instruction. This can be used in GCC with an "n"
10934           // modifier that prints the negated value, for use with SUB
10935           // instructions. It is not useful otherwise but is implemented for
10936           // compatibility.
10937           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10938             break;
10939         } else {
10940           // A constant whose negation can be used as an immediate value in a
10941           // data-processing instruction. This can be used in GCC with an "n"
10942           // modifier that prints the negated value, for use with SUB
10943           // instructions. It is not useful otherwise but is implemented for
10944           // compatibility.
10945           if (ARM_AM::getSOImmVal(-CVal) != -1)
10946             break;
10947         }
10948         return;
10949
10950       case 'M':
10951         if (Subtarget->isThumb()) { // FIXME thumb2
10952           // This must be a multiple of 4 between 0 and 1020, for
10953           // ADD sp + immediate.
10954           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10955             break;
10956         } else {
10957           // A power of two or a constant between 0 and 32.  This is used in
10958           // GCC for the shift amount on shifted register operands, but it is
10959           // useful in general for any shift amounts.
10960           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10961             break;
10962         }
10963         return;
10964
10965       case 'N':
10966         if (Subtarget->isThumb()) {  // FIXME thumb2
10967           // This must be a constant between 0 and 31, for shift amounts.
10968           if (CVal >= 0 && CVal <= 31)
10969             break;
10970         }
10971         return;
10972
10973       case 'O':
10974         if (Subtarget->isThumb()) {  // FIXME thumb2
10975           // This must be a multiple of 4 between -508 and 508, for
10976           // ADD/SUB sp = sp + immediate.
10977           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10978             break;
10979         }
10980         return;
10981     }
10982     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10983     break;
10984   }
10985
10986   if (Result.getNode()) {
10987     Ops.push_back(Result);
10988     return;
10989   }
10990   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10991 }
10992
10993 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10994   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10995   unsigned Opcode = Op->getOpcode();
10996   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10997       "Invalid opcode for Div/Rem lowering");
10998   bool isSigned = (Opcode == ISD::SDIVREM);
10999   EVT VT = Op->getValueType(0);
11000   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11001
11002   RTLIB::Libcall LC;
11003   switch (VT.getSimpleVT().SimpleTy) {
11004   default: llvm_unreachable("Unexpected request for libcall!");
11005   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
11006   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11007   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11008   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11009   }
11010
11011   SDValue InChain = DAG.getEntryNode();
11012
11013   TargetLowering::ArgListTy Args;
11014   TargetLowering::ArgListEntry Entry;
11015   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
11016     EVT ArgVT = Op->getOperand(i).getValueType();
11017     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11018     Entry.Node = Op->getOperand(i);
11019     Entry.Ty = ArgTy;
11020     Entry.isSExt = isSigned;
11021     Entry.isZExt = !isSigned;
11022     Args.push_back(Entry);
11023   }
11024
11025   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11026                                          getPointerTy());
11027
11028   Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
11029
11030   SDLoc dl(Op);
11031   TargetLowering::
11032   CallLoweringInfo CLI(InChain, RetTy, isSigned, !isSigned, false, true,
11033                     0, getLibcallCallingConv(LC), /*isTailCall=*/false,
11034                     /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
11035                     Callee, Args, DAG, dl);
11036   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11037
11038   return CallInfo.first;
11039 }
11040
11041 bool
11042 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11043   // The ARM target isn't yet aware of offsets.
11044   return false;
11045 }
11046
11047 bool ARM::isBitFieldInvertedMask(unsigned v) {
11048   if (v == 0xffffffff)
11049     return false;
11050
11051   // there can be 1's on either or both "outsides", all the "inside"
11052   // bits must be 0's
11053   unsigned TO = CountTrailingOnes_32(v);
11054   unsigned LO = CountLeadingOnes_32(v);
11055   v = (v >> TO) << TO;
11056   v = (v << LO) >> LO;
11057   return v == 0;
11058 }
11059
11060 /// isFPImmLegal - Returns true if the target can instruction select the
11061 /// specified FP immediate natively. If false, the legalizer will
11062 /// materialize the FP immediate as a load from a constant pool.
11063 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11064   if (!Subtarget->hasVFP3())
11065     return false;
11066   if (VT == MVT::f32)
11067     return ARM_AM::getFP32Imm(Imm) != -1;
11068   if (VT == MVT::f64)
11069     return ARM_AM::getFP64Imm(Imm) != -1;
11070   return false;
11071 }
11072
11073 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11074 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11075 /// specified in the intrinsic calls.
11076 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11077                                            const CallInst &I,
11078                                            unsigned Intrinsic) const {
11079   switch (Intrinsic) {
11080   case Intrinsic::arm_neon_vld1:
11081   case Intrinsic::arm_neon_vld2:
11082   case Intrinsic::arm_neon_vld3:
11083   case Intrinsic::arm_neon_vld4:
11084   case Intrinsic::arm_neon_vld2lane:
11085   case Intrinsic::arm_neon_vld3lane:
11086   case Intrinsic::arm_neon_vld4lane: {
11087     Info.opc = ISD::INTRINSIC_W_CHAIN;
11088     // Conservatively set memVT to the entire set of vectors loaded.
11089     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
11090     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11091     Info.ptrVal = I.getArgOperand(0);
11092     Info.offset = 0;
11093     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11094     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11095     Info.vol = false; // volatile loads with NEON intrinsics not supported
11096     Info.readMem = true;
11097     Info.writeMem = false;
11098     return true;
11099   }
11100   case Intrinsic::arm_neon_vst1:
11101   case Intrinsic::arm_neon_vst2:
11102   case Intrinsic::arm_neon_vst3:
11103   case Intrinsic::arm_neon_vst4:
11104   case Intrinsic::arm_neon_vst2lane:
11105   case Intrinsic::arm_neon_vst3lane:
11106   case Intrinsic::arm_neon_vst4lane: {
11107     Info.opc = ISD::INTRINSIC_VOID;
11108     // Conservatively set memVT to the entire set of vectors stored.
11109     unsigned NumElts = 0;
11110     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11111       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11112       if (!ArgTy->isVectorTy())
11113         break;
11114       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
11115     }
11116     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11117     Info.ptrVal = I.getArgOperand(0);
11118     Info.offset = 0;
11119     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11120     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11121     Info.vol = false; // volatile stores with NEON intrinsics not supported
11122     Info.readMem = false;
11123     Info.writeMem = true;
11124     return true;
11125   }
11126   case Intrinsic::arm_ldrex: {
11127     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11128     Info.opc = ISD::INTRINSIC_W_CHAIN;
11129     Info.memVT = MVT::getVT(PtrTy->getElementType());
11130     Info.ptrVal = I.getArgOperand(0);
11131     Info.offset = 0;
11132     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11133     Info.vol = true;
11134     Info.readMem = true;
11135     Info.writeMem = false;
11136     return true;
11137   }
11138   case Intrinsic::arm_strex: {
11139     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11140     Info.opc = ISD::INTRINSIC_W_CHAIN;
11141     Info.memVT = MVT::getVT(PtrTy->getElementType());
11142     Info.ptrVal = I.getArgOperand(1);
11143     Info.offset = 0;
11144     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11145     Info.vol = true;
11146     Info.readMem = false;
11147     Info.writeMem = true;
11148     return true;
11149   }
11150   case Intrinsic::arm_strexd: {
11151     Info.opc = ISD::INTRINSIC_W_CHAIN;
11152     Info.memVT = MVT::i64;
11153     Info.ptrVal = I.getArgOperand(2);
11154     Info.offset = 0;
11155     Info.align = 8;
11156     Info.vol = true;
11157     Info.readMem = false;
11158     Info.writeMem = true;
11159     return true;
11160   }
11161   case Intrinsic::arm_ldrexd: {
11162     Info.opc = ISD::INTRINSIC_W_CHAIN;
11163     Info.memVT = MVT::i64;
11164     Info.ptrVal = I.getArgOperand(0);
11165     Info.offset = 0;
11166     Info.align = 8;
11167     Info.vol = true;
11168     Info.readMem = true;
11169     Info.writeMem = false;
11170     return true;
11171   }
11172   default:
11173     break;
11174   }
11175
11176   return false;
11177 }