96942ec8b7dab580fd5dd144399ba75a4b8adf33
[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::PIC_ADD:       return "ARMISD::PIC_ADD";
1019   case ARMISD::CMP:           return "ARMISD::CMP";
1020   case ARMISD::CMN:           return "ARMISD::CMN";
1021   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1022   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1023   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1024   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1025   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1026
1027   case ARMISD::CMOV:          return "ARMISD::CMOV";
1028
1029   case ARMISD::RBIT:          return "ARMISD::RBIT";
1030
1031   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
1032   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
1033   case ARMISD::SITOF:         return "ARMISD::SITOF";
1034   case ARMISD::UITOF:         return "ARMISD::UITOF";
1035
1036   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1037   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1038   case ARMISD::RRX:           return "ARMISD::RRX";
1039
1040   case ARMISD::ADDC:          return "ARMISD::ADDC";
1041   case ARMISD::ADDE:          return "ARMISD::ADDE";
1042   case ARMISD::SUBC:          return "ARMISD::SUBC";
1043   case ARMISD::SUBE:          return "ARMISD::SUBE";
1044
1045   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1046   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1047
1048   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1049   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1050
1051   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1052
1053   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1054
1055   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1056
1057   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1058
1059   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1060
1061   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1062   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1063   case ARMISD::VCGE:          return "ARMISD::VCGE";
1064   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1065   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1066   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1067   case ARMISD::VCGT:          return "ARMISD::VCGT";
1068   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1069   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1070   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1071   case ARMISD::VTST:          return "ARMISD::VTST";
1072
1073   case ARMISD::VSHL:          return "ARMISD::VSHL";
1074   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1075   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1076   case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
1077   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
1078   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
1079   case ARMISD::VSHRN:         return "ARMISD::VSHRN";
1080   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1081   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1082   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1083   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1084   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1085   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1086   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1087   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1088   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1089   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1090   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1091   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1092   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1093   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1094   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1095   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1096   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1097   case ARMISD::VDUP:          return "ARMISD::VDUP";
1098   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1099   case ARMISD::VEXT:          return "ARMISD::VEXT";
1100   case ARMISD::VREV64:        return "ARMISD::VREV64";
1101   case ARMISD::VREV32:        return "ARMISD::VREV32";
1102   case ARMISD::VREV16:        return "ARMISD::VREV16";
1103   case ARMISD::VZIP:          return "ARMISD::VZIP";
1104   case ARMISD::VUZP:          return "ARMISD::VUZP";
1105   case ARMISD::VTRN:          return "ARMISD::VTRN";
1106   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1107   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1108   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1109   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1110   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1111   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1112   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1113   case ARMISD::FMAX:          return "ARMISD::FMAX";
1114   case ARMISD::FMIN:          return "ARMISD::FMIN";
1115   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1116   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1117   case ARMISD::BFI:           return "ARMISD::BFI";
1118   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1119   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1120   case ARMISD::VBSL:          return "ARMISD::VBSL";
1121   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1122   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1123   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1124   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1125   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1126   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1127   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1128   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1129   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1130   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1131   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1132   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1133   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1134   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1135   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1136   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1137   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1138   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1139   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1140   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1141   }
1142 }
1143
1144 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1145   if (!VT.isVector()) return getPointerTy();
1146   return VT.changeVectorElementTypeToInteger();
1147 }
1148
1149 /// getRegClassFor - Return the register class that should be used for the
1150 /// specified value type.
1151 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1152   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1153   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1154   // load / store 4 to 8 consecutive D registers.
1155   if (Subtarget->hasNEON()) {
1156     if (VT == MVT::v4i64)
1157       return &ARM::QQPRRegClass;
1158     if (VT == MVT::v8i64)
1159       return &ARM::QQQQPRRegClass;
1160   }
1161   return TargetLowering::getRegClassFor(VT);
1162 }
1163
1164 // Create a fast isel object.
1165 FastISel *
1166 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1167                                   const TargetLibraryInfo *libInfo) const {
1168   return ARM::createFastISel(funcInfo, libInfo);
1169 }
1170
1171 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1172 /// be used for loads / stores from the global.
1173 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1174   return (Subtarget->isThumb1Only() ? 127 : 4095);
1175 }
1176
1177 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1178   unsigned NumVals = N->getNumValues();
1179   if (!NumVals)
1180     return Sched::RegPressure;
1181
1182   for (unsigned i = 0; i != NumVals; ++i) {
1183     EVT VT = N->getValueType(i);
1184     if (VT == MVT::Glue || VT == MVT::Other)
1185       continue;
1186     if (VT.isFloatingPoint() || VT.isVector())
1187       return Sched::ILP;
1188   }
1189
1190   if (!N->isMachineOpcode())
1191     return Sched::RegPressure;
1192
1193   // Load are scheduled for latency even if there instruction itinerary
1194   // is not available.
1195   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1196   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1197
1198   if (MCID.getNumDefs() == 0)
1199     return Sched::RegPressure;
1200   if (!Itins->isEmpty() &&
1201       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1202     return Sched::ILP;
1203
1204   return Sched::RegPressure;
1205 }
1206
1207 //===----------------------------------------------------------------------===//
1208 // Lowering Code
1209 //===----------------------------------------------------------------------===//
1210
1211 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1212 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1213   switch (CC) {
1214   default: llvm_unreachable("Unknown condition code!");
1215   case ISD::SETNE:  return ARMCC::NE;
1216   case ISD::SETEQ:  return ARMCC::EQ;
1217   case ISD::SETGT:  return ARMCC::GT;
1218   case ISD::SETGE:  return ARMCC::GE;
1219   case ISD::SETLT:  return ARMCC::LT;
1220   case ISD::SETLE:  return ARMCC::LE;
1221   case ISD::SETUGT: return ARMCC::HI;
1222   case ISD::SETUGE: return ARMCC::HS;
1223   case ISD::SETULT: return ARMCC::LO;
1224   case ISD::SETULE: return ARMCC::LS;
1225   }
1226 }
1227
1228 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1229 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1230                         ARMCC::CondCodes &CondCode2) {
1231   CondCode2 = ARMCC::AL;
1232   switch (CC) {
1233   default: llvm_unreachable("Unknown FP condition!");
1234   case ISD::SETEQ:
1235   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1236   case ISD::SETGT:
1237   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1238   case ISD::SETGE:
1239   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1240   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1241   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1242   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1243   case ISD::SETO:   CondCode = ARMCC::VC; break;
1244   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1245   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1246   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1247   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1248   case ISD::SETLT:
1249   case ISD::SETULT: CondCode = ARMCC::LT; break;
1250   case ISD::SETLE:
1251   case ISD::SETULE: CondCode = ARMCC::LE; break;
1252   case ISD::SETNE:
1253   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1254   }
1255 }
1256
1257 //===----------------------------------------------------------------------===//
1258 //                      Calling Convention Implementation
1259 //===----------------------------------------------------------------------===//
1260
1261 #include "ARMGenCallingConv.inc"
1262
1263 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1264 /// given CallingConvention value.
1265 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1266                                                  bool Return,
1267                                                  bool isVarArg) const {
1268   switch (CC) {
1269   default:
1270     llvm_unreachable("Unsupported calling convention");
1271   case CallingConv::Fast:
1272     if (Subtarget->hasVFP2() && !isVarArg) {
1273       if (!Subtarget->isAAPCS_ABI())
1274         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1275       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1276       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1277     }
1278     // Fallthrough
1279   case CallingConv::C: {
1280     // Use target triple & subtarget features to do actual dispatch.
1281     if (!Subtarget->isAAPCS_ABI())
1282       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1283     else if (Subtarget->hasVFP2() &&
1284              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1285              !isVarArg)
1286       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1287     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1288   }
1289   case CallingConv::ARM_AAPCS_VFP:
1290     if (!isVarArg)
1291       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1292     // Fallthrough
1293   case CallingConv::ARM_AAPCS:
1294     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1295   case CallingConv::ARM_APCS:
1296     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1297   case CallingConv::GHC:
1298     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1299   }
1300 }
1301
1302 /// LowerCallResult - Lower the result values of a call into the
1303 /// appropriate copies out of appropriate physical registers.
1304 SDValue
1305 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1306                                    CallingConv::ID CallConv, bool isVarArg,
1307                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1308                                    SDLoc dl, SelectionDAG &DAG,
1309                                    SmallVectorImpl<SDValue> &InVals,
1310                                    bool isThisReturn, SDValue ThisVal) const {
1311
1312   // Assign locations to each value returned by this call.
1313   SmallVector<CCValAssign, 16> RVLocs;
1314   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1315                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1316   CCInfo.AnalyzeCallResult(Ins,
1317                            CCAssignFnForNode(CallConv, /* Return*/ true,
1318                                              isVarArg));
1319
1320   // Copy all of the result registers out of their specified physreg.
1321   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1322     CCValAssign VA = RVLocs[i];
1323
1324     // Pass 'this' value directly from the argument to return value, to avoid
1325     // reg unit interference
1326     if (i == 0 && isThisReturn) {
1327       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1328              "unexpected return calling convention register assignment");
1329       InVals.push_back(ThisVal);
1330       continue;
1331     }
1332
1333     SDValue Val;
1334     if (VA.needsCustom()) {
1335       // Handle f64 or half of a v2f64.
1336       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1337                                       InFlag);
1338       Chain = Lo.getValue(1);
1339       InFlag = Lo.getValue(2);
1340       VA = RVLocs[++i]; // skip ahead to next loc
1341       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1342                                       InFlag);
1343       Chain = Hi.getValue(1);
1344       InFlag = Hi.getValue(2);
1345       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1346
1347       if (VA.getLocVT() == MVT::v2f64) {
1348         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1349         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1350                           DAG.getConstant(0, MVT::i32));
1351
1352         VA = RVLocs[++i]; // skip ahead to next loc
1353         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1354         Chain = Lo.getValue(1);
1355         InFlag = Lo.getValue(2);
1356         VA = RVLocs[++i]; // skip ahead to next loc
1357         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1358         Chain = Hi.getValue(1);
1359         InFlag = Hi.getValue(2);
1360         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1361         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1362                           DAG.getConstant(1, MVT::i32));
1363       }
1364     } else {
1365       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1366                                InFlag);
1367       Chain = Val.getValue(1);
1368       InFlag = Val.getValue(2);
1369     }
1370
1371     switch (VA.getLocInfo()) {
1372     default: llvm_unreachable("Unknown loc info!");
1373     case CCValAssign::Full: break;
1374     case CCValAssign::BCvt:
1375       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1376       break;
1377     }
1378
1379     InVals.push_back(Val);
1380   }
1381
1382   return Chain;
1383 }
1384
1385 /// LowerMemOpCallTo - Store the argument to the stack.
1386 SDValue
1387 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1388                                     SDValue StackPtr, SDValue Arg,
1389                                     SDLoc dl, SelectionDAG &DAG,
1390                                     const CCValAssign &VA,
1391                                     ISD::ArgFlagsTy Flags) const {
1392   unsigned LocMemOffset = VA.getLocMemOffset();
1393   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1394   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1395   return DAG.getStore(Chain, dl, Arg, PtrOff,
1396                       MachinePointerInfo::getStack(LocMemOffset),
1397                       false, false, 0);
1398 }
1399
1400 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1401                                          SDValue Chain, SDValue &Arg,
1402                                          RegsToPassVector &RegsToPass,
1403                                          CCValAssign &VA, CCValAssign &NextVA,
1404                                          SDValue &StackPtr,
1405                                          SmallVectorImpl<SDValue> &MemOpChains,
1406                                          ISD::ArgFlagsTy Flags) const {
1407
1408   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1409                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1410   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1411
1412   if (NextVA.isRegLoc())
1413     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1414   else {
1415     assert(NextVA.isMemLoc());
1416     if (StackPtr.getNode() == 0)
1417       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1418
1419     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1420                                            dl, DAG, NextVA,
1421                                            Flags));
1422   }
1423 }
1424
1425 /// LowerCall - Lowering a call into a callseq_start <-
1426 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1427 /// nodes.
1428 SDValue
1429 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1430                              SmallVectorImpl<SDValue> &InVals) const {
1431   SelectionDAG &DAG                     = CLI.DAG;
1432   SDLoc &dl                          = CLI.DL;
1433   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1434   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1435   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1436   SDValue Chain                         = CLI.Chain;
1437   SDValue Callee                        = CLI.Callee;
1438   bool &isTailCall                      = CLI.IsTailCall;
1439   CallingConv::ID CallConv              = CLI.CallConv;
1440   bool doesNotRet                       = CLI.DoesNotReturn;
1441   bool isVarArg                         = CLI.IsVarArg;
1442
1443   MachineFunction &MF = DAG.getMachineFunction();
1444   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1445   bool isThisReturn   = false;
1446   bool isSibCall      = false;
1447   // Disable tail calls if they're not supported.
1448   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1449     isTailCall = false;
1450   if (isTailCall) {
1451     // Check if it's really possible to do a tail call.
1452     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1453                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1454                                                    Outs, OutVals, Ins, DAG);
1455     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1456     // detected sibcalls.
1457     if (isTailCall) {
1458       ++NumTailCalls;
1459       isSibCall = true;
1460     }
1461   }
1462
1463   // Analyze operands of the call, assigning locations to each operand.
1464   SmallVector<CCValAssign, 16> ArgLocs;
1465   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1466                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1467   CCInfo.AnalyzeCallOperands(Outs,
1468                              CCAssignFnForNode(CallConv, /* Return*/ false,
1469                                                isVarArg));
1470
1471   // Get a count of how many bytes are to be pushed on the stack.
1472   unsigned NumBytes = CCInfo.getNextStackOffset();
1473
1474   // For tail calls, memory operands are available in our caller's stack.
1475   if (isSibCall)
1476     NumBytes = 0;
1477
1478   // Adjust the stack pointer for the new arguments...
1479   // These operations are automatically eliminated by the prolog/epilog pass
1480   if (!isSibCall)
1481     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1482                                  dl);
1483
1484   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1485
1486   RegsToPassVector RegsToPass;
1487   SmallVector<SDValue, 8> MemOpChains;
1488
1489   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1490   // of tail call optimization, arguments are handled later.
1491   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1492        i != e;
1493        ++i, ++realArgIdx) {
1494     CCValAssign &VA = ArgLocs[i];
1495     SDValue Arg = OutVals[realArgIdx];
1496     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1497     bool isByVal = Flags.isByVal();
1498
1499     // Promote the value if needed.
1500     switch (VA.getLocInfo()) {
1501     default: llvm_unreachable("Unknown loc info!");
1502     case CCValAssign::Full: break;
1503     case CCValAssign::SExt:
1504       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1505       break;
1506     case CCValAssign::ZExt:
1507       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1508       break;
1509     case CCValAssign::AExt:
1510       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1511       break;
1512     case CCValAssign::BCvt:
1513       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1514       break;
1515     }
1516
1517     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1518     if (VA.needsCustom()) {
1519       if (VA.getLocVT() == MVT::v2f64) {
1520         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1521                                   DAG.getConstant(0, MVT::i32));
1522         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1523                                   DAG.getConstant(1, MVT::i32));
1524
1525         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1526                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1527
1528         VA = ArgLocs[++i]; // skip ahead to next loc
1529         if (VA.isRegLoc()) {
1530           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1531                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1532         } else {
1533           assert(VA.isMemLoc());
1534
1535           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1536                                                  dl, DAG, VA, Flags));
1537         }
1538       } else {
1539         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1540                          StackPtr, MemOpChains, Flags);
1541       }
1542     } else if (VA.isRegLoc()) {
1543       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1544         assert(VA.getLocVT() == MVT::i32 &&
1545                "unexpected calling convention register assignment");
1546         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1547                "unexpected use of 'returned'");
1548         isThisReturn = true;
1549       }
1550       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1551     } else if (isByVal) {
1552       assert(VA.isMemLoc());
1553       unsigned offset = 0;
1554
1555       // True if this byval aggregate will be split between registers
1556       // and memory.
1557       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1558       unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1559
1560       if (CurByValIdx < ByValArgsCount) {
1561
1562         unsigned RegBegin, RegEnd;
1563         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1564
1565         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1566         unsigned int i, j;
1567         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1568           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1569           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1570           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1571                                      MachinePointerInfo(),
1572                                      false, false, false, 0);
1573           MemOpChains.push_back(Load.getValue(1));
1574           RegsToPass.push_back(std::make_pair(j, Load));
1575         }
1576
1577         // If parameter size outsides register area, "offset" value
1578         // helps us to calculate stack slot for remained part properly.
1579         offset = RegEnd - RegBegin;
1580
1581         CCInfo.nextInRegsParam();
1582       }
1583
1584       if (Flags.getByValSize() > 4*offset) {
1585         unsigned LocMemOffset = VA.getLocMemOffset();
1586         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1587         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1588                                   StkPtrOff);
1589         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1590         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1591         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1592                                            MVT::i32);
1593         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1594
1595         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1596         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1597         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1598                                           Ops, array_lengthof(Ops)));
1599       }
1600     } else if (!isSibCall) {
1601       assert(VA.isMemLoc());
1602
1603       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1604                                              dl, DAG, VA, Flags));
1605     }
1606   }
1607
1608   if (!MemOpChains.empty())
1609     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1610                         &MemOpChains[0], MemOpChains.size());
1611
1612   // Build a sequence of copy-to-reg nodes chained together with token chain
1613   // and flag operands which copy the outgoing args into the appropriate regs.
1614   SDValue InFlag;
1615   // Tail call byval lowering might overwrite argument registers so in case of
1616   // tail call optimization the copies to registers are lowered later.
1617   if (!isTailCall)
1618     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1619       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1620                                RegsToPass[i].second, InFlag);
1621       InFlag = Chain.getValue(1);
1622     }
1623
1624   // For tail calls lower the arguments to the 'real' stack slot.
1625   if (isTailCall) {
1626     // Force all the incoming stack arguments to be loaded from the stack
1627     // before any new outgoing arguments are stored to the stack, because the
1628     // outgoing stack slots may alias the incoming argument stack slots, and
1629     // the alias isn't otherwise explicit. This is slightly more conservative
1630     // than necessary, because it means that each store effectively depends
1631     // on every argument instead of just those arguments it would clobber.
1632
1633     // Do not flag preceding copytoreg stuff together with the following stuff.
1634     InFlag = SDValue();
1635     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1636       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1637                                RegsToPass[i].second, InFlag);
1638       InFlag = Chain.getValue(1);
1639     }
1640     InFlag = SDValue();
1641   }
1642
1643   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1644   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1645   // node so that legalize doesn't hack it.
1646   bool isDirect = false;
1647   bool isARMFunc = false;
1648   bool isLocalARMFunc = false;
1649   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1650
1651   if (EnableARMLongCalls) {
1652     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1653             && "long-calls with non-static relocation model!");
1654     // Handle a global address or an external symbol. If it's not one of
1655     // those, the target's already in a register, so we don't need to do
1656     // anything extra.
1657     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1658       const GlobalValue *GV = G->getGlobal();
1659       // Create a constant pool entry for the callee address
1660       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1661       ARMConstantPoolValue *CPV =
1662         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1663
1664       // Get the address of the callee into a register
1665       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1666       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1667       Callee = DAG.getLoad(getPointerTy(), dl,
1668                            DAG.getEntryNode(), CPAddr,
1669                            MachinePointerInfo::getConstantPool(),
1670                            false, false, false, 0);
1671     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1672       const char *Sym = S->getSymbol();
1673
1674       // Create a constant pool entry for the callee address
1675       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1676       ARMConstantPoolValue *CPV =
1677         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1678                                       ARMPCLabelIndex, 0);
1679       // Get the address of the callee into a register
1680       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1681       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1682       Callee = DAG.getLoad(getPointerTy(), dl,
1683                            DAG.getEntryNode(), CPAddr,
1684                            MachinePointerInfo::getConstantPool(),
1685                            false, false, false, 0);
1686     }
1687   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1688     const GlobalValue *GV = G->getGlobal();
1689     isDirect = true;
1690     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1691     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1692                    getTargetMachine().getRelocationModel() != Reloc::Static;
1693     isARMFunc = !Subtarget->isThumb() || isStub;
1694     // ARM call to a local ARM function is predicable.
1695     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1696     // tBX takes a register source operand.
1697     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1698       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1699       ARMConstantPoolValue *CPV =
1700         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1701       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1702       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1703       Callee = DAG.getLoad(getPointerTy(), dl,
1704                            DAG.getEntryNode(), CPAddr,
1705                            MachinePointerInfo::getConstantPool(),
1706                            false, false, false, 0);
1707       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1708       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1709                            getPointerTy(), Callee, PICLabel);
1710     } else {
1711       // On ELF targets for PIC code, direct calls should go through the PLT
1712       unsigned OpFlags = 0;
1713       if (Subtarget->isTargetELF() &&
1714           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1715         OpFlags = ARMII::MO_PLT;
1716       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1717     }
1718   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1719     isDirect = true;
1720     bool isStub = Subtarget->isTargetDarwin() &&
1721                   getTargetMachine().getRelocationModel() != Reloc::Static;
1722     isARMFunc = !Subtarget->isThumb() || isStub;
1723     // tBX takes a register source operand.
1724     const char *Sym = S->getSymbol();
1725     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1726       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1727       ARMConstantPoolValue *CPV =
1728         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1729                                       ARMPCLabelIndex, 4);
1730       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1731       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1732       Callee = DAG.getLoad(getPointerTy(), dl,
1733                            DAG.getEntryNode(), CPAddr,
1734                            MachinePointerInfo::getConstantPool(),
1735                            false, false, false, 0);
1736       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1737       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1738                            getPointerTy(), Callee, PICLabel);
1739     } else {
1740       unsigned OpFlags = 0;
1741       // On ELF targets for PIC code, direct calls should go through the PLT
1742       if (Subtarget->isTargetELF() &&
1743                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1744         OpFlags = ARMII::MO_PLT;
1745       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1746     }
1747   }
1748
1749   // FIXME: handle tail calls differently.
1750   unsigned CallOpc;
1751   bool HasMinSizeAttr = MF.getFunction()->getAttributes().
1752     hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
1753   if (Subtarget->isThumb()) {
1754     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1755       CallOpc = ARMISD::CALL_NOLINK;
1756     else
1757       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1758   } else {
1759     if (!isDirect && !Subtarget->hasV5TOps())
1760       CallOpc = ARMISD::CALL_NOLINK;
1761     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1762                // Emit regular call when code size is the priority
1763                !HasMinSizeAttr)
1764       // "mov lr, pc; b _foo" to avoid confusing the RSP
1765       CallOpc = ARMISD::CALL_NOLINK;
1766     else
1767       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1768   }
1769
1770   std::vector<SDValue> Ops;
1771   Ops.push_back(Chain);
1772   Ops.push_back(Callee);
1773
1774   // Add argument registers to the end of the list so that they are known live
1775   // into the call.
1776   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1777     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1778                                   RegsToPass[i].second.getValueType()));
1779
1780   // Add a register mask operand representing the call-preserved registers.
1781   const uint32_t *Mask;
1782   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1783   const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1784   if (isThisReturn) {
1785     // For 'this' returns, use the R0-preserving mask if applicable
1786     Mask = ARI->getThisReturnPreservedMask(CallConv);
1787     if (!Mask) {
1788       // Set isThisReturn to false if the calling convention is not one that
1789       // allows 'returned' to be modeled in this way, so LowerCallResult does
1790       // not try to pass 'this' straight through 
1791       isThisReturn = false;
1792       Mask = ARI->getCallPreservedMask(CallConv);
1793     }
1794   } else
1795     Mask = ARI->getCallPreservedMask(CallConv);
1796
1797   assert(Mask && "Missing call preserved mask for calling convention");
1798   Ops.push_back(DAG.getRegisterMask(Mask));
1799
1800   if (InFlag.getNode())
1801     Ops.push_back(InFlag);
1802
1803   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1804   if (isTailCall)
1805     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1806
1807   // Returns a chain and a flag for retval copy to use.
1808   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1809   InFlag = Chain.getValue(1);
1810
1811   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1812                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1813   if (!Ins.empty())
1814     InFlag = Chain.getValue(1);
1815
1816   // Handle result values, copying them out of physregs into vregs that we
1817   // return.
1818   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1819                          InVals, isThisReturn,
1820                          isThisReturn ? OutVals[0] : SDValue());
1821 }
1822
1823 /// HandleByVal - Every parameter *after* a byval parameter is passed
1824 /// on the stack.  Remember the next parameter register to allocate,
1825 /// and then confiscate the rest of the parameter registers to insure
1826 /// this.
1827 void
1828 ARMTargetLowering::HandleByVal(
1829     CCState *State, unsigned &size, unsigned Align) const {
1830   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1831   assert((State->getCallOrPrologue() == Prologue ||
1832           State->getCallOrPrologue() == Call) &&
1833          "unhandled ParmContext");
1834
1835   // For in-prologue parameters handling, we also introduce stack offset
1836   // for byval registers: see CallingConvLower.cpp, CCState::HandleByVal.
1837   // This behaviour outsides AAPCS rules (5.5 Parameters Passing) of how
1838   // NSAA should be evaluted (NSAA means "next stacked argument address").
1839   // So: NextStackOffset = NSAAOffset + SizeOfByValParamsStoredInRegs.
1840   // Then: NSAAOffset = NextStackOffset - SizeOfByValParamsStoredInRegs.
1841   unsigned NSAAOffset = State->getNextStackOffset();
1842   if (State->getCallOrPrologue() != Call) {
1843     for (unsigned i = 0, e = State->getInRegsParamsCount(); i != e; ++i) {
1844       unsigned RB, RE;
1845       State->getInRegsParamInfo(i, RB, RE);
1846       assert(NSAAOffset >= (RE-RB)*4 &&
1847              "Stack offset for byval regs doesn't introduced anymore?");
1848       NSAAOffset -= (RE-RB)*4;
1849     }
1850   }
1851   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1852     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1853       unsigned AlignInRegs = Align / 4;
1854       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1855       for (unsigned i = 0; i < Waste; ++i)
1856         reg = State->AllocateReg(GPRArgRegs, 4);
1857     }
1858     if (reg != 0) {
1859       unsigned excess = 4 * (ARM::R4 - reg);
1860
1861       // Special case when NSAA != SP and parameter size greater than size of
1862       // all remained GPR regs. In that case we can't split parameter, we must
1863       // send it to stack. We also must set NCRN to R4, so waste all
1864       // remained registers.
1865       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1866         while (State->AllocateReg(GPRArgRegs, 4))
1867           ;
1868         return;
1869       }
1870
1871       // First register for byval parameter is the first register that wasn't
1872       // allocated before this method call, so it would be "reg".
1873       // If parameter is small enough to be saved in range [reg, r4), then
1874       // the end (first after last) register would be reg + param-size-in-regs,
1875       // else parameter would be splitted between registers and stack,
1876       // end register would be r4 in this case.
1877       unsigned ByValRegBegin = reg;
1878       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1879       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1880       // Note, first register is allocated in the beginning of function already,
1881       // allocate remained amount of registers we need.
1882       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1883         State->AllocateReg(GPRArgRegs, 4);
1884       // At a call site, a byval parameter that is split between
1885       // registers and memory needs its size truncated here.  In a
1886       // function prologue, such byval parameters are reassembled in
1887       // memory, and are not truncated.
1888       if (State->getCallOrPrologue() == Call) {
1889         // Make remained size equal to 0 in case, when
1890         // the whole structure may be stored into registers.
1891         if (size < excess)
1892           size = 0;
1893         else
1894           size -= excess;
1895       }
1896     }
1897   }
1898 }
1899
1900 /// MatchingStackOffset - Return true if the given stack call argument is
1901 /// already available in the same position (relatively) of the caller's
1902 /// incoming argument stack.
1903 static
1904 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1905                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1906                          const TargetInstrInfo *TII) {
1907   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1908   int FI = INT_MAX;
1909   if (Arg.getOpcode() == ISD::CopyFromReg) {
1910     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1911     if (!TargetRegisterInfo::isVirtualRegister(VR))
1912       return false;
1913     MachineInstr *Def = MRI->getVRegDef(VR);
1914     if (!Def)
1915       return false;
1916     if (!Flags.isByVal()) {
1917       if (!TII->isLoadFromStackSlot(Def, FI))
1918         return false;
1919     } else {
1920       return false;
1921     }
1922   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1923     if (Flags.isByVal())
1924       // ByVal argument is passed in as a pointer but it's now being
1925       // dereferenced. e.g.
1926       // define @foo(%struct.X* %A) {
1927       //   tail call @bar(%struct.X* byval %A)
1928       // }
1929       return false;
1930     SDValue Ptr = Ld->getBasePtr();
1931     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1932     if (!FINode)
1933       return false;
1934     FI = FINode->getIndex();
1935   } else
1936     return false;
1937
1938   assert(FI != INT_MAX);
1939   if (!MFI->isFixedObjectIndex(FI))
1940     return false;
1941   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1942 }
1943
1944 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1945 /// for tail call optimization. Targets which want to do tail call
1946 /// optimization should implement this function.
1947 bool
1948 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1949                                                      CallingConv::ID CalleeCC,
1950                                                      bool isVarArg,
1951                                                      bool isCalleeStructRet,
1952                                                      bool isCallerStructRet,
1953                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1954                                     const SmallVectorImpl<SDValue> &OutVals,
1955                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1956                                                      SelectionDAG& DAG) const {
1957   const Function *CallerF = DAG.getMachineFunction().getFunction();
1958   CallingConv::ID CallerCC = CallerF->getCallingConv();
1959   bool CCMatch = CallerCC == CalleeCC;
1960
1961   // Look for obvious safe cases to perform tail call optimization that do not
1962   // require ABI changes. This is what gcc calls sibcall.
1963
1964   // Do not sibcall optimize vararg calls unless the call site is not passing
1965   // any arguments.
1966   if (isVarArg && !Outs.empty())
1967     return false;
1968
1969   // Also avoid sibcall optimization if either caller or callee uses struct
1970   // return semantics.
1971   if (isCalleeStructRet || isCallerStructRet)
1972     return false;
1973
1974   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1975   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1976   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1977   // support in the assembler and linker to be used. This would need to be
1978   // fixed to fully support tail calls in Thumb1.
1979   //
1980   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1981   // LR.  This means if we need to reload LR, it takes an extra instructions,
1982   // which outweighs the value of the tail call; but here we don't know yet
1983   // whether LR is going to be used.  Probably the right approach is to
1984   // generate the tail call here and turn it back into CALL/RET in
1985   // emitEpilogue if LR is used.
1986
1987   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1988   // but we need to make sure there are enough registers; the only valid
1989   // registers are the 4 used for parameters.  We don't currently do this
1990   // case.
1991   if (Subtarget->isThumb1Only())
1992     return false;
1993
1994   // If the calling conventions do not match, then we'd better make sure the
1995   // results are returned in the same way as what the caller expects.
1996   if (!CCMatch) {
1997     SmallVector<CCValAssign, 16> RVLocs1;
1998     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1999                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
2000     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2001
2002     SmallVector<CCValAssign, 16> RVLocs2;
2003     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2004                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
2005     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2006
2007     if (RVLocs1.size() != RVLocs2.size())
2008       return false;
2009     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2010       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2011         return false;
2012       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2013         return false;
2014       if (RVLocs1[i].isRegLoc()) {
2015         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2016           return false;
2017       } else {
2018         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2019           return false;
2020       }
2021     }
2022   }
2023
2024   // If Caller's vararg or byval argument has been split between registers and
2025   // stack, do not perform tail call, since part of the argument is in caller's
2026   // local frame.
2027   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2028                                       getInfo<ARMFunctionInfo>();
2029   if (AFI_Caller->getArgRegsSaveSize())
2030     return false;
2031
2032   // If the callee takes no arguments then go on to check the results of the
2033   // call.
2034   if (!Outs.empty()) {
2035     // Check if stack adjustment is needed. For now, do not do this if any
2036     // argument is passed on the stack.
2037     SmallVector<CCValAssign, 16> ArgLocs;
2038     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2039                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
2040     CCInfo.AnalyzeCallOperands(Outs,
2041                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2042     if (CCInfo.getNextStackOffset()) {
2043       MachineFunction &MF = DAG.getMachineFunction();
2044
2045       // Check if the arguments are already laid out in the right way as
2046       // the caller's fixed stack objects.
2047       MachineFrameInfo *MFI = MF.getFrameInfo();
2048       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2049       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2050       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2051            i != e;
2052            ++i, ++realArgIdx) {
2053         CCValAssign &VA = ArgLocs[i];
2054         EVT RegVT = VA.getLocVT();
2055         SDValue Arg = OutVals[realArgIdx];
2056         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2057         if (VA.getLocInfo() == CCValAssign::Indirect)
2058           return false;
2059         if (VA.needsCustom()) {
2060           // f64 and vector types are split into multiple registers or
2061           // register/stack-slot combinations.  The types will not match
2062           // the registers; give up on memory f64 refs until we figure
2063           // out what to do about this.
2064           if (!VA.isRegLoc())
2065             return false;
2066           if (!ArgLocs[++i].isRegLoc())
2067             return false;
2068           if (RegVT == MVT::v2f64) {
2069             if (!ArgLocs[++i].isRegLoc())
2070               return false;
2071             if (!ArgLocs[++i].isRegLoc())
2072               return false;
2073           }
2074         } else if (!VA.isRegLoc()) {
2075           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2076                                    MFI, MRI, TII))
2077             return false;
2078         }
2079       }
2080     }
2081   }
2082
2083   return true;
2084 }
2085
2086 bool
2087 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2088                                   MachineFunction &MF, bool isVarArg,
2089                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2090                                   LLVMContext &Context) const {
2091   SmallVector<CCValAssign, 16> RVLocs;
2092   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2093   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2094                                                     isVarArg));
2095 }
2096
2097 SDValue
2098 ARMTargetLowering::LowerReturn(SDValue Chain,
2099                                CallingConv::ID CallConv, bool isVarArg,
2100                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2101                                const SmallVectorImpl<SDValue> &OutVals,
2102                                SDLoc dl, SelectionDAG &DAG) const {
2103
2104   // CCValAssign - represent the assignment of the return value to a location.
2105   SmallVector<CCValAssign, 16> RVLocs;
2106
2107   // CCState - Info about the registers and stack slots.
2108   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2109                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2110
2111   // Analyze outgoing return values.
2112   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2113                                                isVarArg));
2114
2115   SDValue Flag;
2116   SmallVector<SDValue, 4> RetOps;
2117   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2118
2119   // Copy the result values into the output registers.
2120   for (unsigned i = 0, realRVLocIdx = 0;
2121        i != RVLocs.size();
2122        ++i, ++realRVLocIdx) {
2123     CCValAssign &VA = RVLocs[i];
2124     assert(VA.isRegLoc() && "Can only return in registers!");
2125
2126     SDValue Arg = OutVals[realRVLocIdx];
2127
2128     switch (VA.getLocInfo()) {
2129     default: llvm_unreachable("Unknown loc info!");
2130     case CCValAssign::Full: break;
2131     case CCValAssign::BCvt:
2132       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2133       break;
2134     }
2135
2136     if (VA.needsCustom()) {
2137       if (VA.getLocVT() == MVT::v2f64) {
2138         // Extract the first half and return it in two registers.
2139         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2140                                    DAG.getConstant(0, MVT::i32));
2141         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2142                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2143
2144         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
2145         Flag = Chain.getValue(1);
2146         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2147         VA = RVLocs[++i]; // skip ahead to next loc
2148         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2149                                  HalfGPRs.getValue(1), Flag);
2150         Flag = Chain.getValue(1);
2151         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2152         VA = RVLocs[++i]; // skip ahead to next loc
2153
2154         // Extract the 2nd half and fall through to handle it as an f64 value.
2155         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2156                           DAG.getConstant(1, MVT::i32));
2157       }
2158       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2159       // available.
2160       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2161                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
2162       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
2163       Flag = Chain.getValue(1);
2164       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2165       VA = RVLocs[++i]; // skip ahead to next loc
2166       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
2167                                Flag);
2168     } else
2169       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2170
2171     // Guarantee that all emitted copies are
2172     // stuck together, avoiding something bad.
2173     Flag = Chain.getValue(1);
2174     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2175   }
2176
2177   // Update chain and glue.
2178   RetOps[0] = Chain;
2179   if (Flag.getNode())
2180     RetOps.push_back(Flag);
2181
2182   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
2183                      RetOps.data(), RetOps.size());
2184 }
2185
2186 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2187   if (N->getNumValues() != 1)
2188     return false;
2189   if (!N->hasNUsesOfValue(1, 0))
2190     return false;
2191
2192   SDValue TCChain = Chain;
2193   SDNode *Copy = *N->use_begin();
2194   if (Copy->getOpcode() == ISD::CopyToReg) {
2195     // If the copy has a glue operand, we conservatively assume it isn't safe to
2196     // perform a tail call.
2197     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2198       return false;
2199     TCChain = Copy->getOperand(0);
2200   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2201     SDNode *VMov = Copy;
2202     // f64 returned in a pair of GPRs.
2203     SmallPtrSet<SDNode*, 2> Copies;
2204     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2205          UI != UE; ++UI) {
2206       if (UI->getOpcode() != ISD::CopyToReg)
2207         return false;
2208       Copies.insert(*UI);
2209     }
2210     if (Copies.size() > 2)
2211       return false;
2212
2213     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2214          UI != UE; ++UI) {
2215       SDValue UseChain = UI->getOperand(0);
2216       if (Copies.count(UseChain.getNode()))
2217         // Second CopyToReg
2218         Copy = *UI;
2219       else
2220         // First CopyToReg
2221         TCChain = UseChain;
2222     }
2223   } else if (Copy->getOpcode() == ISD::BITCAST) {
2224     // f32 returned in a single GPR.
2225     if (!Copy->hasOneUse())
2226       return false;
2227     Copy = *Copy->use_begin();
2228     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2229       return false;
2230     TCChain = Copy->getOperand(0);
2231   } else {
2232     return false;
2233   }
2234
2235   bool HasRet = false;
2236   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2237        UI != UE; ++UI) {
2238     if (UI->getOpcode() != ARMISD::RET_FLAG)
2239       return false;
2240     HasRet = true;
2241   }
2242
2243   if (!HasRet)
2244     return false;
2245
2246   Chain = TCChain;
2247   return true;
2248 }
2249
2250 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2251   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2252     return false;
2253
2254   if (!CI->isTailCall())
2255     return false;
2256
2257   return !Subtarget->isThumb1Only();
2258 }
2259
2260 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2261 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2262 // one of the above mentioned nodes. It has to be wrapped because otherwise
2263 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2264 // be used to form addressing mode. These wrapped nodes will be selected
2265 // into MOVi.
2266 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2267   EVT PtrVT = Op.getValueType();
2268   // FIXME there is no actual debug info here
2269   SDLoc dl(Op);
2270   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2271   SDValue Res;
2272   if (CP->isMachineConstantPoolEntry())
2273     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2274                                     CP->getAlignment());
2275   else
2276     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2277                                     CP->getAlignment());
2278   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2279 }
2280
2281 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2282   return MachineJumpTableInfo::EK_Inline;
2283 }
2284
2285 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2286                                              SelectionDAG &DAG) const {
2287   MachineFunction &MF = DAG.getMachineFunction();
2288   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2289   unsigned ARMPCLabelIndex = 0;
2290   SDLoc DL(Op);
2291   EVT PtrVT = getPointerTy();
2292   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2293   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2294   SDValue CPAddr;
2295   if (RelocM == Reloc::Static) {
2296     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2297   } else {
2298     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2299     ARMPCLabelIndex = AFI->createPICLabelUId();
2300     ARMConstantPoolValue *CPV =
2301       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2302                                       ARMCP::CPBlockAddress, PCAdj);
2303     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2304   }
2305   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2306   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2307                                MachinePointerInfo::getConstantPool(),
2308                                false, false, false, 0);
2309   if (RelocM == Reloc::Static)
2310     return Result;
2311   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2312   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2313 }
2314
2315 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2316 SDValue
2317 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2318                                                  SelectionDAG &DAG) const {
2319   SDLoc dl(GA);
2320   EVT PtrVT = getPointerTy();
2321   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2322   MachineFunction &MF = DAG.getMachineFunction();
2323   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2324   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2325   ARMConstantPoolValue *CPV =
2326     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2327                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2328   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2329   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2330   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2331                          MachinePointerInfo::getConstantPool(),
2332                          false, false, false, 0);
2333   SDValue Chain = Argument.getValue(1);
2334
2335   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2336   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2337
2338   // call __tls_get_addr.
2339   ArgListTy Args;
2340   ArgListEntry Entry;
2341   Entry.Node = Argument;
2342   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2343   Args.push_back(Entry);
2344   // FIXME: is there useful debug info available here?
2345   TargetLowering::CallLoweringInfo CLI(Chain,
2346                 (Type *) Type::getInt32Ty(*DAG.getContext()),
2347                 false, false, false, false,
2348                 0, CallingConv::C, /*isTailCall=*/false,
2349                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2350                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2351   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2352   return CallResult.first;
2353 }
2354
2355 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2356 // "local exec" model.
2357 SDValue
2358 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2359                                         SelectionDAG &DAG,
2360                                         TLSModel::Model model) const {
2361   const GlobalValue *GV = GA->getGlobal();
2362   SDLoc dl(GA);
2363   SDValue Offset;
2364   SDValue Chain = DAG.getEntryNode();
2365   EVT PtrVT = getPointerTy();
2366   // Get the Thread Pointer
2367   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2368
2369   if (model == TLSModel::InitialExec) {
2370     MachineFunction &MF = DAG.getMachineFunction();
2371     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2372     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2373     // Initial exec model.
2374     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2375     ARMConstantPoolValue *CPV =
2376       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2377                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2378                                       true);
2379     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2380     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2381     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2382                          MachinePointerInfo::getConstantPool(),
2383                          false, false, false, 0);
2384     Chain = Offset.getValue(1);
2385
2386     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2387     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2388
2389     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2390                          MachinePointerInfo::getConstantPool(),
2391                          false, false, false, 0);
2392   } else {
2393     // local exec model
2394     assert(model == TLSModel::LocalExec);
2395     ARMConstantPoolValue *CPV =
2396       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2397     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2398     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2399     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2400                          MachinePointerInfo::getConstantPool(),
2401                          false, false, false, 0);
2402   }
2403
2404   // The address of the thread local variable is the add of the thread
2405   // pointer with the offset of the variable.
2406   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2407 }
2408
2409 SDValue
2410 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2411   // TODO: implement the "local dynamic" model
2412   assert(Subtarget->isTargetELF() &&
2413          "TLS not implemented for non-ELF targets");
2414   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2415
2416   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2417
2418   switch (model) {
2419     case TLSModel::GeneralDynamic:
2420     case TLSModel::LocalDynamic:
2421       return LowerToTLSGeneralDynamicModel(GA, DAG);
2422     case TLSModel::InitialExec:
2423     case TLSModel::LocalExec:
2424       return LowerToTLSExecModels(GA, DAG, model);
2425   }
2426   llvm_unreachable("bogus TLS model");
2427 }
2428
2429 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2430                                                  SelectionDAG &DAG) const {
2431   EVT PtrVT = getPointerTy();
2432   SDLoc dl(Op);
2433   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2434   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2435     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2436     ARMConstantPoolValue *CPV =
2437       ARMConstantPoolConstant::Create(GV,
2438                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2439     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2440     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2441     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2442                                  CPAddr,
2443                                  MachinePointerInfo::getConstantPool(),
2444                                  false, false, false, 0);
2445     SDValue Chain = Result.getValue(1);
2446     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2447     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2448     if (!UseGOTOFF)
2449       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2450                            MachinePointerInfo::getGOT(),
2451                            false, false, false, 0);
2452     return Result;
2453   }
2454
2455   // If we have T2 ops, we can materialize the address directly via movt/movw
2456   // pair. This is always cheaper.
2457   if (Subtarget->useMovt()) {
2458     ++NumMovwMovt;
2459     // FIXME: Once remat is capable of dealing with instructions with register
2460     // operands, expand this into two nodes.
2461     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2462                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2463   } else {
2464     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2465     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2466     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2467                        MachinePointerInfo::getConstantPool(),
2468                        false, false, false, 0);
2469   }
2470 }
2471
2472 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2473                                                     SelectionDAG &DAG) const {
2474   EVT PtrVT = getPointerTy();
2475   SDLoc dl(Op);
2476   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2477   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2478
2479   // FIXME: Enable this for static codegen when tool issues are fixed.  Also
2480   // update ARMFastISel::ARMMaterializeGV.
2481   if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2482     ++NumMovwMovt;
2483     // FIXME: Once remat is capable of dealing with instructions with register
2484     // operands, expand this into two nodes.
2485     if (RelocM == Reloc::Static)
2486       return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2487                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2488
2489     unsigned Wrapper = (RelocM == Reloc::PIC_)
2490       ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2491     SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2492                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2493     if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2494       Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2495                            MachinePointerInfo::getGOT(),
2496                            false, false, false, 0);
2497     return Result;
2498   }
2499
2500   unsigned ARMPCLabelIndex = 0;
2501   SDValue CPAddr;
2502   if (RelocM == Reloc::Static) {
2503     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2504   } else {
2505     ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2506     ARMPCLabelIndex = AFI->createPICLabelUId();
2507     unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2508     ARMConstantPoolValue *CPV =
2509       ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2510                                       PCAdj);
2511     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2512   }
2513   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2514
2515   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2516                                MachinePointerInfo::getConstantPool(),
2517                                false, false, false, 0);
2518   SDValue Chain = Result.getValue(1);
2519
2520   if (RelocM == Reloc::PIC_) {
2521     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2522     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2523   }
2524
2525   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2526     Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2527                          false, false, false, 0);
2528
2529   return Result;
2530 }
2531
2532 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2533                                                     SelectionDAG &DAG) const {
2534   assert(Subtarget->isTargetELF() &&
2535          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2536   MachineFunction &MF = DAG.getMachineFunction();
2537   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2538   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2539   EVT PtrVT = getPointerTy();
2540   SDLoc dl(Op);
2541   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2542   ARMConstantPoolValue *CPV =
2543     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2544                                   ARMPCLabelIndex, PCAdj);
2545   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2546   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2547   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2548                                MachinePointerInfo::getConstantPool(),
2549                                false, false, false, 0);
2550   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2551   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2552 }
2553
2554 SDValue
2555 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2556   SDLoc dl(Op);
2557   SDValue Val = DAG.getConstant(0, MVT::i32);
2558   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2559                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2560                      Op.getOperand(1), Val);
2561 }
2562
2563 SDValue
2564 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2565   SDLoc dl(Op);
2566   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2567                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2568 }
2569
2570 SDValue
2571 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2572                                           const ARMSubtarget *Subtarget) const {
2573   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2574   SDLoc dl(Op);
2575   switch (IntNo) {
2576   default: return SDValue();    // Don't custom lower most intrinsics.
2577   case Intrinsic::arm_thread_pointer: {
2578     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2579     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2580   }
2581   case Intrinsic::eh_sjlj_lsda: {
2582     MachineFunction &MF = DAG.getMachineFunction();
2583     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2584     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2585     EVT PtrVT = getPointerTy();
2586     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2587     SDValue CPAddr;
2588     unsigned PCAdj = (RelocM != Reloc::PIC_)
2589       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2590     ARMConstantPoolValue *CPV =
2591       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2592                                       ARMCP::CPLSDA, PCAdj);
2593     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2594     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2595     SDValue Result =
2596       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2597                   MachinePointerInfo::getConstantPool(),
2598                   false, false, false, 0);
2599
2600     if (RelocM == Reloc::PIC_) {
2601       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2602       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2603     }
2604     return Result;
2605   }
2606   case Intrinsic::arm_neon_vmulls:
2607   case Intrinsic::arm_neon_vmullu: {
2608     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2609       ? ARMISD::VMULLs : ARMISD::VMULLu;
2610     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2611                        Op.getOperand(1), Op.getOperand(2));
2612   }
2613   }
2614 }
2615
2616 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2617                                  const ARMSubtarget *Subtarget) {
2618   // FIXME: handle "fence singlethread" more efficiently.
2619   SDLoc dl(Op);
2620   if (!Subtarget->hasDataBarrier()) {
2621     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2622     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2623     // here.
2624     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2625            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2626     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2627                        DAG.getConstant(0, MVT::i32));
2628   }
2629
2630   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2631   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2632   unsigned Domain = ARM_MB::ISH;
2633   if (Subtarget->isMClass()) {
2634     // Only a full system barrier exists in the M-class architectures.
2635     Domain = ARM_MB::SY;
2636   } else if (Subtarget->isSwift() && Ord == Release) {
2637     // Swift happens to implement ISHST barriers in a way that's compatible with
2638     // Release semantics but weaker than ISH so we'd be fools not to use
2639     // it. Beware: other processors probably don't!
2640     Domain = ARM_MB::ISHST;
2641   }
2642
2643   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2644                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2645                      DAG.getConstant(Domain, MVT::i32));
2646 }
2647
2648 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2649                              const ARMSubtarget *Subtarget) {
2650   // ARM pre v5TE and Thumb1 does not have preload instructions.
2651   if (!(Subtarget->isThumb2() ||
2652         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2653     // Just preserve the chain.
2654     return Op.getOperand(0);
2655
2656   SDLoc dl(Op);
2657   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2658   if (!isRead &&
2659       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2660     // ARMv7 with MP extension has PLDW.
2661     return Op.getOperand(0);
2662
2663   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2664   if (Subtarget->isThumb()) {
2665     // Invert the bits.
2666     isRead = ~isRead & 1;
2667     isData = ~isData & 1;
2668   }
2669
2670   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2671                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2672                      DAG.getConstant(isData, MVT::i32));
2673 }
2674
2675 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2676   MachineFunction &MF = DAG.getMachineFunction();
2677   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2678
2679   // vastart just stores the address of the VarArgsFrameIndex slot into the
2680   // memory location argument.
2681   SDLoc dl(Op);
2682   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2683   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2684   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2685   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2686                       MachinePointerInfo(SV), false, false, 0);
2687 }
2688
2689 SDValue
2690 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2691                                         SDValue &Root, SelectionDAG &DAG,
2692                                         SDLoc dl) const {
2693   MachineFunction &MF = DAG.getMachineFunction();
2694   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2695
2696   const TargetRegisterClass *RC;
2697   if (AFI->isThumb1OnlyFunction())
2698     RC = &ARM::tGPRRegClass;
2699   else
2700     RC = &ARM::GPRRegClass;
2701
2702   // Transform the arguments stored in physical registers into virtual ones.
2703   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2704   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2705
2706   SDValue ArgValue2;
2707   if (NextVA.isMemLoc()) {
2708     MachineFrameInfo *MFI = MF.getFrameInfo();
2709     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2710
2711     // Create load node to retrieve arguments from the stack.
2712     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2713     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2714                             MachinePointerInfo::getFixedStack(FI),
2715                             false, false, false, 0);
2716   } else {
2717     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2718     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2719   }
2720
2721   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2722 }
2723
2724 void
2725 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2726                                   unsigned InRegsParamRecordIdx,
2727                                   unsigned ArgSize,
2728                                   unsigned &ArgRegsSize,
2729                                   unsigned &ArgRegsSaveSize)
2730   const {
2731   unsigned NumGPRs;
2732   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2733     unsigned RBegin, REnd;
2734     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2735     NumGPRs = REnd - RBegin;
2736   } else {
2737     unsigned int firstUnalloced;
2738     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2739                                                 sizeof(GPRArgRegs) /
2740                                                 sizeof(GPRArgRegs[0]));
2741     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2742   }
2743
2744   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2745   ArgRegsSize = NumGPRs * 4;
2746
2747   // If parameter is split between stack and GPRs...
2748   if (NumGPRs && Align == 8 &&
2749       (ArgRegsSize < ArgSize ||
2750         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2751     // Add padding for part of param recovered from GPRs, so
2752     // its last byte must be at address K*8 - 1.
2753     // We need to do it, since remained (stack) part of parameter has
2754     // stack alignment, and we need to "attach" "GPRs head" without gaps
2755     // to it:
2756     // Stack:
2757     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2758     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2759     //
2760     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2761     unsigned Padding =
2762         ((ArgRegsSize + AFI->getArgRegsSaveSize() + Align - 1) & ~(Align-1)) -
2763         (ArgRegsSize + AFI->getArgRegsSaveSize());
2764     ArgRegsSaveSize = ArgRegsSize + Padding;
2765   } else
2766     // We don't need to extend regs save size for byval parameters if they
2767     // are passed via GPRs only.
2768     ArgRegsSaveSize = ArgRegsSize;
2769 }
2770
2771 // The remaining GPRs hold either the beginning of variable-argument
2772 // data, or the beginning of an aggregate passed by value (usually
2773 // byval).  Either way, we allocate stack slots adjacent to the data
2774 // provided by our caller, and store the unallocated registers there.
2775 // If this is a variadic function, the va_list pointer will begin with
2776 // these values; otherwise, this reassembles a (byval) structure that
2777 // was split between registers and memory.
2778 // Return: The frame index registers were stored into.
2779 int
2780 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2781                                   SDLoc dl, SDValue &Chain,
2782                                   const Value *OrigArg,
2783                                   unsigned InRegsParamRecordIdx,
2784                                   unsigned OffsetFromOrigArg,
2785                                   unsigned ArgOffset,
2786                                   unsigned ArgSize,
2787                                   bool ForceMutable) const {
2788
2789   // Currently, two use-cases possible:
2790   // Case #1. Non var-args function, and we meet first byval parameter.
2791   //          Setup first unallocated register as first byval register;
2792   //          eat all remained registers
2793   //          (these two actions are performed by HandleByVal method).
2794   //          Then, here, we initialize stack frame with
2795   //          "store-reg" instructions.
2796   // Case #2. Var-args function, that doesn't contain byval parameters.
2797   //          The same: eat all remained unallocated registers,
2798   //          initialize stack frame.
2799
2800   MachineFunction &MF = DAG.getMachineFunction();
2801   MachineFrameInfo *MFI = MF.getFrameInfo();
2802   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2803   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2804   unsigned RBegin, REnd;
2805   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2806     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2807     firstRegToSaveIndex = RBegin - ARM::R0;
2808     lastRegToSaveIndex = REnd - ARM::R0;
2809   } else {
2810     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2811       (GPRArgRegs, array_lengthof(GPRArgRegs));
2812     lastRegToSaveIndex = 4;
2813   }
2814
2815   unsigned ArgRegsSize, ArgRegsSaveSize;
2816   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2817                  ArgRegsSize, ArgRegsSaveSize);
2818
2819   // Store any by-val regs to their spots on the stack so that they may be
2820   // loaded by deferencing the result of formal parameter pointer or va_next.
2821   // Note: once stack area for byval/varargs registers
2822   // was initialized, it can't be initialized again.
2823   if (ArgRegsSaveSize) {
2824
2825     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2826
2827     if (Padding) {
2828       assert(AFI->getStoredByValParamsPadding() == 0 &&
2829              "The only parameter may be padded.");
2830       AFI->setStoredByValParamsPadding(Padding);
2831     }
2832
2833     int FrameIndex = MFI->CreateFixedObject(
2834                       ArgRegsSaveSize,
2835                       Padding + ArgOffset,
2836                       false);
2837     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2838
2839     SmallVector<SDValue, 4> MemOps;
2840     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2841          ++firstRegToSaveIndex, ++i) {
2842       const TargetRegisterClass *RC;
2843       if (AFI->isThumb1OnlyFunction())
2844         RC = &ARM::tGPRRegClass;
2845       else
2846         RC = &ARM::GPRRegClass;
2847
2848       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2849       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2850       SDValue Store =
2851         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2852                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2853                      false, false, 0);
2854       MemOps.push_back(Store);
2855       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2856                         DAG.getConstant(4, getPointerTy()));
2857     }
2858
2859     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2860
2861     if (!MemOps.empty())
2862       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2863                           &MemOps[0], MemOps.size());
2864     return FrameIndex;
2865   } else
2866     // This will point to the next argument passed via stack.
2867     return MFI->CreateFixedObject(
2868         4, AFI->getStoredByValParamsPadding() + ArgOffset, !ForceMutable);
2869 }
2870
2871 // Setup stack frame, the va_list pointer will start from.
2872 void
2873 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2874                                         SDLoc dl, SDValue &Chain,
2875                                         unsigned ArgOffset,
2876                                         bool ForceMutable) const {
2877   MachineFunction &MF = DAG.getMachineFunction();
2878   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2879
2880   // Try to store any remaining integer argument regs
2881   // to their spots on the stack so that they may be loaded by deferencing
2882   // the result of va_next.
2883   // If there is no regs to be stored, just point address after last
2884   // argument passed via stack.
2885   int FrameIndex =
2886     StoreByValRegs(CCInfo, DAG, dl, Chain, 0, CCInfo.getInRegsParamsCount(),
2887                    0, ArgOffset, 0, ForceMutable);
2888
2889   AFI->setVarArgsFrameIndex(FrameIndex);
2890 }
2891
2892 SDValue
2893 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2894                                         CallingConv::ID CallConv, bool isVarArg,
2895                                         const SmallVectorImpl<ISD::InputArg>
2896                                           &Ins,
2897                                         SDLoc dl, SelectionDAG &DAG,
2898                                         SmallVectorImpl<SDValue> &InVals)
2899                                           const {
2900   MachineFunction &MF = DAG.getMachineFunction();
2901   MachineFrameInfo *MFI = MF.getFrameInfo();
2902
2903   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2904
2905   // Assign locations to all of the incoming arguments.
2906   SmallVector<CCValAssign, 16> ArgLocs;
2907   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2908                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2909   CCInfo.AnalyzeFormalArguments(Ins,
2910                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2911                                                   isVarArg));
2912
2913   SmallVector<SDValue, 16> ArgValues;
2914   int lastInsIndex = -1;
2915   SDValue ArgValue;
2916   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2917   unsigned CurArgIdx = 0;
2918
2919   // Initially ArgRegsSaveSize is zero.
2920   // Then we increase this value each time we meet byval parameter.
2921   // We also increase this value in case of varargs function.
2922   AFI->setArgRegsSaveSize(0);
2923
2924   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2925     CCValAssign &VA = ArgLocs[i];
2926     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2927     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2928     // Arguments stored in registers.
2929     if (VA.isRegLoc()) {
2930       EVT RegVT = VA.getLocVT();
2931
2932       if (VA.needsCustom()) {
2933         // f64 and vector types are split up into multiple registers or
2934         // combinations of registers and stack slots.
2935         if (VA.getLocVT() == MVT::v2f64) {
2936           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2937                                                    Chain, DAG, dl);
2938           VA = ArgLocs[++i]; // skip ahead to next loc
2939           SDValue ArgValue2;
2940           if (VA.isMemLoc()) {
2941             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2942             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2943             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2944                                     MachinePointerInfo::getFixedStack(FI),
2945                                     false, false, false, 0);
2946           } else {
2947             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2948                                              Chain, DAG, dl);
2949           }
2950           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2951           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2952                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2953           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2954                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2955         } else
2956           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2957
2958       } else {
2959         const TargetRegisterClass *RC;
2960
2961         if (RegVT == MVT::f32)
2962           RC = &ARM::SPRRegClass;
2963         else if (RegVT == MVT::f64)
2964           RC = &ARM::DPRRegClass;
2965         else if (RegVT == MVT::v2f64)
2966           RC = &ARM::QPRRegClass;
2967         else if (RegVT == MVT::i32)
2968           RC = AFI->isThumb1OnlyFunction() ?
2969             (const TargetRegisterClass*)&ARM::tGPRRegClass :
2970             (const TargetRegisterClass*)&ARM::GPRRegClass;
2971         else
2972           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2973
2974         // Transform the arguments in physical registers into virtual ones.
2975         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2976         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2977       }
2978
2979       // If this is an 8 or 16-bit value, it is really passed promoted
2980       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2981       // truncate to the right size.
2982       switch (VA.getLocInfo()) {
2983       default: llvm_unreachable("Unknown loc info!");
2984       case CCValAssign::Full: break;
2985       case CCValAssign::BCvt:
2986         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2987         break;
2988       case CCValAssign::SExt:
2989         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2990                                DAG.getValueType(VA.getValVT()));
2991         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2992         break;
2993       case CCValAssign::ZExt:
2994         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2995                                DAG.getValueType(VA.getValVT()));
2996         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2997         break;
2998       }
2999
3000       InVals.push_back(ArgValue);
3001
3002     } else { // VA.isRegLoc()
3003
3004       // sanity check
3005       assert(VA.isMemLoc());
3006       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3007
3008       int index = ArgLocs[i].getValNo();
3009
3010       // Some Ins[] entries become multiple ArgLoc[] entries.
3011       // Process them only once.
3012       if (index != lastInsIndex)
3013         {
3014           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3015           // FIXME: For now, all byval parameter objects are marked mutable.
3016           // This can be changed with more analysis.
3017           // In case of tail call optimization mark all arguments mutable.
3018           // Since they could be overwritten by lowering of arguments in case of
3019           // a tail call.
3020           if (Flags.isByVal()) {
3021             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3022             int FrameIndex = StoreByValRegs(
3023                 CCInfo, DAG, dl, Chain, CurOrigArg,
3024                 CurByValIndex,
3025                 Ins[VA.getValNo()].PartOffset,
3026                 VA.getLocMemOffset(),
3027                 Flags.getByValSize(),
3028                 true /*force mutable frames*/);
3029             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3030             CCInfo.nextInRegsParam();
3031           } else {
3032             unsigned FIOffset = VA.getLocMemOffset() +
3033                                 AFI->getStoredByValParamsPadding();
3034             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3035                                             FIOffset, true);
3036
3037             // Create load nodes to retrieve arguments from the stack.
3038             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3039             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3040                                          MachinePointerInfo::getFixedStack(FI),
3041                                          false, false, false, 0));
3042           }
3043           lastInsIndex = index;
3044         }
3045     }
3046   }
3047
3048   // varargs
3049   if (isVarArg)
3050     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3051                          CCInfo.getNextStackOffset());
3052
3053   return Chain;
3054 }
3055
3056 /// isFloatingPointZero - Return true if this is +0.0.
3057 static bool isFloatingPointZero(SDValue Op) {
3058   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3059     return CFP->getValueAPF().isPosZero();
3060   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3061     // Maybe this has already been legalized into the constant pool?
3062     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3063       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3064       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3065         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3066           return CFP->getValueAPF().isPosZero();
3067     }
3068   }
3069   return false;
3070 }
3071
3072 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3073 /// the given operands.
3074 SDValue
3075 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3076                              SDValue &ARMcc, SelectionDAG &DAG,
3077                              SDLoc dl) const {
3078   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3079     unsigned C = RHSC->getZExtValue();
3080     if (!isLegalICmpImmediate(C)) {
3081       // Constant does not fit, try adjusting it by one?
3082       switch (CC) {
3083       default: break;
3084       case ISD::SETLT:
3085       case ISD::SETGE:
3086         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3087           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3088           RHS = DAG.getConstant(C-1, MVT::i32);
3089         }
3090         break;
3091       case ISD::SETULT:
3092       case ISD::SETUGE:
3093         if (C != 0 && isLegalICmpImmediate(C-1)) {
3094           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3095           RHS = DAG.getConstant(C-1, MVT::i32);
3096         }
3097         break;
3098       case ISD::SETLE:
3099       case ISD::SETGT:
3100         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3101           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3102           RHS = DAG.getConstant(C+1, MVT::i32);
3103         }
3104         break;
3105       case ISD::SETULE:
3106       case ISD::SETUGT:
3107         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3108           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3109           RHS = DAG.getConstant(C+1, MVT::i32);
3110         }
3111         break;
3112       }
3113     }
3114   }
3115
3116   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3117   ARMISD::NodeType CompareType;
3118   switch (CondCode) {
3119   default:
3120     CompareType = ARMISD::CMP;
3121     break;
3122   case ARMCC::EQ:
3123   case ARMCC::NE:
3124     // Uses only Z Flag
3125     CompareType = ARMISD::CMPZ;
3126     break;
3127   }
3128   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3129   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3130 }
3131
3132 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3133 SDValue
3134 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3135                              SDLoc dl) const {
3136   SDValue Cmp;
3137   if (!isFloatingPointZero(RHS))
3138     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3139   else
3140     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3141   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3142 }
3143
3144 /// duplicateCmp - Glue values can have only one use, so this function
3145 /// duplicates a comparison node.
3146 SDValue
3147 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3148   unsigned Opc = Cmp.getOpcode();
3149   SDLoc DL(Cmp);
3150   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3151     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3152
3153   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3154   Cmp = Cmp.getOperand(0);
3155   Opc = Cmp.getOpcode();
3156   if (Opc == ARMISD::CMPFP)
3157     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3158   else {
3159     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3160     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3161   }
3162   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3163 }
3164
3165 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3166   SDValue Cond = Op.getOperand(0);
3167   SDValue SelectTrue = Op.getOperand(1);
3168   SDValue SelectFalse = Op.getOperand(2);
3169   SDLoc dl(Op);
3170
3171   // Convert:
3172   //
3173   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3174   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3175   //
3176   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3177     const ConstantSDNode *CMOVTrue =
3178       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3179     const ConstantSDNode *CMOVFalse =
3180       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3181
3182     if (CMOVTrue && CMOVFalse) {
3183       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3184       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3185
3186       SDValue True;
3187       SDValue False;
3188       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3189         True = SelectTrue;
3190         False = SelectFalse;
3191       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3192         True = SelectFalse;
3193         False = SelectTrue;
3194       }
3195
3196       if (True.getNode() && False.getNode()) {
3197         EVT VT = Op.getValueType();
3198         SDValue ARMcc = Cond.getOperand(2);
3199         SDValue CCR = Cond.getOperand(3);
3200         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3201         assert(True.getValueType() == VT);
3202         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3203       }
3204     }
3205   }
3206
3207   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3208   // undefined bits before doing a full-word comparison with zero.
3209   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3210                      DAG.getConstant(1, Cond.getValueType()));
3211
3212   return DAG.getSelectCC(dl, Cond,
3213                          DAG.getConstant(0, Cond.getValueType()),
3214                          SelectTrue, SelectFalse, ISD::SETNE);
3215 }
3216
3217 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3218   if (CC == ISD::SETNE)
3219     return ISD::SETEQ;
3220   return ISD::getSetCCSwappedOperands(CC);
3221 }
3222
3223 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3224                                  bool &swpCmpOps, bool &swpVselOps) {
3225   // Start by selecting the GE condition code for opcodes that return true for
3226   // 'equality'
3227   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3228       CC == ISD::SETULE)
3229     CondCode = ARMCC::GE;
3230
3231   // and GT for opcodes that return false for 'equality'.
3232   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3233            CC == ISD::SETULT)
3234     CondCode = ARMCC::GT;
3235
3236   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3237   // to swap the compare operands.
3238   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3239       CC == ISD::SETULT)
3240     swpCmpOps = true;
3241
3242   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3243   // If we have an unordered opcode, we need to swap the operands to the VSEL
3244   // instruction (effectively negating the condition).
3245   //
3246   // This also has the effect of swapping which one of 'less' or 'greater'
3247   // returns true, so we also swap the compare operands. It also switches
3248   // whether we return true for 'equality', so we compensate by picking the
3249   // opposite condition code to our original choice.
3250   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3251       CC == ISD::SETUGT) {
3252     swpCmpOps = !swpCmpOps;
3253     swpVselOps = !swpVselOps;
3254     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3255   }
3256
3257   // 'ordered' is 'anything but unordered', so use the VS condition code and
3258   // swap the VSEL operands.
3259   if (CC == ISD::SETO) {
3260     CondCode = ARMCC::VS;
3261     swpVselOps = true;
3262   }
3263
3264   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3265   // code and swap the VSEL operands.
3266   if (CC == ISD::SETUNE) {
3267     CondCode = ARMCC::EQ;
3268     swpVselOps = true;
3269   }
3270 }
3271
3272 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3273   EVT VT = Op.getValueType();
3274   SDValue LHS = Op.getOperand(0);
3275   SDValue RHS = Op.getOperand(1);
3276   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3277   SDValue TrueVal = Op.getOperand(2);
3278   SDValue FalseVal = Op.getOperand(3);
3279   SDLoc dl(Op);
3280
3281   if (LHS.getValueType() == MVT::i32) {
3282     // Try to generate VSEL on ARMv8.
3283     // The VSEL instruction can't use all the usual ARM condition
3284     // codes: it only has two bits to select the condition code, so it's
3285     // constrained to use only GE, GT, VS and EQ.
3286     //
3287     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3288     // swap the operands of the previous compare instruction (effectively
3289     // inverting the compare condition, swapping 'less' and 'greater') and
3290     // sometimes need to swap the operands to the VSEL (which inverts the
3291     // condition in the sense of firing whenever the previous condition didn't)
3292     if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3293                                       TrueVal.getValueType() == MVT::f64)) {
3294       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3295       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3296           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3297         CC = getInverseCCForVSEL(CC);
3298         std::swap(TrueVal, FalseVal);
3299       }
3300     }
3301
3302     SDValue ARMcc;
3303     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3304     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3305     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3306                        Cmp);
3307   }
3308
3309   ARMCC::CondCodes CondCode, CondCode2;
3310   FPCCToARMCC(CC, CondCode, CondCode2);
3311
3312   // Try to generate VSEL on ARMv8.
3313   if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3314                                     TrueVal.getValueType() == MVT::f64)) {
3315     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3316     // same operands, as follows:
3317     //   c = fcmp [ogt, olt, ugt, ult] a, b
3318     //   select c, a, b
3319     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3320     // handled differently than the original code sequence.
3321     if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3322         RHS == FalseVal) {
3323       if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3324         return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3325       if (CC == ISD::SETOLT || CC == ISD::SETULT)
3326         return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3327     }
3328
3329     bool swpCmpOps = false;
3330     bool swpVselOps = false;
3331     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3332
3333     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3334         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3335       if (swpCmpOps)
3336         std::swap(LHS, RHS);
3337       if (swpVselOps)
3338         std::swap(TrueVal, FalseVal);
3339     }
3340   }
3341
3342   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3343   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3344   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3345   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3346                                ARMcc, CCR, Cmp);
3347   if (CondCode2 != ARMCC::AL) {
3348     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3349     // FIXME: Needs another CMP because flag can have but one use.
3350     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3351     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3352                          Result, TrueVal, ARMcc2, CCR, Cmp2);
3353   }
3354   return Result;
3355 }
3356
3357 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3358 /// to morph to an integer compare sequence.
3359 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3360                            const ARMSubtarget *Subtarget) {
3361   SDNode *N = Op.getNode();
3362   if (!N->hasOneUse())
3363     // Otherwise it requires moving the value from fp to integer registers.
3364     return false;
3365   if (!N->getNumValues())
3366     return false;
3367   EVT VT = Op.getValueType();
3368   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3369     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3370     // vmrs are very slow, e.g. cortex-a8.
3371     return false;
3372
3373   if (isFloatingPointZero(Op)) {
3374     SeenZero = true;
3375     return true;
3376   }
3377   return ISD::isNormalLoad(N);
3378 }
3379
3380 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3381   if (isFloatingPointZero(Op))
3382     return DAG.getConstant(0, MVT::i32);
3383
3384   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3385     return DAG.getLoad(MVT::i32, SDLoc(Op),
3386                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3387                        Ld->isVolatile(), Ld->isNonTemporal(),
3388                        Ld->isInvariant(), Ld->getAlignment());
3389
3390   llvm_unreachable("Unknown VFP cmp argument!");
3391 }
3392
3393 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3394                            SDValue &RetVal1, SDValue &RetVal2) {
3395   if (isFloatingPointZero(Op)) {
3396     RetVal1 = DAG.getConstant(0, MVT::i32);
3397     RetVal2 = DAG.getConstant(0, MVT::i32);
3398     return;
3399   }
3400
3401   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3402     SDValue Ptr = Ld->getBasePtr();
3403     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3404                           Ld->getChain(), Ptr,
3405                           Ld->getPointerInfo(),
3406                           Ld->isVolatile(), Ld->isNonTemporal(),
3407                           Ld->isInvariant(), Ld->getAlignment());
3408
3409     EVT PtrType = Ptr.getValueType();
3410     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3411     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3412                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3413     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3414                           Ld->getChain(), NewPtr,
3415                           Ld->getPointerInfo().getWithOffset(4),
3416                           Ld->isVolatile(), Ld->isNonTemporal(),
3417                           Ld->isInvariant(), NewAlign);
3418     return;
3419   }
3420
3421   llvm_unreachable("Unknown VFP cmp argument!");
3422 }
3423
3424 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3425 /// f32 and even f64 comparisons to integer ones.
3426 SDValue
3427 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3428   SDValue Chain = Op.getOperand(0);
3429   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3430   SDValue LHS = Op.getOperand(2);
3431   SDValue RHS = Op.getOperand(3);
3432   SDValue Dest = Op.getOperand(4);
3433   SDLoc dl(Op);
3434
3435   bool LHSSeenZero = false;
3436   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3437   bool RHSSeenZero = false;
3438   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3439   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3440     // If unsafe fp math optimization is enabled and there are no other uses of
3441     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3442     // to an integer comparison.
3443     if (CC == ISD::SETOEQ)
3444       CC = ISD::SETEQ;
3445     else if (CC == ISD::SETUNE)
3446       CC = ISD::SETNE;
3447
3448     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3449     SDValue ARMcc;
3450     if (LHS.getValueType() == MVT::f32) {
3451       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3452                         bitcastf32Toi32(LHS, DAG), Mask);
3453       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3454                         bitcastf32Toi32(RHS, DAG), Mask);
3455       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3456       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3457       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3458                          Chain, Dest, ARMcc, CCR, Cmp);
3459     }
3460
3461     SDValue LHS1, LHS2;
3462     SDValue RHS1, RHS2;
3463     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3464     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3465     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3466     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3467     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3468     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3469     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3470     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3471     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3472   }
3473
3474   return SDValue();
3475 }
3476
3477 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3478   SDValue Chain = Op.getOperand(0);
3479   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3480   SDValue LHS = Op.getOperand(2);
3481   SDValue RHS = Op.getOperand(3);
3482   SDValue Dest = Op.getOperand(4);
3483   SDLoc dl(Op);
3484
3485   if (LHS.getValueType() == MVT::i32) {
3486     SDValue ARMcc;
3487     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3488     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3489     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3490                        Chain, Dest, ARMcc, CCR, Cmp);
3491   }
3492
3493   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3494
3495   if (getTargetMachine().Options.UnsafeFPMath &&
3496       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3497        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3498     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3499     if (Result.getNode())
3500       return Result;
3501   }
3502
3503   ARMCC::CondCodes CondCode, CondCode2;
3504   FPCCToARMCC(CC, CondCode, CondCode2);
3505
3506   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3507   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3508   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3509   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3510   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3511   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3512   if (CondCode2 != ARMCC::AL) {
3513     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3514     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3515     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3516   }
3517   return Res;
3518 }
3519
3520 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3521   SDValue Chain = Op.getOperand(0);
3522   SDValue Table = Op.getOperand(1);
3523   SDValue Index = Op.getOperand(2);
3524   SDLoc dl(Op);
3525
3526   EVT PTy = getPointerTy();
3527   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3528   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3529   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3530   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3531   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3532   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3533   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3534   if (Subtarget->isThumb2()) {
3535     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3536     // which does another jump to the destination. This also makes it easier
3537     // to translate it to TBB / TBH later.
3538     // FIXME: This might not work if the function is extremely large.
3539     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3540                        Addr, Op.getOperand(2), JTI, UId);
3541   }
3542   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3543     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3544                        MachinePointerInfo::getJumpTable(),
3545                        false, false, false, 0);
3546     Chain = Addr.getValue(1);
3547     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3548     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3549   } else {
3550     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3551                        MachinePointerInfo::getJumpTable(),
3552                        false, false, false, 0);
3553     Chain = Addr.getValue(1);
3554     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3555   }
3556 }
3557
3558 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3559   EVT VT = Op.getValueType();
3560   SDLoc dl(Op);
3561
3562   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3563     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3564       return Op;
3565     return DAG.UnrollVectorOp(Op.getNode());
3566   }
3567
3568   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3569          "Invalid type for custom lowering!");
3570   if (VT != MVT::v4i16)
3571     return DAG.UnrollVectorOp(Op.getNode());
3572
3573   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3574   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3575 }
3576
3577 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3578   EVT VT = Op.getValueType();
3579   if (VT.isVector())
3580     return LowerVectorFP_TO_INT(Op, DAG);
3581
3582   SDLoc dl(Op);
3583   unsigned Opc;
3584
3585   switch (Op.getOpcode()) {
3586   default: llvm_unreachable("Invalid opcode!");
3587   case ISD::FP_TO_SINT:
3588     Opc = ARMISD::FTOSI;
3589     break;
3590   case ISD::FP_TO_UINT:
3591     Opc = ARMISD::FTOUI;
3592     break;
3593   }
3594   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3595   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3596 }
3597
3598 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3599   EVT VT = Op.getValueType();
3600   SDLoc dl(Op);
3601
3602   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3603     if (VT.getVectorElementType() == MVT::f32)
3604       return Op;
3605     return DAG.UnrollVectorOp(Op.getNode());
3606   }
3607
3608   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3609          "Invalid type for custom lowering!");
3610   if (VT != MVT::v4f32)
3611     return DAG.UnrollVectorOp(Op.getNode());
3612
3613   unsigned CastOpc;
3614   unsigned Opc;
3615   switch (Op.getOpcode()) {
3616   default: llvm_unreachable("Invalid opcode!");
3617   case ISD::SINT_TO_FP:
3618     CastOpc = ISD::SIGN_EXTEND;
3619     Opc = ISD::SINT_TO_FP;
3620     break;
3621   case ISD::UINT_TO_FP:
3622     CastOpc = ISD::ZERO_EXTEND;
3623     Opc = ISD::UINT_TO_FP;
3624     break;
3625   }
3626
3627   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3628   return DAG.getNode(Opc, dl, VT, Op);
3629 }
3630
3631 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3632   EVT VT = Op.getValueType();
3633   if (VT.isVector())
3634     return LowerVectorINT_TO_FP(Op, DAG);
3635
3636   SDLoc dl(Op);
3637   unsigned Opc;
3638
3639   switch (Op.getOpcode()) {
3640   default: llvm_unreachable("Invalid opcode!");
3641   case ISD::SINT_TO_FP:
3642     Opc = ARMISD::SITOF;
3643     break;
3644   case ISD::UINT_TO_FP:
3645     Opc = ARMISD::UITOF;
3646     break;
3647   }
3648
3649   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3650   return DAG.getNode(Opc, dl, VT, Op);
3651 }
3652
3653 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3654   // Implement fcopysign with a fabs and a conditional fneg.
3655   SDValue Tmp0 = Op.getOperand(0);
3656   SDValue Tmp1 = Op.getOperand(1);
3657   SDLoc dl(Op);
3658   EVT VT = Op.getValueType();
3659   EVT SrcVT = Tmp1.getValueType();
3660   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3661     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3662   bool UseNEON = !InGPR && Subtarget->hasNEON();
3663
3664   if (UseNEON) {
3665     // Use VBSL to copy the sign bit.
3666     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3667     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3668                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3669     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3670     if (VT == MVT::f64)
3671       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3672                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3673                          DAG.getConstant(32, MVT::i32));
3674     else /*if (VT == MVT::f32)*/
3675       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3676     if (SrcVT == MVT::f32) {
3677       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3678       if (VT == MVT::f64)
3679         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3680                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3681                            DAG.getConstant(32, MVT::i32));
3682     } else if (VT == MVT::f32)
3683       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3684                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3685                          DAG.getConstant(32, MVT::i32));
3686     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3687     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3688
3689     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3690                                             MVT::i32);
3691     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3692     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3693                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3694
3695     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3696                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3697                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3698     if (VT == MVT::f32) {
3699       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3700       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3701                         DAG.getConstant(0, MVT::i32));
3702     } else {
3703       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3704     }
3705
3706     return Res;
3707   }
3708
3709   // Bitcast operand 1 to i32.
3710   if (SrcVT == MVT::f64)
3711     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3712                        &Tmp1, 1).getValue(1);
3713   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3714
3715   // Or in the signbit with integer operations.
3716   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3717   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3718   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3719   if (VT == MVT::f32) {
3720     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3721                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3722     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3723                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3724   }
3725
3726   // f64: Or the high part with signbit and then combine two parts.
3727   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3728                      &Tmp0, 1);
3729   SDValue Lo = Tmp0.getValue(0);
3730   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3731   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3732   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3733 }
3734
3735 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3736   MachineFunction &MF = DAG.getMachineFunction();
3737   MachineFrameInfo *MFI = MF.getFrameInfo();
3738   MFI->setReturnAddressIsTaken(true);
3739
3740   EVT VT = Op.getValueType();
3741   SDLoc dl(Op);
3742   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3743   if (Depth) {
3744     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3745     SDValue Offset = DAG.getConstant(4, MVT::i32);
3746     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3747                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3748                        MachinePointerInfo(), false, false, false, 0);
3749   }
3750
3751   // Return LR, which contains the return address. Mark it an implicit live-in.
3752   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3753   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3754 }
3755
3756 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3757   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3758   MFI->setFrameAddressIsTaken(true);
3759
3760   EVT VT = Op.getValueType();
3761   SDLoc dl(Op);  // FIXME probably not meaningful
3762   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3763   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3764     ? ARM::R7 : ARM::R11;
3765   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3766   while (Depth--)
3767     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3768                             MachinePointerInfo(),
3769                             false, false, false, 0);
3770   return FrameAddr;
3771 }
3772
3773 /// Custom Expand long vector extensions, where size(DestVec) > 2*size(SrcVec),
3774 /// and size(DestVec) > 128-bits.
3775 /// This is achieved by doing the one extension from the SrcVec, splitting the
3776 /// result, extending these parts, and then concatenating these into the
3777 /// destination.
3778 static SDValue ExpandVectorExtension(SDNode *N, SelectionDAG &DAG) {
3779   SDValue Op = N->getOperand(0);
3780   EVT SrcVT = Op.getValueType();
3781   EVT DestVT = N->getValueType(0);
3782
3783   assert(DestVT.getSizeInBits() > 128 &&
3784          "Custom sext/zext expansion needs >128-bit vector.");
3785   // If this is a normal length extension, use the default expansion.
3786   if (SrcVT.getSizeInBits()*4 != DestVT.getSizeInBits() &&
3787       SrcVT.getSizeInBits()*8 != DestVT.getSizeInBits())
3788     return SDValue();
3789
3790   SDLoc dl(N);
3791   unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
3792   unsigned DestEltSize = DestVT.getVectorElementType().getSizeInBits();
3793   unsigned NumElts = SrcVT.getVectorNumElements();
3794   LLVMContext &Ctx = *DAG.getContext();
3795   SDValue Mid, SplitLo, SplitHi, ExtLo, ExtHi;
3796
3797   EVT MidVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3798                                NumElts);
3799   EVT SplitVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3800                                  NumElts/2);
3801   EVT ExtVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, DestEltSize),
3802                                NumElts/2);
3803
3804   Mid = DAG.getNode(N->getOpcode(), dl, MidVT, Op);
3805   SplitLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3806                         DAG.getIntPtrConstant(0));
3807   SplitHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3808                         DAG.getIntPtrConstant(NumElts/2));
3809   ExtLo = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitLo);
3810   ExtHi = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitHi);
3811   return DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, ExtLo, ExtHi);
3812 }
3813
3814 /// ExpandBITCAST - If the target supports VFP, this function is called to
3815 /// expand a bit convert where either the source or destination type is i64 to
3816 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3817 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3818 /// vectors), since the legalizer won't know what to do with that.
3819 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3820   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3821   SDLoc dl(N);
3822   SDValue Op = N->getOperand(0);
3823
3824   // This function is only supposed to be called for i64 types, either as the
3825   // source or destination of the bit convert.
3826   EVT SrcVT = Op.getValueType();
3827   EVT DstVT = N->getValueType(0);
3828   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3829          "ExpandBITCAST called for non-i64 type");
3830
3831   // Turn i64->f64 into VMOVDRR.
3832   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3833     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3834                              DAG.getConstant(0, MVT::i32));
3835     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3836                              DAG.getConstant(1, MVT::i32));
3837     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3838                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3839   }
3840
3841   // Turn f64->i64 into VMOVRRD.
3842   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3843     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3844                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3845     // Merge the pieces into a single i64 value.
3846     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3847   }
3848
3849   return SDValue();
3850 }
3851
3852 /// getZeroVector - Returns a vector of specified type with all zero elements.
3853 /// Zero vectors are used to represent vector negation and in those cases
3854 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3855 /// not support i64 elements, so sometimes the zero vectors will need to be
3856 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3857 /// zero vector.
3858 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3859   assert(VT.isVector() && "Expected a vector type");
3860   // The canonical modified immediate encoding of a zero vector is....0!
3861   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3862   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3863   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3864   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3865 }
3866
3867 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3868 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3869 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3870                                                 SelectionDAG &DAG) const {
3871   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3872   EVT VT = Op.getValueType();
3873   unsigned VTBits = VT.getSizeInBits();
3874   SDLoc dl(Op);
3875   SDValue ShOpLo = Op.getOperand(0);
3876   SDValue ShOpHi = Op.getOperand(1);
3877   SDValue ShAmt  = Op.getOperand(2);
3878   SDValue ARMcc;
3879   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3880
3881   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3882
3883   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3884                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3885   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3886   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3887                                    DAG.getConstant(VTBits, MVT::i32));
3888   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3889   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3890   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3891
3892   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3893   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3894                           ARMcc, DAG, dl);
3895   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3896   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3897                            CCR, Cmp);
3898
3899   SDValue Ops[2] = { Lo, Hi };
3900   return DAG.getMergeValues(Ops, 2, dl);
3901 }
3902
3903 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3904 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3905 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3906                                                SelectionDAG &DAG) const {
3907   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3908   EVT VT = Op.getValueType();
3909   unsigned VTBits = VT.getSizeInBits();
3910   SDLoc dl(Op);
3911   SDValue ShOpLo = Op.getOperand(0);
3912   SDValue ShOpHi = Op.getOperand(1);
3913   SDValue ShAmt  = Op.getOperand(2);
3914   SDValue ARMcc;
3915
3916   assert(Op.getOpcode() == ISD::SHL_PARTS);
3917   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3918                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3919   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3920   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3921                                    DAG.getConstant(VTBits, MVT::i32));
3922   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3923   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3924
3925   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3926   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3927   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3928                           ARMcc, DAG, dl);
3929   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3930   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3931                            CCR, Cmp);
3932
3933   SDValue Ops[2] = { Lo, Hi };
3934   return DAG.getMergeValues(Ops, 2, dl);
3935 }
3936
3937 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3938                                             SelectionDAG &DAG) const {
3939   // The rounding mode is in bits 23:22 of the FPSCR.
3940   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3941   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3942   // so that the shift + and get folded into a bitfield extract.
3943   SDLoc dl(Op);
3944   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3945                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3946                                               MVT::i32));
3947   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3948                                   DAG.getConstant(1U << 22, MVT::i32));
3949   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3950                               DAG.getConstant(22, MVT::i32));
3951   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3952                      DAG.getConstant(3, MVT::i32));
3953 }
3954
3955 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3956                          const ARMSubtarget *ST) {
3957   EVT VT = N->getValueType(0);
3958   SDLoc dl(N);
3959
3960   if (!ST->hasV6T2Ops())
3961     return SDValue();
3962
3963   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3964   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3965 }
3966
3967 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3968 /// for each 16-bit element from operand, repeated.  The basic idea is to
3969 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3970 ///
3971 /// Trace for v4i16:
3972 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
3973 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3974 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3975 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3976 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
3977 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
3978 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3979 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
3980 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3981   EVT VT = N->getValueType(0);
3982   SDLoc DL(N);
3983
3984   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
3985   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
3986   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
3987   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
3988   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
3989   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
3990 }
3991
3992 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
3993 /// bit-count for each 16-bit element from the operand.  We need slightly
3994 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
3995 /// 64/128-bit registers.
3996 ///
3997 /// Trace for v4i16:
3998 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
3999 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4000 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4001 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4002 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4003   EVT VT = N->getValueType(0);
4004   SDLoc DL(N);
4005
4006   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4007   if (VT.is64BitVector()) {
4008     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4009     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4010                        DAG.getIntPtrConstant(0));
4011   } else {
4012     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4013                                     BitCounts, DAG.getIntPtrConstant(0));
4014     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4015   }
4016 }
4017
4018 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4019 /// bit-count for each 32-bit element from the operand.  The idea here is
4020 /// to split the vector into 16-bit elements, leverage the 16-bit count
4021 /// routine, and then combine the results.
4022 ///
4023 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4024 /// input    = [v0    v1    ] (vi: 32-bit elements)
4025 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4026 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4027 /// vrev: N0 = [k1 k0 k3 k2 ]
4028 ///            [k0 k1 k2 k3 ]
4029 ///       N1 =+[k1 k0 k3 k2 ]
4030 ///            [k0 k2 k1 k3 ]
4031 ///       N2 =+[k1 k3 k0 k2 ]
4032 ///            [k0    k2    k1    k3    ]
4033 /// Extended =+[k1    k3    k0    k2    ]
4034 ///            [k0    k2    ]
4035 /// Extracted=+[k1    k3    ]
4036 ///
4037 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4038   EVT VT = N->getValueType(0);
4039   SDLoc DL(N);
4040
4041   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4042
4043   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4044   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4045   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4046   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4047   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4048
4049   if (VT.is64BitVector()) {
4050     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4051     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4052                        DAG.getIntPtrConstant(0));
4053   } else {
4054     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4055                                     DAG.getIntPtrConstant(0));
4056     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4057   }
4058 }
4059
4060 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4061                           const ARMSubtarget *ST) {
4062   EVT VT = N->getValueType(0);
4063
4064   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4065   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4066           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4067          "Unexpected type for custom ctpop lowering");
4068
4069   if (VT.getVectorElementType() == MVT::i32)
4070     return lowerCTPOP32BitElements(N, DAG);
4071   else
4072     return lowerCTPOP16BitElements(N, DAG);
4073 }
4074
4075 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4076                           const ARMSubtarget *ST) {
4077   EVT VT = N->getValueType(0);
4078   SDLoc dl(N);
4079
4080   if (!VT.isVector())
4081     return SDValue();
4082
4083   // Lower vector shifts on NEON to use VSHL.
4084   assert(ST->hasNEON() && "unexpected vector shift");
4085
4086   // Left shifts translate directly to the vshiftu intrinsic.
4087   if (N->getOpcode() == ISD::SHL)
4088     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4089                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4090                        N->getOperand(0), N->getOperand(1));
4091
4092   assert((N->getOpcode() == ISD::SRA ||
4093           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4094
4095   // NEON uses the same intrinsics for both left and right shifts.  For
4096   // right shifts, the shift amounts are negative, so negate the vector of
4097   // shift amounts.
4098   EVT ShiftVT = N->getOperand(1).getValueType();
4099   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4100                                      getZeroVector(ShiftVT, DAG, dl),
4101                                      N->getOperand(1));
4102   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4103                              Intrinsic::arm_neon_vshifts :
4104                              Intrinsic::arm_neon_vshiftu);
4105   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4106                      DAG.getConstant(vshiftInt, MVT::i32),
4107                      N->getOperand(0), NegatedCount);
4108 }
4109
4110 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4111                                 const ARMSubtarget *ST) {
4112   EVT VT = N->getValueType(0);
4113   SDLoc dl(N);
4114
4115   // We can get here for a node like i32 = ISD::SHL i32, i64
4116   if (VT != MVT::i64)
4117     return SDValue();
4118
4119   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4120          "Unknown shift to lower!");
4121
4122   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4123   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4124       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4125     return SDValue();
4126
4127   // If we are in thumb mode, we don't have RRX.
4128   if (ST->isThumb1Only()) return SDValue();
4129
4130   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4131   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4132                            DAG.getConstant(0, MVT::i32));
4133   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4134                            DAG.getConstant(1, MVT::i32));
4135
4136   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4137   // captures the result into a carry flag.
4138   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4139   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
4140
4141   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4142   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4143
4144   // Merge the pieces into a single i64 value.
4145  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4146 }
4147
4148 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4149   SDValue TmpOp0, TmpOp1;
4150   bool Invert = false;
4151   bool Swap = false;
4152   unsigned Opc = 0;
4153
4154   SDValue Op0 = Op.getOperand(0);
4155   SDValue Op1 = Op.getOperand(1);
4156   SDValue CC = Op.getOperand(2);
4157   EVT VT = Op.getValueType();
4158   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4159   SDLoc dl(Op);
4160
4161   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4162     switch (SetCCOpcode) {
4163     default: llvm_unreachable("Illegal FP comparison");
4164     case ISD::SETUNE:
4165     case ISD::SETNE:  Invert = true; // Fallthrough
4166     case ISD::SETOEQ:
4167     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4168     case ISD::SETOLT:
4169     case ISD::SETLT: Swap = true; // Fallthrough
4170     case ISD::SETOGT:
4171     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4172     case ISD::SETOLE:
4173     case ISD::SETLE:  Swap = true; // Fallthrough
4174     case ISD::SETOGE:
4175     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4176     case ISD::SETUGE: Swap = true; // Fallthrough
4177     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4178     case ISD::SETUGT: Swap = true; // Fallthrough
4179     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4180     case ISD::SETUEQ: Invert = true; // Fallthrough
4181     case ISD::SETONE:
4182       // Expand this to (OLT | OGT).
4183       TmpOp0 = Op0;
4184       TmpOp1 = Op1;
4185       Opc = ISD::OR;
4186       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4187       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4188       break;
4189     case ISD::SETUO: Invert = true; // Fallthrough
4190     case ISD::SETO:
4191       // Expand this to (OLT | OGE).
4192       TmpOp0 = Op0;
4193       TmpOp1 = Op1;
4194       Opc = ISD::OR;
4195       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4196       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4197       break;
4198     }
4199   } else {
4200     // Integer comparisons.
4201     switch (SetCCOpcode) {
4202     default: llvm_unreachable("Illegal integer comparison");
4203     case ISD::SETNE:  Invert = true;
4204     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4205     case ISD::SETLT:  Swap = true;
4206     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4207     case ISD::SETLE:  Swap = true;
4208     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4209     case ISD::SETULT: Swap = true;
4210     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4211     case ISD::SETULE: Swap = true;
4212     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4213     }
4214
4215     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4216     if (Opc == ARMISD::VCEQ) {
4217
4218       SDValue AndOp;
4219       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4220         AndOp = Op0;
4221       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4222         AndOp = Op1;
4223
4224       // Ignore bitconvert.
4225       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4226         AndOp = AndOp.getOperand(0);
4227
4228       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4229         Opc = ARMISD::VTST;
4230         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4231         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4232         Invert = !Invert;
4233       }
4234     }
4235   }
4236
4237   if (Swap)
4238     std::swap(Op0, Op1);
4239
4240   // If one of the operands is a constant vector zero, attempt to fold the
4241   // comparison to a specialized compare-against-zero form.
4242   SDValue SingleOp;
4243   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4244     SingleOp = Op0;
4245   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4246     if (Opc == ARMISD::VCGE)
4247       Opc = ARMISD::VCLEZ;
4248     else if (Opc == ARMISD::VCGT)
4249       Opc = ARMISD::VCLTZ;
4250     SingleOp = Op1;
4251   }
4252
4253   SDValue Result;
4254   if (SingleOp.getNode()) {
4255     switch (Opc) {
4256     case ARMISD::VCEQ:
4257       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4258     case ARMISD::VCGE:
4259       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4260     case ARMISD::VCLEZ:
4261       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4262     case ARMISD::VCGT:
4263       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4264     case ARMISD::VCLTZ:
4265       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4266     default:
4267       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4268     }
4269   } else {
4270      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4271   }
4272
4273   if (Invert)
4274     Result = DAG.getNOT(dl, Result, VT);
4275
4276   return Result;
4277 }
4278
4279 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4280 /// valid vector constant for a NEON instruction with a "modified immediate"
4281 /// operand (e.g., VMOV).  If so, return the encoded value.
4282 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4283                                  unsigned SplatBitSize, SelectionDAG &DAG,
4284                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4285   unsigned OpCmode, Imm;
4286
4287   // SplatBitSize is set to the smallest size that splats the vector, so a
4288   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4289   // immediate instructions others than VMOV do not support the 8-bit encoding
4290   // of a zero vector, and the default encoding of zero is supposed to be the
4291   // 32-bit version.
4292   if (SplatBits == 0)
4293     SplatBitSize = 32;
4294
4295   switch (SplatBitSize) {
4296   case 8:
4297     if (type != VMOVModImm)
4298       return SDValue();
4299     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4300     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4301     OpCmode = 0xe;
4302     Imm = SplatBits;
4303     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4304     break;
4305
4306   case 16:
4307     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4308     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4309     if ((SplatBits & ~0xff) == 0) {
4310       // Value = 0x00nn: Op=x, Cmode=100x.
4311       OpCmode = 0x8;
4312       Imm = SplatBits;
4313       break;
4314     }
4315     if ((SplatBits & ~0xff00) == 0) {
4316       // Value = 0xnn00: Op=x, Cmode=101x.
4317       OpCmode = 0xa;
4318       Imm = SplatBits >> 8;
4319       break;
4320     }
4321     return SDValue();
4322
4323   case 32:
4324     // NEON's 32-bit VMOV supports splat values where:
4325     // * only one byte is nonzero, or
4326     // * the least significant byte is 0xff and the second byte is nonzero, or
4327     // * the least significant 2 bytes are 0xff and the third is nonzero.
4328     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4329     if ((SplatBits & ~0xff) == 0) {
4330       // Value = 0x000000nn: Op=x, Cmode=000x.
4331       OpCmode = 0;
4332       Imm = SplatBits;
4333       break;
4334     }
4335     if ((SplatBits & ~0xff00) == 0) {
4336       // Value = 0x0000nn00: Op=x, Cmode=001x.
4337       OpCmode = 0x2;
4338       Imm = SplatBits >> 8;
4339       break;
4340     }
4341     if ((SplatBits & ~0xff0000) == 0) {
4342       // Value = 0x00nn0000: Op=x, Cmode=010x.
4343       OpCmode = 0x4;
4344       Imm = SplatBits >> 16;
4345       break;
4346     }
4347     if ((SplatBits & ~0xff000000) == 0) {
4348       // Value = 0xnn000000: Op=x, Cmode=011x.
4349       OpCmode = 0x6;
4350       Imm = SplatBits >> 24;
4351       break;
4352     }
4353
4354     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4355     if (type == OtherModImm) return SDValue();
4356
4357     if ((SplatBits & ~0xffff) == 0 &&
4358         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4359       // Value = 0x0000nnff: Op=x, Cmode=1100.
4360       OpCmode = 0xc;
4361       Imm = SplatBits >> 8;
4362       SplatBits |= 0xff;
4363       break;
4364     }
4365
4366     if ((SplatBits & ~0xffffff) == 0 &&
4367         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4368       // Value = 0x00nnffff: Op=x, Cmode=1101.
4369       OpCmode = 0xd;
4370       Imm = SplatBits >> 16;
4371       SplatBits |= 0xffff;
4372       break;
4373     }
4374
4375     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4376     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4377     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4378     // and fall through here to test for a valid 64-bit splat.  But, then the
4379     // caller would also need to check and handle the change in size.
4380     return SDValue();
4381
4382   case 64: {
4383     if (type != VMOVModImm)
4384       return SDValue();
4385     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4386     uint64_t BitMask = 0xff;
4387     uint64_t Val = 0;
4388     unsigned ImmMask = 1;
4389     Imm = 0;
4390     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4391       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4392         Val |= BitMask;
4393         Imm |= ImmMask;
4394       } else if ((SplatBits & BitMask) != 0) {
4395         return SDValue();
4396       }
4397       BitMask <<= 8;
4398       ImmMask <<= 1;
4399     }
4400     // Op=1, Cmode=1110.
4401     OpCmode = 0x1e;
4402     SplatBits = Val;
4403     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4404     break;
4405   }
4406
4407   default:
4408     llvm_unreachable("unexpected size for isNEONModifiedImm");
4409   }
4410
4411   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4412   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4413 }
4414
4415 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4416                                            const ARMSubtarget *ST) const {
4417   if (!ST->hasVFP3())
4418     return SDValue();
4419
4420   bool IsDouble = Op.getValueType() == MVT::f64;
4421   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4422
4423   // Try splatting with a VMOV.f32...
4424   APFloat FPVal = CFP->getValueAPF();
4425   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4426
4427   if (ImmVal != -1) {
4428     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4429       // We have code in place to select a valid ConstantFP already, no need to
4430       // do any mangling.
4431       return Op;
4432     }
4433
4434     // It's a float and we are trying to use NEON operations where
4435     // possible. Lower it to a splat followed by an extract.
4436     SDLoc DL(Op);
4437     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4438     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4439                                       NewVal);
4440     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4441                        DAG.getConstant(0, MVT::i32));
4442   }
4443
4444   // The rest of our options are NEON only, make sure that's allowed before
4445   // proceeding..
4446   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4447     return SDValue();
4448
4449   EVT VMovVT;
4450   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4451
4452   // It wouldn't really be worth bothering for doubles except for one very
4453   // important value, which does happen to match: 0.0. So make sure we don't do
4454   // anything stupid.
4455   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4456     return SDValue();
4457
4458   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4459   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4460                                      false, VMOVModImm);
4461   if (NewVal != SDValue()) {
4462     SDLoc DL(Op);
4463     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4464                                       NewVal);
4465     if (IsDouble)
4466       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4467
4468     // It's a float: cast and extract a vector element.
4469     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4470                                        VecConstant);
4471     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4472                        DAG.getConstant(0, MVT::i32));
4473   }
4474
4475   // Finally, try a VMVN.i32
4476   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4477                              false, VMVNModImm);
4478   if (NewVal != SDValue()) {
4479     SDLoc DL(Op);
4480     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4481
4482     if (IsDouble)
4483       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4484
4485     // It's a float: cast and extract a vector element.
4486     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4487                                        VecConstant);
4488     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4489                        DAG.getConstant(0, MVT::i32));
4490   }
4491
4492   return SDValue();
4493 }
4494
4495 // check if an VEXT instruction can handle the shuffle mask when the
4496 // vector sources of the shuffle are the same.
4497 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4498   unsigned NumElts = VT.getVectorNumElements();
4499
4500   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4501   if (M[0] < 0)
4502     return false;
4503
4504   Imm = M[0];
4505
4506   // If this is a VEXT shuffle, the immediate value is the index of the first
4507   // element.  The other shuffle indices must be the successive elements after
4508   // the first one.
4509   unsigned ExpectedElt = Imm;
4510   for (unsigned i = 1; i < NumElts; ++i) {
4511     // Increment the expected index.  If it wraps around, just follow it
4512     // back to index zero and keep going.
4513     ++ExpectedElt;
4514     if (ExpectedElt == NumElts)
4515       ExpectedElt = 0;
4516
4517     if (M[i] < 0) continue; // ignore UNDEF indices
4518     if (ExpectedElt != static_cast<unsigned>(M[i]))
4519       return false;
4520   }
4521
4522   return true;
4523 }
4524
4525
4526 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4527                        bool &ReverseVEXT, unsigned &Imm) {
4528   unsigned NumElts = VT.getVectorNumElements();
4529   ReverseVEXT = false;
4530
4531   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4532   if (M[0] < 0)
4533     return false;
4534
4535   Imm = M[0];
4536
4537   // If this is a VEXT shuffle, the immediate value is the index of the first
4538   // element.  The other shuffle indices must be the successive elements after
4539   // the first one.
4540   unsigned ExpectedElt = Imm;
4541   for (unsigned i = 1; i < NumElts; ++i) {
4542     // Increment the expected index.  If it wraps around, it may still be
4543     // a VEXT but the source vectors must be swapped.
4544     ExpectedElt += 1;
4545     if (ExpectedElt == NumElts * 2) {
4546       ExpectedElt = 0;
4547       ReverseVEXT = true;
4548     }
4549
4550     if (M[i] < 0) continue; // ignore UNDEF indices
4551     if (ExpectedElt != static_cast<unsigned>(M[i]))
4552       return false;
4553   }
4554
4555   // Adjust the index value if the source operands will be swapped.
4556   if (ReverseVEXT)
4557     Imm -= NumElts;
4558
4559   return true;
4560 }
4561
4562 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4563 /// instruction with the specified blocksize.  (The order of the elements
4564 /// within each block of the vector is reversed.)
4565 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4566   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4567          "Only possible block sizes for VREV are: 16, 32, 64");
4568
4569   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4570   if (EltSz == 64)
4571     return false;
4572
4573   unsigned NumElts = VT.getVectorNumElements();
4574   unsigned BlockElts = M[0] + 1;
4575   // If the first shuffle index is UNDEF, be optimistic.
4576   if (M[0] < 0)
4577     BlockElts = BlockSize / EltSz;
4578
4579   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4580     return false;
4581
4582   for (unsigned i = 0; i < NumElts; ++i) {
4583     if (M[i] < 0) continue; // ignore UNDEF indices
4584     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4585       return false;
4586   }
4587
4588   return true;
4589 }
4590
4591 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4592   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4593   // range, then 0 is placed into the resulting vector. So pretty much any mask
4594   // of 8 elements can work here.
4595   return VT == MVT::v8i8 && M.size() == 8;
4596 }
4597
4598 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4599   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4600   if (EltSz == 64)
4601     return false;
4602
4603   unsigned NumElts = VT.getVectorNumElements();
4604   WhichResult = (M[0] == 0 ? 0 : 1);
4605   for (unsigned i = 0; i < NumElts; i += 2) {
4606     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4607         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4608       return false;
4609   }
4610   return true;
4611 }
4612
4613 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4614 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4615 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4616 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4617   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4618   if (EltSz == 64)
4619     return false;
4620
4621   unsigned NumElts = VT.getVectorNumElements();
4622   WhichResult = (M[0] == 0 ? 0 : 1);
4623   for (unsigned i = 0; i < NumElts; i += 2) {
4624     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4625         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4626       return false;
4627   }
4628   return true;
4629 }
4630
4631 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4632   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4633   if (EltSz == 64)
4634     return false;
4635
4636   unsigned NumElts = VT.getVectorNumElements();
4637   WhichResult = (M[0] == 0 ? 0 : 1);
4638   for (unsigned i = 0; i != NumElts; ++i) {
4639     if (M[i] < 0) continue; // ignore UNDEF indices
4640     if ((unsigned) M[i] != 2 * i + WhichResult)
4641       return false;
4642   }
4643
4644   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4645   if (VT.is64BitVector() && EltSz == 32)
4646     return false;
4647
4648   return true;
4649 }
4650
4651 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4652 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4653 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4654 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4655   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4656   if (EltSz == 64)
4657     return false;
4658
4659   unsigned Half = VT.getVectorNumElements() / 2;
4660   WhichResult = (M[0] == 0 ? 0 : 1);
4661   for (unsigned j = 0; j != 2; ++j) {
4662     unsigned Idx = WhichResult;
4663     for (unsigned i = 0; i != Half; ++i) {
4664       int MIdx = M[i + j * Half];
4665       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4666         return false;
4667       Idx += 2;
4668     }
4669   }
4670
4671   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4672   if (VT.is64BitVector() && EltSz == 32)
4673     return false;
4674
4675   return true;
4676 }
4677
4678 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4679   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4680   if (EltSz == 64)
4681     return false;
4682
4683   unsigned NumElts = VT.getVectorNumElements();
4684   WhichResult = (M[0] == 0 ? 0 : 1);
4685   unsigned Idx = WhichResult * NumElts / 2;
4686   for (unsigned i = 0; i != NumElts; i += 2) {
4687     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4688         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4689       return false;
4690     Idx += 1;
4691   }
4692
4693   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4694   if (VT.is64BitVector() && EltSz == 32)
4695     return false;
4696
4697   return true;
4698 }
4699
4700 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4701 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4702 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4703 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4704   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4705   if (EltSz == 64)
4706     return false;
4707
4708   unsigned NumElts = VT.getVectorNumElements();
4709   WhichResult = (M[0] == 0 ? 0 : 1);
4710   unsigned Idx = WhichResult * NumElts / 2;
4711   for (unsigned i = 0; i != NumElts; i += 2) {
4712     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4713         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4714       return false;
4715     Idx += 1;
4716   }
4717
4718   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4719   if (VT.is64BitVector() && EltSz == 32)
4720     return false;
4721
4722   return true;
4723 }
4724
4725 /// \return true if this is a reverse operation on an vector.
4726 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4727   unsigned NumElts = VT.getVectorNumElements();
4728   // Make sure the mask has the right size.
4729   if (NumElts != M.size())
4730       return false;
4731
4732   // Look for <15, ..., 3, -1, 1, 0>.
4733   for (unsigned i = 0; i != NumElts; ++i)
4734     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4735       return false;
4736
4737   return true;
4738 }
4739
4740 // If N is an integer constant that can be moved into a register in one
4741 // instruction, return an SDValue of such a constant (will become a MOV
4742 // instruction).  Otherwise return null.
4743 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4744                                      const ARMSubtarget *ST, SDLoc dl) {
4745   uint64_t Val;
4746   if (!isa<ConstantSDNode>(N))
4747     return SDValue();
4748   Val = cast<ConstantSDNode>(N)->getZExtValue();
4749
4750   if (ST->isThumb1Only()) {
4751     if (Val <= 255 || ~Val <= 255)
4752       return DAG.getConstant(Val, MVT::i32);
4753   } else {
4754     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4755       return DAG.getConstant(Val, MVT::i32);
4756   }
4757   return SDValue();
4758 }
4759
4760 // If this is a case we can't handle, return null and let the default
4761 // expansion code take care of it.
4762 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4763                                              const ARMSubtarget *ST) const {
4764   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4765   SDLoc dl(Op);
4766   EVT VT = Op.getValueType();
4767
4768   APInt SplatBits, SplatUndef;
4769   unsigned SplatBitSize;
4770   bool HasAnyUndefs;
4771   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4772     if (SplatBitSize <= 64) {
4773       // Check if an immediate VMOV works.
4774       EVT VmovVT;
4775       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4776                                       SplatUndef.getZExtValue(), SplatBitSize,
4777                                       DAG, VmovVT, VT.is128BitVector(),
4778                                       VMOVModImm);
4779       if (Val.getNode()) {
4780         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4781         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4782       }
4783
4784       // Try an immediate VMVN.
4785       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4786       Val = isNEONModifiedImm(NegatedImm,
4787                                       SplatUndef.getZExtValue(), SplatBitSize,
4788                                       DAG, VmovVT, VT.is128BitVector(),
4789                                       VMVNModImm);
4790       if (Val.getNode()) {
4791         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4792         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4793       }
4794
4795       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4796       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4797         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4798         if (ImmVal != -1) {
4799           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4800           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4801         }
4802       }
4803     }
4804   }
4805
4806   // Scan through the operands to see if only one value is used.
4807   //
4808   // As an optimisation, even if more than one value is used it may be more
4809   // profitable to splat with one value then change some lanes.
4810   //
4811   // Heuristically we decide to do this if the vector has a "dominant" value,
4812   // defined as splatted to more than half of the lanes.
4813   unsigned NumElts = VT.getVectorNumElements();
4814   bool isOnlyLowElement = true;
4815   bool usesOnlyOneValue = true;
4816   bool hasDominantValue = false;
4817   bool isConstant = true;
4818
4819   // Map of the number of times a particular SDValue appears in the
4820   // element list.
4821   DenseMap<SDValue, unsigned> ValueCounts;
4822   SDValue Value;
4823   for (unsigned i = 0; i < NumElts; ++i) {
4824     SDValue V = Op.getOperand(i);
4825     if (V.getOpcode() == ISD::UNDEF)
4826       continue;
4827     if (i > 0)
4828       isOnlyLowElement = false;
4829     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4830       isConstant = false;
4831
4832     ValueCounts.insert(std::make_pair(V, 0));
4833     unsigned &Count = ValueCounts[V];
4834
4835     // Is this value dominant? (takes up more than half of the lanes)
4836     if (++Count > (NumElts / 2)) {
4837       hasDominantValue = true;
4838       Value = V;
4839     }
4840   }
4841   if (ValueCounts.size() != 1)
4842     usesOnlyOneValue = false;
4843   if (!Value.getNode() && ValueCounts.size() > 0)
4844     Value = ValueCounts.begin()->first;
4845
4846   if (ValueCounts.size() == 0)
4847     return DAG.getUNDEF(VT);
4848
4849   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
4850   // Keep going if we are hitting this case.
4851   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
4852     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4853
4854   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4855
4856   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4857   // i32 and try again.
4858   if (hasDominantValue && EltSize <= 32) {
4859     if (!isConstant) {
4860       SDValue N;
4861
4862       // If we are VDUPing a value that comes directly from a vector, that will
4863       // cause an unnecessary move to and from a GPR, where instead we could
4864       // just use VDUPLANE. We can only do this if the lane being extracted
4865       // is at a constant index, as the VDUP from lane instructions only have
4866       // constant-index forms.
4867       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4868           isa<ConstantSDNode>(Value->getOperand(1))) {
4869         // We need to create a new undef vector to use for the VDUPLANE if the
4870         // size of the vector from which we get the value is different than the
4871         // size of the vector that we need to create. We will insert the element
4872         // such that the register coalescer will remove unnecessary copies.
4873         if (VT != Value->getOperand(0).getValueType()) {
4874           ConstantSDNode *constIndex;
4875           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4876           assert(constIndex && "The index is not a constant!");
4877           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4878                              VT.getVectorNumElements();
4879           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4880                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4881                         Value, DAG.getConstant(index, MVT::i32)),
4882                            DAG.getConstant(index, MVT::i32));
4883         } else
4884           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4885                         Value->getOperand(0), Value->getOperand(1));
4886       } else
4887         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4888
4889       if (!usesOnlyOneValue) {
4890         // The dominant value was splatted as 'N', but we now have to insert
4891         // all differing elements.
4892         for (unsigned I = 0; I < NumElts; ++I) {
4893           if (Op.getOperand(I) == Value)
4894             continue;
4895           SmallVector<SDValue, 3> Ops;
4896           Ops.push_back(N);
4897           Ops.push_back(Op.getOperand(I));
4898           Ops.push_back(DAG.getConstant(I, MVT::i32));
4899           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4900         }
4901       }
4902       return N;
4903     }
4904     if (VT.getVectorElementType().isFloatingPoint()) {
4905       SmallVector<SDValue, 8> Ops;
4906       for (unsigned i = 0; i < NumElts; ++i)
4907         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4908                                   Op.getOperand(i)));
4909       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4910       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4911       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4912       if (Val.getNode())
4913         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4914     }
4915     if (usesOnlyOneValue) {
4916       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4917       if (isConstant && Val.getNode())
4918         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4919     }
4920   }
4921
4922   // If all elements are constants and the case above didn't get hit, fall back
4923   // to the default expansion, which will generate a load from the constant
4924   // pool.
4925   if (isConstant)
4926     return SDValue();
4927
4928   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4929   if (NumElts >= 4) {
4930     SDValue shuffle = ReconstructShuffle(Op, DAG);
4931     if (shuffle != SDValue())
4932       return shuffle;
4933   }
4934
4935   // Vectors with 32- or 64-bit elements can be built by directly assigning
4936   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4937   // will be legalized.
4938   if (EltSize >= 32) {
4939     // Do the expansion with floating-point types, since that is what the VFP
4940     // registers are defined to use, and since i64 is not legal.
4941     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4942     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4943     SmallVector<SDValue, 8> Ops;
4944     for (unsigned i = 0; i < NumElts; ++i)
4945       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4946     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4947     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4948   }
4949
4950   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
4951   // know the default expansion would otherwise fall back on something even
4952   // worse. For a vector with one or two non-undef values, that's
4953   // scalar_to_vector for the elements followed by a shuffle (provided the
4954   // shuffle is valid for the target) and materialization element by element
4955   // on the stack followed by a load for everything else.
4956   if (!isConstant && !usesOnlyOneValue) {
4957     SDValue Vec = DAG.getUNDEF(VT);
4958     for (unsigned i = 0 ; i < NumElts; ++i) {
4959       SDValue V = Op.getOperand(i);
4960       if (V.getOpcode() == ISD::UNDEF)
4961         continue;
4962       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
4963       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
4964     }
4965     return Vec;
4966   }
4967
4968   return SDValue();
4969 }
4970
4971 // Gather data to see if the operation can be modelled as a
4972 // shuffle in combination with VEXTs.
4973 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4974                                               SelectionDAG &DAG) const {
4975   SDLoc dl(Op);
4976   EVT VT = Op.getValueType();
4977   unsigned NumElts = VT.getVectorNumElements();
4978
4979   SmallVector<SDValue, 2> SourceVecs;
4980   SmallVector<unsigned, 2> MinElts;
4981   SmallVector<unsigned, 2> MaxElts;
4982
4983   for (unsigned i = 0; i < NumElts; ++i) {
4984     SDValue V = Op.getOperand(i);
4985     if (V.getOpcode() == ISD::UNDEF)
4986       continue;
4987     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4988       // A shuffle can only come from building a vector from various
4989       // elements of other vectors.
4990       return SDValue();
4991     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4992                VT.getVectorElementType()) {
4993       // This code doesn't know how to handle shuffles where the vector
4994       // element types do not match (this happens because type legalization
4995       // promotes the return type of EXTRACT_VECTOR_ELT).
4996       // FIXME: It might be appropriate to extend this code to handle
4997       // mismatched types.
4998       return SDValue();
4999     }
5000
5001     // Record this extraction against the appropriate vector if possible...
5002     SDValue SourceVec = V.getOperand(0);
5003     // If the element number isn't a constant, we can't effectively
5004     // analyze what's going on.
5005     if (!isa<ConstantSDNode>(V.getOperand(1)))
5006       return SDValue();
5007     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5008     bool FoundSource = false;
5009     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5010       if (SourceVecs[j] == SourceVec) {
5011         if (MinElts[j] > EltNo)
5012           MinElts[j] = EltNo;
5013         if (MaxElts[j] < EltNo)
5014           MaxElts[j] = EltNo;
5015         FoundSource = true;
5016         break;
5017       }
5018     }
5019
5020     // Or record a new source if not...
5021     if (!FoundSource) {
5022       SourceVecs.push_back(SourceVec);
5023       MinElts.push_back(EltNo);
5024       MaxElts.push_back(EltNo);
5025     }
5026   }
5027
5028   // Currently only do something sane when at most two source vectors
5029   // involved.
5030   if (SourceVecs.size() > 2)
5031     return SDValue();
5032
5033   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5034   int VEXTOffsets[2] = {0, 0};
5035
5036   // This loop extracts the usage patterns of the source vectors
5037   // and prepares appropriate SDValues for a shuffle if possible.
5038   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5039     if (SourceVecs[i].getValueType() == VT) {
5040       // No VEXT necessary
5041       ShuffleSrcs[i] = SourceVecs[i];
5042       VEXTOffsets[i] = 0;
5043       continue;
5044     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5045       // It probably isn't worth padding out a smaller vector just to
5046       // break it down again in a shuffle.
5047       return SDValue();
5048     }
5049
5050     // Since only 64-bit and 128-bit vectors are legal on ARM and
5051     // we've eliminated the other cases...
5052     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5053            "unexpected vector sizes in ReconstructShuffle");
5054
5055     if (MaxElts[i] - MinElts[i] >= NumElts) {
5056       // Span too large for a VEXT to cope
5057       return SDValue();
5058     }
5059
5060     if (MinElts[i] >= NumElts) {
5061       // The extraction can just take the second half
5062       VEXTOffsets[i] = NumElts;
5063       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5064                                    SourceVecs[i],
5065                                    DAG.getIntPtrConstant(NumElts));
5066     } else if (MaxElts[i] < NumElts) {
5067       // The extraction can just take the first half
5068       VEXTOffsets[i] = 0;
5069       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5070                                    SourceVecs[i],
5071                                    DAG.getIntPtrConstant(0));
5072     } else {
5073       // An actual VEXT is needed
5074       VEXTOffsets[i] = MinElts[i];
5075       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5076                                      SourceVecs[i],
5077                                      DAG.getIntPtrConstant(0));
5078       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5079                                      SourceVecs[i],
5080                                      DAG.getIntPtrConstant(NumElts));
5081       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5082                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5083     }
5084   }
5085
5086   SmallVector<int, 8> Mask;
5087
5088   for (unsigned i = 0; i < NumElts; ++i) {
5089     SDValue Entry = Op.getOperand(i);
5090     if (Entry.getOpcode() == ISD::UNDEF) {
5091       Mask.push_back(-1);
5092       continue;
5093     }
5094
5095     SDValue ExtractVec = Entry.getOperand(0);
5096     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5097                                           .getOperand(1))->getSExtValue();
5098     if (ExtractVec == SourceVecs[0]) {
5099       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5100     } else {
5101       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5102     }
5103   }
5104
5105   // Final check before we try to produce nonsense...
5106   if (isShuffleMaskLegal(Mask, VT))
5107     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5108                                 &Mask[0]);
5109
5110   return SDValue();
5111 }
5112
5113 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5114 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5115 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5116 /// are assumed to be legal.
5117 bool
5118 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5119                                       EVT VT) const {
5120   if (VT.getVectorNumElements() == 4 &&
5121       (VT.is128BitVector() || VT.is64BitVector())) {
5122     unsigned PFIndexes[4];
5123     for (unsigned i = 0; i != 4; ++i) {
5124       if (M[i] < 0)
5125         PFIndexes[i] = 8;
5126       else
5127         PFIndexes[i] = M[i];
5128     }
5129
5130     // Compute the index in the perfect shuffle table.
5131     unsigned PFTableIndex =
5132       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5133     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5134     unsigned Cost = (PFEntry >> 30);
5135
5136     if (Cost <= 4)
5137       return true;
5138   }
5139
5140   bool ReverseVEXT;
5141   unsigned Imm, WhichResult;
5142
5143   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5144   return (EltSize >= 32 ||
5145           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5146           isVREVMask(M, VT, 64) ||
5147           isVREVMask(M, VT, 32) ||
5148           isVREVMask(M, VT, 16) ||
5149           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5150           isVTBLMask(M, VT) ||
5151           isVTRNMask(M, VT, WhichResult) ||
5152           isVUZPMask(M, VT, WhichResult) ||
5153           isVZIPMask(M, VT, WhichResult) ||
5154           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5155           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5156           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5157           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5158 }
5159
5160 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5161 /// the specified operations to build the shuffle.
5162 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5163                                       SDValue RHS, SelectionDAG &DAG,
5164                                       SDLoc dl) {
5165   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5166   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5167   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5168
5169   enum {
5170     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5171     OP_VREV,
5172     OP_VDUP0,
5173     OP_VDUP1,
5174     OP_VDUP2,
5175     OP_VDUP3,
5176     OP_VEXT1,
5177     OP_VEXT2,
5178     OP_VEXT3,
5179     OP_VUZPL, // VUZP, left result
5180     OP_VUZPR, // VUZP, right result
5181     OP_VZIPL, // VZIP, left result
5182     OP_VZIPR, // VZIP, right result
5183     OP_VTRNL, // VTRN, left result
5184     OP_VTRNR  // VTRN, right result
5185   };
5186
5187   if (OpNum == OP_COPY) {
5188     if (LHSID == (1*9+2)*9+3) return LHS;
5189     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5190     return RHS;
5191   }
5192
5193   SDValue OpLHS, OpRHS;
5194   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5195   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5196   EVT VT = OpLHS.getValueType();
5197
5198   switch (OpNum) {
5199   default: llvm_unreachable("Unknown shuffle opcode!");
5200   case OP_VREV:
5201     // VREV divides the vector in half and swaps within the half.
5202     if (VT.getVectorElementType() == MVT::i32 ||
5203         VT.getVectorElementType() == MVT::f32)
5204       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5205     // vrev <4 x i16> -> VREV32
5206     if (VT.getVectorElementType() == MVT::i16)
5207       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5208     // vrev <4 x i8> -> VREV16
5209     assert(VT.getVectorElementType() == MVT::i8);
5210     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5211   case OP_VDUP0:
5212   case OP_VDUP1:
5213   case OP_VDUP2:
5214   case OP_VDUP3:
5215     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5216                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5217   case OP_VEXT1:
5218   case OP_VEXT2:
5219   case OP_VEXT3:
5220     return DAG.getNode(ARMISD::VEXT, dl, VT,
5221                        OpLHS, OpRHS,
5222                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5223   case OP_VUZPL:
5224   case OP_VUZPR:
5225     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5226                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5227   case OP_VZIPL:
5228   case OP_VZIPR:
5229     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5230                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5231   case OP_VTRNL:
5232   case OP_VTRNR:
5233     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5234                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5235   }
5236 }
5237
5238 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5239                                        ArrayRef<int> ShuffleMask,
5240                                        SelectionDAG &DAG) {
5241   // Check to see if we can use the VTBL instruction.
5242   SDValue V1 = Op.getOperand(0);
5243   SDValue V2 = Op.getOperand(1);
5244   SDLoc DL(Op);
5245
5246   SmallVector<SDValue, 8> VTBLMask;
5247   for (ArrayRef<int>::iterator
5248          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5249     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5250
5251   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5252     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5253                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5254                                    &VTBLMask[0], 8));
5255
5256   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5257                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5258                                  &VTBLMask[0], 8));
5259 }
5260
5261 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5262                                                       SelectionDAG &DAG) {
5263   SDLoc DL(Op);
5264   SDValue OpLHS = Op.getOperand(0);
5265   EVT VT = OpLHS.getValueType();
5266
5267   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5268          "Expect an v8i16/v16i8 type");
5269   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5270   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5271   // extract the first 8 bytes into the top double word and the last 8 bytes
5272   // into the bottom double word. The v8i16 case is similar.
5273   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5274   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5275                      DAG.getConstant(ExtractNum, MVT::i32));
5276 }
5277
5278 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5279   SDValue V1 = Op.getOperand(0);
5280   SDValue V2 = Op.getOperand(1);
5281   SDLoc dl(Op);
5282   EVT VT = Op.getValueType();
5283   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5284
5285   // Convert shuffles that are directly supported on NEON to target-specific
5286   // DAG nodes, instead of keeping them as shuffles and matching them again
5287   // during code selection.  This is more efficient and avoids the possibility
5288   // of inconsistencies between legalization and selection.
5289   // FIXME: floating-point vectors should be canonicalized to integer vectors
5290   // of the same time so that they get CSEd properly.
5291   ArrayRef<int> ShuffleMask = SVN->getMask();
5292
5293   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5294   if (EltSize <= 32) {
5295     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5296       int Lane = SVN->getSplatIndex();
5297       // If this is undef splat, generate it via "just" vdup, if possible.
5298       if (Lane == -1) Lane = 0;
5299
5300       // Test if V1 is a SCALAR_TO_VECTOR.
5301       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5302         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5303       }
5304       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5305       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5306       // reaches it).
5307       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5308           !isa<ConstantSDNode>(V1.getOperand(0))) {
5309         bool IsScalarToVector = true;
5310         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5311           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5312             IsScalarToVector = false;
5313             break;
5314           }
5315         if (IsScalarToVector)
5316           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5317       }
5318       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5319                          DAG.getConstant(Lane, MVT::i32));
5320     }
5321
5322     bool ReverseVEXT;
5323     unsigned Imm;
5324     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5325       if (ReverseVEXT)
5326         std::swap(V1, V2);
5327       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5328                          DAG.getConstant(Imm, MVT::i32));
5329     }
5330
5331     if (isVREVMask(ShuffleMask, VT, 64))
5332       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5333     if (isVREVMask(ShuffleMask, VT, 32))
5334       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5335     if (isVREVMask(ShuffleMask, VT, 16))
5336       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5337
5338     if (V2->getOpcode() == ISD::UNDEF &&
5339         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5340       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5341                          DAG.getConstant(Imm, MVT::i32));
5342     }
5343
5344     // Check for Neon shuffles that modify both input vectors in place.
5345     // If both results are used, i.e., if there are two shuffles with the same
5346     // source operands and with masks corresponding to both results of one of
5347     // these operations, DAG memoization will ensure that a single node is
5348     // used for both shuffles.
5349     unsigned WhichResult;
5350     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5351       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5352                          V1, V2).getValue(WhichResult);
5353     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5354       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5355                          V1, V2).getValue(WhichResult);
5356     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5357       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5358                          V1, V2).getValue(WhichResult);
5359
5360     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5361       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5362                          V1, V1).getValue(WhichResult);
5363     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5364       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5365                          V1, V1).getValue(WhichResult);
5366     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5367       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5368                          V1, V1).getValue(WhichResult);
5369   }
5370
5371   // If the shuffle is not directly supported and it has 4 elements, use
5372   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5373   unsigned NumElts = VT.getVectorNumElements();
5374   if (NumElts == 4) {
5375     unsigned PFIndexes[4];
5376     for (unsigned i = 0; i != 4; ++i) {
5377       if (ShuffleMask[i] < 0)
5378         PFIndexes[i] = 8;
5379       else
5380         PFIndexes[i] = ShuffleMask[i];
5381     }
5382
5383     // Compute the index in the perfect shuffle table.
5384     unsigned PFTableIndex =
5385       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5386     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5387     unsigned Cost = (PFEntry >> 30);
5388
5389     if (Cost <= 4)
5390       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5391   }
5392
5393   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5394   if (EltSize >= 32) {
5395     // Do the expansion with floating-point types, since that is what the VFP
5396     // registers are defined to use, and since i64 is not legal.
5397     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5398     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5399     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5400     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5401     SmallVector<SDValue, 8> Ops;
5402     for (unsigned i = 0; i < NumElts; ++i) {
5403       if (ShuffleMask[i] < 0)
5404         Ops.push_back(DAG.getUNDEF(EltVT));
5405       else
5406         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5407                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5408                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5409                                                   MVT::i32)));
5410     }
5411     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5412     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5413   }
5414
5415   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5416     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5417
5418   if (VT == MVT::v8i8) {
5419     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5420     if (NewOp.getNode())
5421       return NewOp;
5422   }
5423
5424   return SDValue();
5425 }
5426
5427 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5428   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5429   SDValue Lane = Op.getOperand(2);
5430   if (!isa<ConstantSDNode>(Lane))
5431     return SDValue();
5432
5433   return Op;
5434 }
5435
5436 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5437   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5438   SDValue Lane = Op.getOperand(1);
5439   if (!isa<ConstantSDNode>(Lane))
5440     return SDValue();
5441
5442   SDValue Vec = Op.getOperand(0);
5443   if (Op.getValueType() == MVT::i32 &&
5444       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5445     SDLoc dl(Op);
5446     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5447   }
5448
5449   return Op;
5450 }
5451
5452 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5453   // The only time a CONCAT_VECTORS operation can have legal types is when
5454   // two 64-bit vectors are concatenated to a 128-bit vector.
5455   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5456          "unexpected CONCAT_VECTORS");
5457   SDLoc dl(Op);
5458   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5459   SDValue Op0 = Op.getOperand(0);
5460   SDValue Op1 = Op.getOperand(1);
5461   if (Op0.getOpcode() != ISD::UNDEF)
5462     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5463                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5464                       DAG.getIntPtrConstant(0));
5465   if (Op1.getOpcode() != ISD::UNDEF)
5466     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5467                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5468                       DAG.getIntPtrConstant(1));
5469   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5470 }
5471
5472 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5473 /// element has been zero/sign-extended, depending on the isSigned parameter,
5474 /// from an integer type half its size.
5475 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5476                                    bool isSigned) {
5477   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5478   EVT VT = N->getValueType(0);
5479   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5480     SDNode *BVN = N->getOperand(0).getNode();
5481     if (BVN->getValueType(0) != MVT::v4i32 ||
5482         BVN->getOpcode() != ISD::BUILD_VECTOR)
5483       return false;
5484     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5485     unsigned HiElt = 1 - LoElt;
5486     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5487     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5488     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5489     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5490     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5491       return false;
5492     if (isSigned) {
5493       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5494           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5495         return true;
5496     } else {
5497       if (Hi0->isNullValue() && Hi1->isNullValue())
5498         return true;
5499     }
5500     return false;
5501   }
5502
5503   if (N->getOpcode() != ISD::BUILD_VECTOR)
5504     return false;
5505
5506   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5507     SDNode *Elt = N->getOperand(i).getNode();
5508     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5509       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5510       unsigned HalfSize = EltSize / 2;
5511       if (isSigned) {
5512         if (!isIntN(HalfSize, C->getSExtValue()))
5513           return false;
5514       } else {
5515         if (!isUIntN(HalfSize, C->getZExtValue()))
5516           return false;
5517       }
5518       continue;
5519     }
5520     return false;
5521   }
5522
5523   return true;
5524 }
5525
5526 /// isSignExtended - Check if a node is a vector value that is sign-extended
5527 /// or a constant BUILD_VECTOR with sign-extended elements.
5528 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5529   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5530     return true;
5531   if (isExtendedBUILD_VECTOR(N, DAG, true))
5532     return true;
5533   return false;
5534 }
5535
5536 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5537 /// or a constant BUILD_VECTOR with zero-extended elements.
5538 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5539   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5540     return true;
5541   if (isExtendedBUILD_VECTOR(N, DAG, false))
5542     return true;
5543   return false;
5544 }
5545
5546 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5547   if (OrigVT.getSizeInBits() >= 64)
5548     return OrigVT;
5549
5550   assert(OrigVT.isSimple() && "Expecting a simple value type");
5551
5552   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5553   switch (OrigSimpleTy) {
5554   default: llvm_unreachable("Unexpected Vector Type");
5555   case MVT::v2i8:
5556   case MVT::v2i16:
5557      return MVT::v2i32;
5558   case MVT::v4i8:
5559     return  MVT::v4i16;
5560   }
5561 }
5562
5563 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5564 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5565 /// We insert the required extension here to get the vector to fill a D register.
5566 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5567                                             const EVT &OrigTy,
5568                                             const EVT &ExtTy,
5569                                             unsigned ExtOpcode) {
5570   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5571   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5572   // 64-bits we need to insert a new extension so that it will be 64-bits.
5573   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5574   if (OrigTy.getSizeInBits() >= 64)
5575     return N;
5576
5577   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5578   EVT NewVT = getExtensionTo64Bits(OrigTy);
5579
5580   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5581 }
5582
5583 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5584 /// does not do any sign/zero extension. If the original vector is less
5585 /// than 64 bits, an appropriate extension will be added after the load to
5586 /// reach a total size of 64 bits. We have to add the extension separately
5587 /// because ARM does not have a sign/zero extending load for vectors.
5588 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5589   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5590
5591   // The load already has the right type.
5592   if (ExtendedTy == LD->getMemoryVT())
5593     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5594                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5595                 LD->isNonTemporal(), LD->isInvariant(),
5596                 LD->getAlignment());
5597
5598   // We need to create a zextload/sextload. We cannot just create a load
5599   // followed by a zext/zext node because LowerMUL is also run during normal
5600   // operation legalization where we can't create illegal types.
5601   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5602                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5603                         LD->getMemoryVT(), LD->isVolatile(),
5604                         LD->isNonTemporal(), LD->getAlignment());
5605 }
5606
5607 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5608 /// extending load, or BUILD_VECTOR with extended elements, return the
5609 /// unextended value. The unextended vector should be 64 bits so that it can
5610 /// be used as an operand to a VMULL instruction. If the original vector size
5611 /// before extension is less than 64 bits we add a an extension to resize
5612 /// the vector to 64 bits.
5613 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5614   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5615     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5616                                         N->getOperand(0)->getValueType(0),
5617                                         N->getValueType(0),
5618                                         N->getOpcode());
5619
5620   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5621     return SkipLoadExtensionForVMULL(LD, DAG);
5622
5623   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5624   // have been legalized as a BITCAST from v4i32.
5625   if (N->getOpcode() == ISD::BITCAST) {
5626     SDNode *BVN = N->getOperand(0).getNode();
5627     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5628            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5629     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5630     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5631                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5632   }
5633   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5634   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5635   EVT VT = N->getValueType(0);
5636   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5637   unsigned NumElts = VT.getVectorNumElements();
5638   MVT TruncVT = MVT::getIntegerVT(EltSize);
5639   SmallVector<SDValue, 8> Ops;
5640   for (unsigned i = 0; i != NumElts; ++i) {
5641     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5642     const APInt &CInt = C->getAPIntValue();
5643     // Element types smaller than 32 bits are not legal, so use i32 elements.
5644     // The values are implicitly truncated so sext vs. zext doesn't matter.
5645     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5646   }
5647   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5648                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5649 }
5650
5651 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5652   unsigned Opcode = N->getOpcode();
5653   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5654     SDNode *N0 = N->getOperand(0).getNode();
5655     SDNode *N1 = N->getOperand(1).getNode();
5656     return N0->hasOneUse() && N1->hasOneUse() &&
5657       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5658   }
5659   return false;
5660 }
5661
5662 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5663   unsigned Opcode = N->getOpcode();
5664   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5665     SDNode *N0 = N->getOperand(0).getNode();
5666     SDNode *N1 = N->getOperand(1).getNode();
5667     return N0->hasOneUse() && N1->hasOneUse() &&
5668       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5669   }
5670   return false;
5671 }
5672
5673 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5674   // Multiplications are only custom-lowered for 128-bit vectors so that
5675   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5676   EVT VT = Op.getValueType();
5677   assert(VT.is128BitVector() && VT.isInteger() &&
5678          "unexpected type for custom-lowering ISD::MUL");
5679   SDNode *N0 = Op.getOperand(0).getNode();
5680   SDNode *N1 = Op.getOperand(1).getNode();
5681   unsigned NewOpc = 0;
5682   bool isMLA = false;
5683   bool isN0SExt = isSignExtended(N0, DAG);
5684   bool isN1SExt = isSignExtended(N1, DAG);
5685   if (isN0SExt && isN1SExt)
5686     NewOpc = ARMISD::VMULLs;
5687   else {
5688     bool isN0ZExt = isZeroExtended(N0, DAG);
5689     bool isN1ZExt = isZeroExtended(N1, DAG);
5690     if (isN0ZExt && isN1ZExt)
5691       NewOpc = ARMISD::VMULLu;
5692     else if (isN1SExt || isN1ZExt) {
5693       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5694       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5695       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5696         NewOpc = ARMISD::VMULLs;
5697         isMLA = true;
5698       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5699         NewOpc = ARMISD::VMULLu;
5700         isMLA = true;
5701       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5702         std::swap(N0, N1);
5703         NewOpc = ARMISD::VMULLu;
5704         isMLA = true;
5705       }
5706     }
5707
5708     if (!NewOpc) {
5709       if (VT == MVT::v2i64)
5710         // Fall through to expand this.  It is not legal.
5711         return SDValue();
5712       else
5713         // Other vector multiplications are legal.
5714         return Op;
5715     }
5716   }
5717
5718   // Legalize to a VMULL instruction.
5719   SDLoc DL(Op);
5720   SDValue Op0;
5721   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5722   if (!isMLA) {
5723     Op0 = SkipExtensionForVMULL(N0, DAG);
5724     assert(Op0.getValueType().is64BitVector() &&
5725            Op1.getValueType().is64BitVector() &&
5726            "unexpected types for extended operands to VMULL");
5727     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5728   }
5729
5730   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5731   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5732   //   vmull q0, d4, d6
5733   //   vmlal q0, d5, d6
5734   // is faster than
5735   //   vaddl q0, d4, d5
5736   //   vmovl q1, d6
5737   //   vmul  q0, q0, q1
5738   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5739   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5740   EVT Op1VT = Op1.getValueType();
5741   return DAG.getNode(N0->getOpcode(), DL, VT,
5742                      DAG.getNode(NewOpc, DL, VT,
5743                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5744                      DAG.getNode(NewOpc, DL, VT,
5745                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5746 }
5747
5748 static SDValue
5749 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5750   // Convert to float
5751   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5752   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5753   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5754   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5755   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5756   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5757   // Get reciprocal estimate.
5758   // float4 recip = vrecpeq_f32(yf);
5759   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5760                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5761   // Because char has a smaller range than uchar, we can actually get away
5762   // without any newton steps.  This requires that we use a weird bias
5763   // of 0xb000, however (again, this has been exhaustively tested).
5764   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5765   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5766   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5767   Y = DAG.getConstant(0xb000, MVT::i32);
5768   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5769   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5770   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5771   // Convert back to short.
5772   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5773   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5774   return X;
5775 }
5776
5777 static SDValue
5778 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5779   SDValue N2;
5780   // Convert to float.
5781   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5782   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5783   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5784   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5785   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5786   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5787
5788   // Use reciprocal estimate and one refinement step.
5789   // float4 recip = vrecpeq_f32(yf);
5790   // recip *= vrecpsq_f32(yf, recip);
5791   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5792                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5793   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5794                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5795                    N1, N2);
5796   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5797   // Because short has a smaller range than ushort, we can actually get away
5798   // with only a single newton step.  This requires that we use a weird bias
5799   // of 89, however (again, this has been exhaustively tested).
5800   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5801   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5802   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5803   N1 = DAG.getConstant(0x89, MVT::i32);
5804   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5805   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5806   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5807   // Convert back to integer and return.
5808   // return vmovn_s32(vcvt_s32_f32(result));
5809   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5810   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5811   return N0;
5812 }
5813
5814 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5815   EVT VT = Op.getValueType();
5816   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5817          "unexpected type for custom-lowering ISD::SDIV");
5818
5819   SDLoc dl(Op);
5820   SDValue N0 = Op.getOperand(0);
5821   SDValue N1 = Op.getOperand(1);
5822   SDValue N2, N3;
5823
5824   if (VT == MVT::v8i8) {
5825     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5826     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5827
5828     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5829                      DAG.getIntPtrConstant(4));
5830     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5831                      DAG.getIntPtrConstant(4));
5832     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5833                      DAG.getIntPtrConstant(0));
5834     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5835                      DAG.getIntPtrConstant(0));
5836
5837     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5838     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5839
5840     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5841     N0 = LowerCONCAT_VECTORS(N0, DAG);
5842
5843     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5844     return N0;
5845   }
5846   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5847 }
5848
5849 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5850   EVT VT = Op.getValueType();
5851   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5852          "unexpected type for custom-lowering ISD::UDIV");
5853
5854   SDLoc dl(Op);
5855   SDValue N0 = Op.getOperand(0);
5856   SDValue N1 = Op.getOperand(1);
5857   SDValue N2, N3;
5858
5859   if (VT == MVT::v8i8) {
5860     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5861     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5862
5863     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5864                      DAG.getIntPtrConstant(4));
5865     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5866                      DAG.getIntPtrConstant(4));
5867     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5868                      DAG.getIntPtrConstant(0));
5869     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5870                      DAG.getIntPtrConstant(0));
5871
5872     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5873     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5874
5875     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5876     N0 = LowerCONCAT_VECTORS(N0, DAG);
5877
5878     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5879                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5880                      N0);
5881     return N0;
5882   }
5883
5884   // v4i16 sdiv ... Convert to float.
5885   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5886   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5887   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5888   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5889   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5890   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5891
5892   // Use reciprocal estimate and two refinement steps.
5893   // float4 recip = vrecpeq_f32(yf);
5894   // recip *= vrecpsq_f32(yf, recip);
5895   // recip *= vrecpsq_f32(yf, recip);
5896   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5897                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5898   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5899                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5900                    BN1, N2);
5901   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5902   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5903                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5904                    BN1, N2);
5905   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5906   // Simply multiplying by the reciprocal estimate can leave us a few ulps
5907   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5908   // and that it will never cause us to return an answer too large).
5909   // float4 result = as_float4(as_int4(xf*recip) + 2);
5910   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5911   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5912   N1 = DAG.getConstant(2, MVT::i32);
5913   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5914   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5915   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5916   // Convert back to integer and return.
5917   // return vmovn_u32(vcvt_s32_f32(result));
5918   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5919   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5920   return N0;
5921 }
5922
5923 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5924   EVT VT = Op.getNode()->getValueType(0);
5925   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5926
5927   unsigned Opc;
5928   bool ExtraOp = false;
5929   switch (Op.getOpcode()) {
5930   default: llvm_unreachable("Invalid code");
5931   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5932   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5933   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5934   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5935   }
5936
5937   if (!ExtraOp)
5938     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5939                        Op.getOperand(1));
5940   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5941                      Op.getOperand(1), Op.getOperand(2));
5942 }
5943
5944 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5945   // Monotonic load/store is legal for all targets
5946   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5947     return Op;
5948
5949   // Aquire/Release load/store is not legal for targets without a
5950   // dmb or equivalent available.
5951   return SDValue();
5952 }
5953
5954 static void
5955 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5956                     SelectionDAG &DAG) {
5957   SDLoc dl(Node);
5958   assert (Node->getValueType(0) == MVT::i64 &&
5959           "Only know how to expand i64 atomics");
5960   AtomicSDNode *AN = cast<AtomicSDNode>(Node);
5961
5962   SmallVector<SDValue, 6> Ops;
5963   Ops.push_back(Node->getOperand(0)); // Chain
5964   Ops.push_back(Node->getOperand(1)); // Ptr
5965   for(unsigned i=2; i<Node->getNumOperands(); i++) {
5966     // Low part
5967     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5968                               Node->getOperand(i), DAG.getIntPtrConstant(0)));
5969     // High part
5970     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5971                               Node->getOperand(i), DAG.getIntPtrConstant(1)));
5972   }
5973   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5974   SDValue Result =
5975     DAG.getAtomic(Node->getOpcode(), dl, MVT::i64, Tys, Ops.data(), Ops.size(),
5976                   cast<MemSDNode>(Node)->getMemOperand(), AN->getOrdering(),
5977                   AN->getSynchScope());
5978   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5979   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5980   Results.push_back(Result.getValue(2));
5981 }
5982
5983 static void ReplaceREADCYCLECOUNTER(SDNode *N,
5984                                     SmallVectorImpl<SDValue> &Results,
5985                                     SelectionDAG &DAG,
5986                                     const ARMSubtarget *Subtarget) {
5987   SDLoc DL(N);
5988   SDValue Cycles32, OutChain;
5989
5990   if (Subtarget->hasPerfMon()) {
5991     // Under Power Management extensions, the cycle-count is:
5992     //    mrc p15, #0, <Rt>, c9, c13, #0
5993     SDValue Ops[] = { N->getOperand(0), // Chain
5994                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
5995                       DAG.getConstant(15, MVT::i32),
5996                       DAG.getConstant(0, MVT::i32),
5997                       DAG.getConstant(9, MVT::i32),
5998                       DAG.getConstant(13, MVT::i32),
5999                       DAG.getConstant(0, MVT::i32)
6000     };
6001
6002     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6003                            DAG.getVTList(MVT::i32, MVT::Other), &Ops[0],
6004                            array_lengthof(Ops));
6005     OutChain = Cycles32.getValue(1);
6006   } else {
6007     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6008     // there are older ARM CPUs that have implementation-specific ways of
6009     // obtaining this information (FIXME!).
6010     Cycles32 = DAG.getConstant(0, MVT::i32);
6011     OutChain = DAG.getEntryNode();
6012   }
6013
6014
6015   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6016                                  Cycles32, DAG.getConstant(0, MVT::i32));
6017   Results.push_back(Cycles64);
6018   Results.push_back(OutChain);
6019 }
6020
6021 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6022   switch (Op.getOpcode()) {
6023   default: llvm_unreachable("Don't know how to custom lower this!");
6024   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6025   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6026   case ISD::GlobalAddress:
6027     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
6028       LowerGlobalAddressELF(Op, DAG);
6029   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6030   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6031   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6032   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6033   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6034   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6035   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6036   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6037   case ISD::SINT_TO_FP:
6038   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6039   case ISD::FP_TO_SINT:
6040   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6041   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6042   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6043   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6044   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6045   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6046   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6047   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6048                                                                Subtarget);
6049   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6050   case ISD::SHL:
6051   case ISD::SRL:
6052   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6053   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6054   case ISD::SRL_PARTS:
6055   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6056   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6057   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6058   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6059   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6060   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6061   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6062   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6063   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6064   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6065   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6066   case ISD::MUL:           return LowerMUL(Op, DAG);
6067   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6068   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6069   case ISD::ADDC:
6070   case ISD::ADDE:
6071   case ISD::SUBC:
6072   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6073   case ISD::ATOMIC_LOAD:
6074   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6075   case ISD::SDIVREM:
6076   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6077   }
6078 }
6079
6080 /// ReplaceNodeResults - Replace the results of node with an illegal result
6081 /// type with new values built out of custom code.
6082 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6083                                            SmallVectorImpl<SDValue>&Results,
6084                                            SelectionDAG &DAG) const {
6085   SDValue Res;
6086   switch (N->getOpcode()) {
6087   default:
6088     llvm_unreachable("Don't know how to custom expand this!");
6089   case ISD::BITCAST:
6090     Res = ExpandBITCAST(N, DAG);
6091     break;
6092   case ISD::SIGN_EXTEND:
6093   case ISD::ZERO_EXTEND:
6094     Res = ExpandVectorExtension(N, DAG);
6095     break;
6096   case ISD::SRL:
6097   case ISD::SRA:
6098     Res = Expand64BitShift(N, DAG, Subtarget);
6099     break;
6100   case ISD::READCYCLECOUNTER:
6101     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6102     return;
6103   case ISD::ATOMIC_STORE:
6104   case ISD::ATOMIC_LOAD:
6105   case ISD::ATOMIC_LOAD_ADD:
6106   case ISD::ATOMIC_LOAD_AND:
6107   case ISD::ATOMIC_LOAD_NAND:
6108   case ISD::ATOMIC_LOAD_OR:
6109   case ISD::ATOMIC_LOAD_SUB:
6110   case ISD::ATOMIC_LOAD_XOR:
6111   case ISD::ATOMIC_SWAP:
6112   case ISD::ATOMIC_CMP_SWAP:
6113   case ISD::ATOMIC_LOAD_MIN:
6114   case ISD::ATOMIC_LOAD_UMIN:
6115   case ISD::ATOMIC_LOAD_MAX:
6116   case ISD::ATOMIC_LOAD_UMAX:
6117     ReplaceATOMIC_OP_64(N, Results, DAG);
6118     return;
6119   }
6120   if (Res.getNode())
6121     Results.push_back(Res);
6122 }
6123
6124 //===----------------------------------------------------------------------===//
6125 //                           ARM Scheduler Hooks
6126 //===----------------------------------------------------------------------===//
6127
6128 MachineBasicBlock *
6129 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
6130                                      MachineBasicBlock *BB,
6131                                      unsigned Size) const {
6132   unsigned dest    = MI->getOperand(0).getReg();
6133   unsigned ptr     = MI->getOperand(1).getReg();
6134   unsigned oldval  = MI->getOperand(2).getReg();
6135   unsigned newval  = MI->getOperand(3).getReg();
6136   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6137   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(4).getImm());
6138   DebugLoc dl = MI->getDebugLoc();
6139   bool isThumb2 = Subtarget->isThumb2();
6140
6141   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6142   unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
6143     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6144     (const TargetRegisterClass*)&ARM::GPRRegClass);
6145
6146   if (isThumb2) {
6147     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6148     MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
6149     MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
6150   }
6151
6152   unsigned ldrOpc, strOpc;
6153   getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6154
6155   MachineFunction *MF = BB->getParent();
6156   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6157   MachineFunction::iterator It = BB;
6158   ++It; // insert the new blocks after the current block
6159
6160   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6161   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6162   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6163   MF->insert(It, loop1MBB);
6164   MF->insert(It, loop2MBB);
6165   MF->insert(It, exitMBB);
6166
6167   // Transfer the remainder of BB and its successor edges to exitMBB.
6168   exitMBB->splice(exitMBB->begin(), BB,
6169                   llvm::next(MachineBasicBlock::iterator(MI)),
6170                   BB->end());
6171   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6172
6173   //  thisMBB:
6174   //   ...
6175   //   fallthrough --> loop1MBB
6176   BB->addSuccessor(loop1MBB);
6177
6178   // loop1MBB:
6179   //   ldrex dest, [ptr]
6180   //   cmp dest, oldval
6181   //   bne exitMBB
6182   BB = loop1MBB;
6183   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6184   if (ldrOpc == ARM::t2LDREX)
6185     MIB.addImm(0);
6186   AddDefaultPred(MIB);
6187   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6188                  .addReg(dest).addReg(oldval));
6189   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6190     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6191   BB->addSuccessor(loop2MBB);
6192   BB->addSuccessor(exitMBB);
6193
6194   // loop2MBB:
6195   //   strex scratch, newval, [ptr]
6196   //   cmp scratch, #0
6197   //   bne loop1MBB
6198   BB = loop2MBB;
6199   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
6200   if (strOpc == ARM::t2STREX)
6201     MIB.addImm(0);
6202   AddDefaultPred(MIB);
6203   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6204                  .addReg(scratch).addImm(0));
6205   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6206     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6207   BB->addSuccessor(loop1MBB);
6208   BB->addSuccessor(exitMBB);
6209
6210   //  exitMBB:
6211   //   ...
6212   BB = exitMBB;
6213
6214   MI->eraseFromParent();   // The instruction is gone now.
6215
6216   return BB;
6217 }
6218
6219 MachineBasicBlock *
6220 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6221                                     unsigned Size, unsigned BinOpcode) const {
6222   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6223   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6224
6225   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6226   MachineFunction *MF = BB->getParent();
6227   MachineFunction::iterator It = BB;
6228   ++It;
6229
6230   unsigned dest = MI->getOperand(0).getReg();
6231   unsigned ptr = MI->getOperand(1).getReg();
6232   unsigned incr = MI->getOperand(2).getReg();
6233   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6234   DebugLoc dl = MI->getDebugLoc();
6235   bool isThumb2 = Subtarget->isThumb2();
6236
6237   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6238   if (isThumb2) {
6239     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6240     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6241     MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6242   }
6243
6244   unsigned ldrOpc, strOpc;
6245   getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6246
6247   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6248   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6249   MF->insert(It, loopMBB);
6250   MF->insert(It, exitMBB);
6251
6252   // Transfer the remainder of BB and its successor edges to exitMBB.
6253   exitMBB->splice(exitMBB->begin(), BB,
6254                   llvm::next(MachineBasicBlock::iterator(MI)),
6255                   BB->end());
6256   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6257
6258   const TargetRegisterClass *TRC = isThumb2 ?
6259     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6260     (const TargetRegisterClass*)&ARM::GPRRegClass;
6261   unsigned scratch = MRI.createVirtualRegister(TRC);
6262   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
6263
6264   //  thisMBB:
6265   //   ...
6266   //   fallthrough --> loopMBB
6267   BB->addSuccessor(loopMBB);
6268
6269   //  loopMBB:
6270   //   ldrex dest, ptr
6271   //   <binop> scratch2, dest, incr
6272   //   strex scratch, scratch2, ptr
6273   //   cmp scratch, #0
6274   //   bne- loopMBB
6275   //   fallthrough --> exitMBB
6276   BB = loopMBB;
6277   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6278   if (ldrOpc == ARM::t2LDREX)
6279     MIB.addImm(0);
6280   AddDefaultPred(MIB);
6281   if (BinOpcode) {
6282     // operand order needs to go the other way for NAND
6283     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
6284       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6285                      addReg(incr).addReg(dest)).addReg(0);
6286     else
6287       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6288                      addReg(dest).addReg(incr)).addReg(0);
6289   }
6290
6291   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6292   if (strOpc == ARM::t2STREX)
6293     MIB.addImm(0);
6294   AddDefaultPred(MIB);
6295   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6296                  .addReg(scratch).addImm(0));
6297   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6298     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6299
6300   BB->addSuccessor(loopMBB);
6301   BB->addSuccessor(exitMBB);
6302
6303   //  exitMBB:
6304   //   ...
6305   BB = exitMBB;
6306
6307   MI->eraseFromParent();   // The instruction is gone now.
6308
6309   return BB;
6310 }
6311
6312 MachineBasicBlock *
6313 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
6314                                           MachineBasicBlock *BB,
6315                                           unsigned Size,
6316                                           bool signExtend,
6317                                           ARMCC::CondCodes Cond) const {
6318   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6319
6320   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6321   MachineFunction *MF = BB->getParent();
6322   MachineFunction::iterator It = BB;
6323   ++It;
6324
6325   unsigned dest = MI->getOperand(0).getReg();
6326   unsigned ptr = MI->getOperand(1).getReg();
6327   unsigned incr = MI->getOperand(2).getReg();
6328   unsigned oldval = dest;
6329   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6330   DebugLoc dl = MI->getDebugLoc();
6331   bool isThumb2 = Subtarget->isThumb2();
6332
6333   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6334   if (isThumb2) {
6335     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6336     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6337     MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6338   }
6339
6340   unsigned ldrOpc, strOpc, extendOpc;
6341   getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6342   switch (Size) {
6343   default: llvm_unreachable("unsupported size for AtomicBinaryMinMax!");
6344   case 1:
6345     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
6346     break;
6347   case 2:
6348     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
6349     break;
6350   case 4:
6351     extendOpc = 0;
6352     break;
6353   }
6354
6355   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6356   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6357   MF->insert(It, loopMBB);
6358   MF->insert(It, exitMBB);
6359
6360   // Transfer the remainder of BB and its successor edges to exitMBB.
6361   exitMBB->splice(exitMBB->begin(), BB,
6362                   llvm::next(MachineBasicBlock::iterator(MI)),
6363                   BB->end());
6364   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6365
6366   const TargetRegisterClass *TRC = isThumb2 ?
6367     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6368     (const TargetRegisterClass*)&ARM::GPRRegClass;
6369   unsigned scratch = MRI.createVirtualRegister(TRC);
6370   unsigned scratch2 = MRI.createVirtualRegister(TRC);
6371
6372   //  thisMBB:
6373   //   ...
6374   //   fallthrough --> loopMBB
6375   BB->addSuccessor(loopMBB);
6376
6377   //  loopMBB:
6378   //   ldrex dest, ptr
6379   //   (sign extend dest, if required)
6380   //   cmp dest, incr
6381   //   cmov.cond scratch2, incr, dest
6382   //   strex scratch, scratch2, ptr
6383   //   cmp scratch, #0
6384   //   bne- loopMBB
6385   //   fallthrough --> exitMBB
6386   BB = loopMBB;
6387   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6388   if (ldrOpc == ARM::t2LDREX)
6389     MIB.addImm(0);
6390   AddDefaultPred(MIB);
6391
6392   // Sign extend the value, if necessary.
6393   if (signExtend && extendOpc) {
6394     oldval = MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass
6395                                                 : &ARM::GPRnopcRegClass);
6396     if (!isThumb2)
6397       MRI.constrainRegClass(dest, &ARM::GPRnopcRegClass);
6398     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
6399                      .addReg(dest)
6400                      .addImm(0));
6401   }
6402
6403   // Build compare and cmov instructions.
6404   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6405                  .addReg(oldval).addReg(incr));
6406   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
6407          .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
6408
6409   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6410   if (strOpc == ARM::t2STREX)
6411     MIB.addImm(0);
6412   AddDefaultPred(MIB);
6413   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6414                  .addReg(scratch).addImm(0));
6415   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6416     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6417
6418   BB->addSuccessor(loopMBB);
6419   BB->addSuccessor(exitMBB);
6420
6421   //  exitMBB:
6422   //   ...
6423   BB = exitMBB;
6424
6425   MI->eraseFromParent();   // The instruction is gone now.
6426
6427   return BB;
6428 }
6429
6430 MachineBasicBlock *
6431 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
6432                                       unsigned Op1, unsigned Op2,
6433                                       bool NeedsCarry, bool IsCmpxchg,
6434                                       bool IsMinMax, ARMCC::CondCodes CC) const {
6435   // This also handles ATOMIC_SWAP and ATOMIC_STORE, indicated by Op1==0.
6436   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6437
6438   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6439   MachineFunction *MF = BB->getParent();
6440   MachineFunction::iterator It = BB;
6441   ++It;
6442
6443   bool isStore = (MI->getOpcode() == ARM::ATOMIC_STORE_I64);
6444   unsigned offset = (isStore ? -2 : 0);
6445   unsigned destlo = MI->getOperand(0).getReg();
6446   unsigned desthi = MI->getOperand(1).getReg();
6447   unsigned ptr = MI->getOperand(offset+2).getReg();
6448   unsigned vallo = MI->getOperand(offset+3).getReg();
6449   unsigned valhi = MI->getOperand(offset+4).getReg();
6450   unsigned OrdIdx = offset + (IsCmpxchg ? 7 : 5);
6451   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(OrdIdx).getImm());
6452   DebugLoc dl = MI->getDebugLoc();
6453   bool isThumb2 = Subtarget->isThumb2();
6454
6455   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6456   if (isThumb2) {
6457     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6458     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6459     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6460     MRI.constrainRegClass(vallo, &ARM::rGPRRegClass);
6461     MRI.constrainRegClass(valhi, &ARM::rGPRRegClass);
6462   }
6463
6464   unsigned ldrOpc, strOpc;
6465   getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6466
6467   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6468   MachineBasicBlock *contBB = 0, *cont2BB = 0;
6469   if (IsCmpxchg || IsMinMax)
6470     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
6471   if (IsCmpxchg)
6472     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
6473   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6474
6475   MF->insert(It, loopMBB);
6476   if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6477   if (IsCmpxchg) MF->insert(It, cont2BB);
6478   MF->insert(It, exitMBB);
6479
6480   // Transfer the remainder of BB and its successor edges to exitMBB.
6481   exitMBB->splice(exitMBB->begin(), BB,
6482                   llvm::next(MachineBasicBlock::iterator(MI)),
6483                   BB->end());
6484   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6485
6486   const TargetRegisterClass *TRC = isThumb2 ?
6487     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6488     (const TargetRegisterClass*)&ARM::GPRRegClass;
6489   unsigned storesuccess = MRI.createVirtualRegister(TRC);
6490
6491   //  thisMBB:
6492   //   ...
6493   //   fallthrough --> loopMBB
6494   BB->addSuccessor(loopMBB);
6495
6496   //  loopMBB:
6497   //   ldrexd r2, r3, ptr
6498   //   <binopa> r0, r2, incr
6499   //   <binopb> r1, r3, incr
6500   //   strexd storesuccess, r0, r1, ptr
6501   //   cmp storesuccess, #0
6502   //   bne- loopMBB
6503   //   fallthrough --> exitMBB
6504   BB = loopMBB;
6505
6506   if (!isStore) {
6507     // Load
6508     if (isThumb2) {
6509       AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6510                      .addReg(destlo, RegState::Define)
6511                      .addReg(desthi, RegState::Define)
6512                      .addReg(ptr));
6513     } else {
6514       unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6515       AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6516                      .addReg(GPRPair0, RegState::Define).addReg(ptr));
6517       // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
6518       BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6519         .addReg(GPRPair0, 0, ARM::gsub_0);
6520       BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6521         .addReg(GPRPair0, 0, ARM::gsub_1);
6522     }
6523   }
6524
6525   unsigned StoreLo, StoreHi;
6526   if (IsCmpxchg) {
6527     // Add early exit
6528     for (unsigned i = 0; i < 2; i++) {
6529       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6530                                                          ARM::CMPrr))
6531                      .addReg(i == 0 ? destlo : desthi)
6532                      .addReg(i == 0 ? vallo : valhi));
6533       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6534         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6535       BB->addSuccessor(exitMBB);
6536       BB->addSuccessor(i == 0 ? contBB : cont2BB);
6537       BB = (i == 0 ? contBB : cont2BB);
6538     }
6539
6540     // Copy to physregs for strexd
6541     StoreLo = MI->getOperand(5).getReg();
6542     StoreHi = MI->getOperand(6).getReg();
6543   } else if (Op1) {
6544     // Perform binary operation
6545     unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6546     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6547                    .addReg(destlo).addReg(vallo))
6548         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6549     unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6550     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6551                    .addReg(desthi).addReg(valhi))
6552         .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6553
6554     StoreLo = tmpRegLo;
6555     StoreHi = tmpRegHi;
6556   } else {
6557     // Copy to physregs for strexd
6558     StoreLo = vallo;
6559     StoreHi = valhi;
6560   }
6561   if (IsMinMax) {
6562     // Compare and branch to exit block.
6563     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6564       .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6565     BB->addSuccessor(exitMBB);
6566     BB->addSuccessor(contBB);
6567     BB = contBB;
6568     StoreLo = vallo;
6569     StoreHi = valhi;
6570   }
6571
6572   // Store
6573   if (isThumb2) {
6574     MRI.constrainRegClass(StoreLo, &ARM::rGPRRegClass);
6575     MRI.constrainRegClass(StoreHi, &ARM::rGPRRegClass);
6576     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6577                    .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6578   } else {
6579     // Marshal a pair...
6580     unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6581     unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6582     unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6583     BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6584     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6585       .addReg(UndefPair)
6586       .addReg(StoreLo)
6587       .addImm(ARM::gsub_0);
6588     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6589       .addReg(r1)
6590       .addReg(StoreHi)
6591       .addImm(ARM::gsub_1);
6592
6593     // ...and store it
6594     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6595                    .addReg(StorePair).addReg(ptr));
6596   }
6597   // Cmp+jump
6598   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6599                  .addReg(storesuccess).addImm(0));
6600   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6601     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6602
6603   BB->addSuccessor(loopMBB);
6604   BB->addSuccessor(exitMBB);
6605
6606   //  exitMBB:
6607   //   ...
6608   BB = exitMBB;
6609
6610   MI->eraseFromParent();   // The instruction is gone now.
6611
6612   return BB;
6613 }
6614
6615 MachineBasicBlock *
6616 ARMTargetLowering::EmitAtomicLoad64(MachineInstr *MI, MachineBasicBlock *BB) const {
6617
6618   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6619
6620   unsigned destlo = MI->getOperand(0).getReg();
6621   unsigned desthi = MI->getOperand(1).getReg();
6622   unsigned ptr = MI->getOperand(2).getReg();
6623   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6624   DebugLoc dl = MI->getDebugLoc();
6625   bool isThumb2 = Subtarget->isThumb2();
6626
6627   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6628   if (isThumb2) {
6629     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6630     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6631     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6632   }
6633   unsigned ldrOpc, strOpc;
6634   getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6635
6636   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(ldrOpc));
6637
6638   if (isThumb2) {
6639     MIB.addReg(destlo, RegState::Define)
6640        .addReg(desthi, RegState::Define)
6641        .addReg(ptr);
6642
6643   } else {
6644     unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6645     MIB.addReg(GPRPair0, RegState::Define).addReg(ptr);
6646
6647     // Copy GPRPair0 into dest.  (This copy will normally be coalesced.)
6648     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), destlo)
6649       .addReg(GPRPair0, 0, ARM::gsub_0);
6650     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), desthi)
6651       .addReg(GPRPair0, 0, ARM::gsub_1);
6652   }
6653   AddDefaultPred(MIB);
6654
6655   MI->eraseFromParent();   // The instruction is gone now.
6656
6657   return BB;
6658 }
6659
6660 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6661 /// registers the function context.
6662 void ARMTargetLowering::
6663 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6664                        MachineBasicBlock *DispatchBB, int FI) const {
6665   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6666   DebugLoc dl = MI->getDebugLoc();
6667   MachineFunction *MF = MBB->getParent();
6668   MachineRegisterInfo *MRI = &MF->getRegInfo();
6669   MachineConstantPool *MCP = MF->getConstantPool();
6670   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6671   const Function *F = MF->getFunction();
6672
6673   bool isThumb = Subtarget->isThumb();
6674   bool isThumb2 = Subtarget->isThumb2();
6675
6676   unsigned PCLabelId = AFI->createPICLabelUId();
6677   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6678   ARMConstantPoolValue *CPV =
6679     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6680   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6681
6682   const TargetRegisterClass *TRC = isThumb ?
6683     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6684     (const TargetRegisterClass*)&ARM::GPRRegClass;
6685
6686   // Grab constant pool and fixed stack memory operands.
6687   MachineMemOperand *CPMMO =
6688     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6689                              MachineMemOperand::MOLoad, 4, 4);
6690
6691   MachineMemOperand *FIMMOSt =
6692     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6693                              MachineMemOperand::MOStore, 4, 4);
6694
6695   // Load the address of the dispatch MBB into the jump buffer.
6696   if (isThumb2) {
6697     // Incoming value: jbuf
6698     //   ldr.n  r5, LCPI1_1
6699     //   orr    r5, r5, #1
6700     //   add    r5, pc
6701     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6702     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6703     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6704                    .addConstantPoolIndex(CPI)
6705                    .addMemOperand(CPMMO));
6706     // Set the low bit because of thumb mode.
6707     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6708     AddDefaultCC(
6709       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6710                      .addReg(NewVReg1, RegState::Kill)
6711                      .addImm(0x01)));
6712     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6713     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6714       .addReg(NewVReg2, RegState::Kill)
6715       .addImm(PCLabelId);
6716     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6717                    .addReg(NewVReg3, RegState::Kill)
6718                    .addFrameIndex(FI)
6719                    .addImm(36)  // &jbuf[1] :: pc
6720                    .addMemOperand(FIMMOSt));
6721   } else if (isThumb) {
6722     // Incoming value: jbuf
6723     //   ldr.n  r1, LCPI1_4
6724     //   add    r1, pc
6725     //   mov    r2, #1
6726     //   orrs   r1, r2
6727     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6728     //   str    r1, [r2]
6729     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6730     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6731                    .addConstantPoolIndex(CPI)
6732                    .addMemOperand(CPMMO));
6733     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6734     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6735       .addReg(NewVReg1, RegState::Kill)
6736       .addImm(PCLabelId);
6737     // Set the low bit because of thumb mode.
6738     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6739     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6740                    .addReg(ARM::CPSR, RegState::Define)
6741                    .addImm(1));
6742     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6743     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6744                    .addReg(ARM::CPSR, RegState::Define)
6745                    .addReg(NewVReg2, RegState::Kill)
6746                    .addReg(NewVReg3, RegState::Kill));
6747     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6748     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6749                    .addFrameIndex(FI)
6750                    .addImm(36)); // &jbuf[1] :: pc
6751     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6752                    .addReg(NewVReg4, RegState::Kill)
6753                    .addReg(NewVReg5, RegState::Kill)
6754                    .addImm(0)
6755                    .addMemOperand(FIMMOSt));
6756   } else {
6757     // Incoming value: jbuf
6758     //   ldr  r1, LCPI1_1
6759     //   add  r1, pc, r1
6760     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6761     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6762     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6763                    .addConstantPoolIndex(CPI)
6764                    .addImm(0)
6765                    .addMemOperand(CPMMO));
6766     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6767     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6768                    .addReg(NewVReg1, RegState::Kill)
6769                    .addImm(PCLabelId));
6770     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6771                    .addReg(NewVReg2, RegState::Kill)
6772                    .addFrameIndex(FI)
6773                    .addImm(36)  // &jbuf[1] :: pc
6774                    .addMemOperand(FIMMOSt));
6775   }
6776 }
6777
6778 MachineBasicBlock *ARMTargetLowering::
6779 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6780   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6781   DebugLoc dl = MI->getDebugLoc();
6782   MachineFunction *MF = MBB->getParent();
6783   MachineRegisterInfo *MRI = &MF->getRegInfo();
6784   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6785   MachineFrameInfo *MFI = MF->getFrameInfo();
6786   int FI = MFI->getFunctionContextIndex();
6787
6788   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6789     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6790     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6791
6792   // Get a mapping of the call site numbers to all of the landing pads they're
6793   // associated with.
6794   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6795   unsigned MaxCSNum = 0;
6796   MachineModuleInfo &MMI = MF->getMMI();
6797   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6798        ++BB) {
6799     if (!BB->isLandingPad()) continue;
6800
6801     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6802     // pad.
6803     for (MachineBasicBlock::iterator
6804            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6805       if (!II->isEHLabel()) continue;
6806
6807       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6808       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6809
6810       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6811       for (SmallVectorImpl<unsigned>::iterator
6812              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6813            CSI != CSE; ++CSI) {
6814         CallSiteNumToLPad[*CSI].push_back(BB);
6815         MaxCSNum = std::max(MaxCSNum, *CSI);
6816       }
6817       break;
6818     }
6819   }
6820
6821   // Get an ordered list of the machine basic blocks for the jump table.
6822   std::vector<MachineBasicBlock*> LPadList;
6823   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6824   LPadList.reserve(CallSiteNumToLPad.size());
6825   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6826     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6827     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6828            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6829       LPadList.push_back(*II);
6830       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6831     }
6832   }
6833
6834   assert(!LPadList.empty() &&
6835          "No landing pad destinations for the dispatch jump table!");
6836
6837   // Create the jump table and associated information.
6838   MachineJumpTableInfo *JTI =
6839     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6840   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6841   unsigned UId = AFI->createJumpTableUId();
6842   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6843
6844   // Create the MBBs for the dispatch code.
6845
6846   // Shove the dispatch's address into the return slot in the function context.
6847   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6848   DispatchBB->setIsLandingPad();
6849
6850   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6851   unsigned trap_opcode;
6852   if (Subtarget->isThumb())
6853     trap_opcode = ARM::tTRAP;
6854   else
6855     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6856
6857   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6858   DispatchBB->addSuccessor(TrapBB);
6859
6860   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6861   DispatchBB->addSuccessor(DispContBB);
6862
6863   // Insert and MBBs.
6864   MF->insert(MF->end(), DispatchBB);
6865   MF->insert(MF->end(), DispContBB);
6866   MF->insert(MF->end(), TrapBB);
6867
6868   // Insert code into the entry block that creates and registers the function
6869   // context.
6870   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6871
6872   MachineMemOperand *FIMMOLd =
6873     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6874                              MachineMemOperand::MOLoad |
6875                              MachineMemOperand::MOVolatile, 4, 4);
6876
6877   MachineInstrBuilder MIB;
6878   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6879
6880   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6881   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6882
6883   // Add a register mask with no preserved registers.  This results in all
6884   // registers being marked as clobbered.
6885   MIB.addRegMask(RI.getNoPreservedMask());
6886
6887   unsigned NumLPads = LPadList.size();
6888   if (Subtarget->isThumb2()) {
6889     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6890     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6891                    .addFrameIndex(FI)
6892                    .addImm(4)
6893                    .addMemOperand(FIMMOLd));
6894
6895     if (NumLPads < 256) {
6896       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6897                      .addReg(NewVReg1)
6898                      .addImm(LPadList.size()));
6899     } else {
6900       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6901       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6902                      .addImm(NumLPads & 0xFFFF));
6903
6904       unsigned VReg2 = VReg1;
6905       if ((NumLPads & 0xFFFF0000) != 0) {
6906         VReg2 = MRI->createVirtualRegister(TRC);
6907         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6908                        .addReg(VReg1)
6909                        .addImm(NumLPads >> 16));
6910       }
6911
6912       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6913                      .addReg(NewVReg1)
6914                      .addReg(VReg2));
6915     }
6916
6917     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6918       .addMBB(TrapBB)
6919       .addImm(ARMCC::HI)
6920       .addReg(ARM::CPSR);
6921
6922     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6923     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6924                    .addJumpTableIndex(MJTI)
6925                    .addImm(UId));
6926
6927     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6928     AddDefaultCC(
6929       AddDefaultPred(
6930         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6931         .addReg(NewVReg3, RegState::Kill)
6932         .addReg(NewVReg1)
6933         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6934
6935     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6936       .addReg(NewVReg4, RegState::Kill)
6937       .addReg(NewVReg1)
6938       .addJumpTableIndex(MJTI)
6939       .addImm(UId);
6940   } else if (Subtarget->isThumb()) {
6941     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6942     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6943                    .addFrameIndex(FI)
6944                    .addImm(1)
6945                    .addMemOperand(FIMMOLd));
6946
6947     if (NumLPads < 256) {
6948       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6949                      .addReg(NewVReg1)
6950                      .addImm(NumLPads));
6951     } else {
6952       MachineConstantPool *ConstantPool = MF->getConstantPool();
6953       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6954       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6955
6956       // MachineConstantPool wants an explicit alignment.
6957       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6958       if (Align == 0)
6959         Align = getDataLayout()->getTypeAllocSize(C->getType());
6960       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6961
6962       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6963       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6964                      .addReg(VReg1, RegState::Define)
6965                      .addConstantPoolIndex(Idx));
6966       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6967                      .addReg(NewVReg1)
6968                      .addReg(VReg1));
6969     }
6970
6971     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6972       .addMBB(TrapBB)
6973       .addImm(ARMCC::HI)
6974       .addReg(ARM::CPSR);
6975
6976     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6977     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6978                    .addReg(ARM::CPSR, RegState::Define)
6979                    .addReg(NewVReg1)
6980                    .addImm(2));
6981
6982     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6983     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6984                    .addJumpTableIndex(MJTI)
6985                    .addImm(UId));
6986
6987     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6988     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6989                    .addReg(ARM::CPSR, RegState::Define)
6990                    .addReg(NewVReg2, RegState::Kill)
6991                    .addReg(NewVReg3));
6992
6993     MachineMemOperand *JTMMOLd =
6994       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6995                                MachineMemOperand::MOLoad, 4, 4);
6996
6997     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6998     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6999                    .addReg(NewVReg4, RegState::Kill)
7000                    .addImm(0)
7001                    .addMemOperand(JTMMOLd));
7002
7003     unsigned NewVReg6 = NewVReg5;
7004     if (RelocM == Reloc::PIC_) {
7005       NewVReg6 = MRI->createVirtualRegister(TRC);
7006       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7007                      .addReg(ARM::CPSR, RegState::Define)
7008                      .addReg(NewVReg5, RegState::Kill)
7009                      .addReg(NewVReg3));
7010     }
7011
7012     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7013       .addReg(NewVReg6, RegState::Kill)
7014       .addJumpTableIndex(MJTI)
7015       .addImm(UId);
7016   } else {
7017     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7018     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7019                    .addFrameIndex(FI)
7020                    .addImm(4)
7021                    .addMemOperand(FIMMOLd));
7022
7023     if (NumLPads < 256) {
7024       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7025                      .addReg(NewVReg1)
7026                      .addImm(NumLPads));
7027     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7028       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7029       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7030                      .addImm(NumLPads & 0xFFFF));
7031
7032       unsigned VReg2 = VReg1;
7033       if ((NumLPads & 0xFFFF0000) != 0) {
7034         VReg2 = MRI->createVirtualRegister(TRC);
7035         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7036                        .addReg(VReg1)
7037                        .addImm(NumLPads >> 16));
7038       }
7039
7040       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7041                      .addReg(NewVReg1)
7042                      .addReg(VReg2));
7043     } else {
7044       MachineConstantPool *ConstantPool = MF->getConstantPool();
7045       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7046       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7047
7048       // MachineConstantPool wants an explicit alignment.
7049       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7050       if (Align == 0)
7051         Align = getDataLayout()->getTypeAllocSize(C->getType());
7052       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7053
7054       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7055       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7056                      .addReg(VReg1, RegState::Define)
7057                      .addConstantPoolIndex(Idx)
7058                      .addImm(0));
7059       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7060                      .addReg(NewVReg1)
7061                      .addReg(VReg1, RegState::Kill));
7062     }
7063
7064     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7065       .addMBB(TrapBB)
7066       .addImm(ARMCC::HI)
7067       .addReg(ARM::CPSR);
7068
7069     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7070     AddDefaultCC(
7071       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7072                      .addReg(NewVReg1)
7073                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7074     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7075     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7076                    .addJumpTableIndex(MJTI)
7077                    .addImm(UId));
7078
7079     MachineMemOperand *JTMMOLd =
7080       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7081                                MachineMemOperand::MOLoad, 4, 4);
7082     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7083     AddDefaultPred(
7084       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7085       .addReg(NewVReg3, RegState::Kill)
7086       .addReg(NewVReg4)
7087       .addImm(0)
7088       .addMemOperand(JTMMOLd));
7089
7090     if (RelocM == Reloc::PIC_) {
7091       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7092         .addReg(NewVReg5, RegState::Kill)
7093         .addReg(NewVReg4)
7094         .addJumpTableIndex(MJTI)
7095         .addImm(UId);
7096     } else {
7097       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7098         .addReg(NewVReg5, RegState::Kill)
7099         .addJumpTableIndex(MJTI)
7100         .addImm(UId);
7101     }
7102   }
7103
7104   // Add the jump table entries as successors to the MBB.
7105   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7106   for (std::vector<MachineBasicBlock*>::iterator
7107          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7108     MachineBasicBlock *CurMBB = *I;
7109     if (SeenMBBs.insert(CurMBB))
7110       DispContBB->addSuccessor(CurMBB);
7111   }
7112
7113   // N.B. the order the invoke BBs are processed in doesn't matter here.
7114   const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
7115   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7116   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
7117          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
7118     MachineBasicBlock *BB = *I;
7119
7120     // Remove the landing pad successor from the invoke block and replace it
7121     // with the new dispatch block.
7122     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7123                                                   BB->succ_end());
7124     while (!Successors.empty()) {
7125       MachineBasicBlock *SMBB = Successors.pop_back_val();
7126       if (SMBB->isLandingPad()) {
7127         BB->removeSuccessor(SMBB);
7128         MBBLPads.push_back(SMBB);
7129       }
7130     }
7131
7132     BB->addSuccessor(DispatchBB);
7133
7134     // Find the invoke call and mark all of the callee-saved registers as
7135     // 'implicit defined' so that they're spilled. This prevents code from
7136     // moving instructions to before the EH block, where they will never be
7137     // executed.
7138     for (MachineBasicBlock::reverse_iterator
7139            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7140       if (!II->isCall()) continue;
7141
7142       DenseMap<unsigned, bool> DefRegs;
7143       for (MachineInstr::mop_iterator
7144              OI = II->operands_begin(), OE = II->operands_end();
7145            OI != OE; ++OI) {
7146         if (!OI->isReg()) continue;
7147         DefRegs[OI->getReg()] = true;
7148       }
7149
7150       MachineInstrBuilder MIB(*MF, &*II);
7151
7152       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7153         unsigned Reg = SavedRegs[i];
7154         if (Subtarget->isThumb2() &&
7155             !ARM::tGPRRegClass.contains(Reg) &&
7156             !ARM::hGPRRegClass.contains(Reg))
7157           continue;
7158         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7159           continue;
7160         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7161           continue;
7162         if (!DefRegs[Reg])
7163           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7164       }
7165
7166       break;
7167     }
7168   }
7169
7170   // Mark all former landing pads as non-landing pads. The dispatch is the only
7171   // landing pad now.
7172   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7173          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7174     (*I)->setIsLandingPad(false);
7175
7176   // The instruction is gone now.
7177   MI->eraseFromParent();
7178
7179   return MBB;
7180 }
7181
7182 static
7183 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7184   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7185        E = MBB->succ_end(); I != E; ++I)
7186     if (*I != Succ)
7187       return *I;
7188   llvm_unreachable("Expecting a BB with two successors!");
7189 }
7190
7191 MachineBasicBlock *ARMTargetLowering::
7192 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
7193   // This pseudo instruction has 3 operands: dst, src, size
7194   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7195   // Otherwise, we will generate unrolled scalar copies.
7196   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7197   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7198   MachineFunction::iterator It = BB;
7199   ++It;
7200
7201   unsigned dest = MI->getOperand(0).getReg();
7202   unsigned src = MI->getOperand(1).getReg();
7203   unsigned SizeVal = MI->getOperand(2).getImm();
7204   unsigned Align = MI->getOperand(3).getImm();
7205   DebugLoc dl = MI->getDebugLoc();
7206
7207   bool isThumb2 = Subtarget->isThumb2();
7208   MachineFunction *MF = BB->getParent();
7209   MachineRegisterInfo &MRI = MF->getRegInfo();
7210   unsigned ldrOpc, strOpc, UnitSize = 0;
7211
7212   const TargetRegisterClass *TRC = isThumb2 ?
7213     (const TargetRegisterClass*)&ARM::tGPRRegClass :
7214     (const TargetRegisterClass*)&ARM::GPRRegClass;
7215   const TargetRegisterClass *TRC_Vec = 0;
7216
7217   if (Align & 1) {
7218     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
7219     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
7220     UnitSize = 1;
7221   } else if (Align & 2) {
7222     ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
7223     strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
7224     UnitSize = 2;
7225   } else {
7226     // Check whether we can use NEON instructions.
7227     if (!MF->getFunction()->getAttributes().
7228           hasAttribute(AttributeSet::FunctionIndex,
7229                        Attribute::NoImplicitFloat) &&
7230         Subtarget->hasNEON()) {
7231       if ((Align % 16 == 0) && SizeVal >= 16) {
7232         ldrOpc = ARM::VLD1q32wb_fixed;
7233         strOpc = ARM::VST1q32wb_fixed;
7234         UnitSize = 16;
7235         TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
7236       }
7237       else if ((Align % 8 == 0) && SizeVal >= 8) {
7238         ldrOpc = ARM::VLD1d32wb_fixed;
7239         strOpc = ARM::VST1d32wb_fixed;
7240         UnitSize = 8;
7241         TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
7242       }
7243     }
7244     // Can't use NEON instructions.
7245     if (UnitSize == 0) {
7246       ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
7247       strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
7248       UnitSize = 4;
7249     }
7250   }
7251
7252   unsigned BytesLeft = SizeVal % UnitSize;
7253   unsigned LoopSize = SizeVal - BytesLeft;
7254
7255   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7256     // Use LDR and STR to copy.
7257     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7258     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7259     unsigned srcIn = src;
7260     unsigned destIn = dest;
7261     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7262       unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
7263       unsigned srcOut = MRI.createVirtualRegister(TRC);
7264       unsigned destOut = MRI.createVirtualRegister(TRC);
7265       if (UnitSize >= 8) {
7266         AddDefaultPred(BuildMI(*BB, MI, dl,
7267           TII->get(ldrOpc), scratch)
7268           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
7269
7270         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7271           .addReg(destIn).addImm(0).addReg(scratch));
7272       } else if (isThumb2) {
7273         AddDefaultPred(BuildMI(*BB, MI, dl,
7274           TII->get(ldrOpc), scratch)
7275           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
7276
7277         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7278           .addReg(scratch).addReg(destIn)
7279           .addImm(UnitSize));
7280       } else {
7281         AddDefaultPred(BuildMI(*BB, MI, dl,
7282           TII->get(ldrOpc), scratch)
7283           .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
7284           .addImm(UnitSize));
7285
7286         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7287           .addReg(scratch).addReg(destIn)
7288           .addReg(0).addImm(UnitSize));
7289       }
7290       srcIn = srcOut;
7291       destIn = destOut;
7292     }
7293
7294     // Handle the leftover bytes with LDRB and STRB.
7295     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7296     // [destOut] = STRB_POST(scratch, destIn, 1)
7297     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
7298     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
7299     for (unsigned i = 0; i < BytesLeft; i++) {
7300       unsigned scratch = MRI.createVirtualRegister(TRC);
7301       unsigned srcOut = MRI.createVirtualRegister(TRC);
7302       unsigned destOut = MRI.createVirtualRegister(TRC);
7303       if (isThumb2) {
7304         AddDefaultPred(BuildMI(*BB, MI, dl,
7305           TII->get(ldrOpc),scratch)
7306           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
7307
7308         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7309           .addReg(scratch).addReg(destIn)
7310           .addReg(0).addImm(1));
7311       } else {
7312         AddDefaultPred(BuildMI(*BB, MI, dl,
7313           TII->get(ldrOpc),scratch)
7314           .addReg(srcOut, RegState::Define).addReg(srcIn)
7315           .addReg(0).addImm(1));
7316
7317         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7318           .addReg(scratch).addReg(destIn)
7319           .addReg(0).addImm(1));
7320       }
7321       srcIn = srcOut;
7322       destIn = destOut;
7323     }
7324     MI->eraseFromParent();   // The instruction is gone now.
7325     return BB;
7326   }
7327
7328   // Expand the pseudo op to a loop.
7329   // thisMBB:
7330   //   ...
7331   //   movw varEnd, # --> with thumb2
7332   //   movt varEnd, #
7333   //   ldrcp varEnd, idx --> without thumb2
7334   //   fallthrough --> loopMBB
7335   // loopMBB:
7336   //   PHI varPhi, varEnd, varLoop
7337   //   PHI srcPhi, src, srcLoop
7338   //   PHI destPhi, dst, destLoop
7339   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7340   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7341   //   subs varLoop, varPhi, #UnitSize
7342   //   bne loopMBB
7343   //   fallthrough --> exitMBB
7344   // exitMBB:
7345   //   epilogue to handle left-over bytes
7346   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7347   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7348   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7349   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7350   MF->insert(It, loopMBB);
7351   MF->insert(It, exitMBB);
7352
7353   // Transfer the remainder of BB and its successor edges to exitMBB.
7354   exitMBB->splice(exitMBB->begin(), BB,
7355                   llvm::next(MachineBasicBlock::iterator(MI)),
7356                   BB->end());
7357   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7358
7359   // Load an immediate to varEnd.
7360   unsigned varEnd = MRI.createVirtualRegister(TRC);
7361   if (isThumb2) {
7362     unsigned VReg1 = varEnd;
7363     if ((LoopSize & 0xFFFF0000) != 0)
7364       VReg1 = MRI.createVirtualRegister(TRC);
7365     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
7366                    .addImm(LoopSize & 0xFFFF));
7367
7368     if ((LoopSize & 0xFFFF0000) != 0)
7369       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7370                      .addReg(VReg1)
7371                      .addImm(LoopSize >> 16));
7372   } else {
7373     MachineConstantPool *ConstantPool = MF->getConstantPool();
7374     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7375     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7376
7377     // MachineConstantPool wants an explicit alignment.
7378     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7379     if (Align == 0)
7380       Align = getDataLayout()->getTypeAllocSize(C->getType());
7381     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7382
7383     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
7384                    .addReg(varEnd, RegState::Define)
7385                    .addConstantPoolIndex(Idx)
7386                    .addImm(0));
7387   }
7388   BB->addSuccessor(loopMBB);
7389
7390   // Generate the loop body:
7391   //   varPhi = PHI(varLoop, varEnd)
7392   //   srcPhi = PHI(srcLoop, src)
7393   //   destPhi = PHI(destLoop, dst)
7394   MachineBasicBlock *entryBB = BB;
7395   BB = loopMBB;
7396   unsigned varLoop = MRI.createVirtualRegister(TRC);
7397   unsigned varPhi = MRI.createVirtualRegister(TRC);
7398   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7399   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7400   unsigned destLoop = MRI.createVirtualRegister(TRC);
7401   unsigned destPhi = MRI.createVirtualRegister(TRC);
7402
7403   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7404     .addReg(varLoop).addMBB(loopMBB)
7405     .addReg(varEnd).addMBB(entryBB);
7406   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7407     .addReg(srcLoop).addMBB(loopMBB)
7408     .addReg(src).addMBB(entryBB);
7409   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7410     .addReg(destLoop).addMBB(loopMBB)
7411     .addReg(dest).addMBB(entryBB);
7412
7413   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7414   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7415   unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
7416   if (UnitSize >= 8) {
7417     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7418       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
7419
7420     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7421       .addReg(destPhi).addImm(0).addReg(scratch));
7422   } else if (isThumb2) {
7423     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7424       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
7425
7426     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7427       .addReg(scratch).addReg(destPhi)
7428       .addImm(UnitSize));
7429   } else {
7430     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7431       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
7432       .addImm(UnitSize));
7433
7434     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7435       .addReg(scratch).addReg(destPhi)
7436       .addReg(0).addImm(UnitSize));
7437   }
7438
7439   // Decrement loop variable by UnitSize.
7440   MachineInstrBuilder MIB = BuildMI(BB, dl,
7441     TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7442   AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7443   MIB->getOperand(5).setReg(ARM::CPSR);
7444   MIB->getOperand(5).setIsDef(true);
7445
7446   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7447     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7448
7449   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7450   BB->addSuccessor(loopMBB);
7451   BB->addSuccessor(exitMBB);
7452
7453   // Add epilogue to handle BytesLeft.
7454   BB = exitMBB;
7455   MachineInstr *StartOfExit = exitMBB->begin();
7456   ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
7457   strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
7458
7459   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7460   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7461   unsigned srcIn = srcLoop;
7462   unsigned destIn = destLoop;
7463   for (unsigned i = 0; i < BytesLeft; i++) {
7464     unsigned scratch = MRI.createVirtualRegister(TRC);
7465     unsigned srcOut = MRI.createVirtualRegister(TRC);
7466     unsigned destOut = MRI.createVirtualRegister(TRC);
7467     if (isThumb2) {
7468       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
7469         TII->get(ldrOpc),scratch)
7470         .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
7471
7472       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
7473         .addReg(scratch).addReg(destIn)
7474         .addImm(1));
7475     } else {
7476       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
7477         TII->get(ldrOpc),scratch)
7478         .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
7479
7480       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
7481         .addReg(scratch).addReg(destIn)
7482         .addReg(0).addImm(1));
7483     }
7484     srcIn = srcOut;
7485     destIn = destOut;
7486   }
7487
7488   MI->eraseFromParent();   // The instruction is gone now.
7489   return BB;
7490 }
7491
7492 MachineBasicBlock *
7493 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7494                                                MachineBasicBlock *BB) const {
7495   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7496   DebugLoc dl = MI->getDebugLoc();
7497   bool isThumb2 = Subtarget->isThumb2();
7498   switch (MI->getOpcode()) {
7499   default: {
7500     MI->dump();
7501     llvm_unreachable("Unexpected instr type to insert");
7502   }
7503   // The Thumb2 pre-indexed stores have the same MI operands, they just
7504   // define them differently in the .td files from the isel patterns, so
7505   // they need pseudos.
7506   case ARM::t2STR_preidx:
7507     MI->setDesc(TII->get(ARM::t2STR_PRE));
7508     return BB;
7509   case ARM::t2STRB_preidx:
7510     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7511     return BB;
7512   case ARM::t2STRH_preidx:
7513     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7514     return BB;
7515
7516   case ARM::STRi_preidx:
7517   case ARM::STRBi_preidx: {
7518     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7519       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7520     // Decode the offset.
7521     unsigned Offset = MI->getOperand(4).getImm();
7522     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7523     Offset = ARM_AM::getAM2Offset(Offset);
7524     if (isSub)
7525       Offset = -Offset;
7526
7527     MachineMemOperand *MMO = *MI->memoperands_begin();
7528     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7529       .addOperand(MI->getOperand(0))  // Rn_wb
7530       .addOperand(MI->getOperand(1))  // Rt
7531       .addOperand(MI->getOperand(2))  // Rn
7532       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7533       .addOperand(MI->getOperand(5))  // pred
7534       .addOperand(MI->getOperand(6))
7535       .addMemOperand(MMO);
7536     MI->eraseFromParent();
7537     return BB;
7538   }
7539   case ARM::STRr_preidx:
7540   case ARM::STRBr_preidx:
7541   case ARM::STRH_preidx: {
7542     unsigned NewOpc;
7543     switch (MI->getOpcode()) {
7544     default: llvm_unreachable("unexpected opcode!");
7545     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7546     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7547     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7548     }
7549     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7550     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7551       MIB.addOperand(MI->getOperand(i));
7552     MI->eraseFromParent();
7553     return BB;
7554   }
7555   case ARM::ATOMIC_LOAD_ADD_I8:
7556      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7557   case ARM::ATOMIC_LOAD_ADD_I16:
7558      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7559   case ARM::ATOMIC_LOAD_ADD_I32:
7560      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7561
7562   case ARM::ATOMIC_LOAD_AND_I8:
7563      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7564   case ARM::ATOMIC_LOAD_AND_I16:
7565      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7566   case ARM::ATOMIC_LOAD_AND_I32:
7567      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7568
7569   case ARM::ATOMIC_LOAD_OR_I8:
7570      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7571   case ARM::ATOMIC_LOAD_OR_I16:
7572      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7573   case ARM::ATOMIC_LOAD_OR_I32:
7574      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7575
7576   case ARM::ATOMIC_LOAD_XOR_I8:
7577      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7578   case ARM::ATOMIC_LOAD_XOR_I16:
7579      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7580   case ARM::ATOMIC_LOAD_XOR_I32:
7581      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7582
7583   case ARM::ATOMIC_LOAD_NAND_I8:
7584      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7585   case ARM::ATOMIC_LOAD_NAND_I16:
7586      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7587   case ARM::ATOMIC_LOAD_NAND_I32:
7588      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7589
7590   case ARM::ATOMIC_LOAD_SUB_I8:
7591      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7592   case ARM::ATOMIC_LOAD_SUB_I16:
7593      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7594   case ARM::ATOMIC_LOAD_SUB_I32:
7595      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7596
7597   case ARM::ATOMIC_LOAD_MIN_I8:
7598      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7599   case ARM::ATOMIC_LOAD_MIN_I16:
7600      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7601   case ARM::ATOMIC_LOAD_MIN_I32:
7602      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7603
7604   case ARM::ATOMIC_LOAD_MAX_I8:
7605      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7606   case ARM::ATOMIC_LOAD_MAX_I16:
7607      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7608   case ARM::ATOMIC_LOAD_MAX_I32:
7609      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7610
7611   case ARM::ATOMIC_LOAD_UMIN_I8:
7612      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7613   case ARM::ATOMIC_LOAD_UMIN_I16:
7614      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7615   case ARM::ATOMIC_LOAD_UMIN_I32:
7616      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7617
7618   case ARM::ATOMIC_LOAD_UMAX_I8:
7619      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7620   case ARM::ATOMIC_LOAD_UMAX_I16:
7621      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7622   case ARM::ATOMIC_LOAD_UMAX_I32:
7623      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7624
7625   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
7626   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7627   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7628
7629   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
7630   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7631   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7632
7633   case ARM::ATOMIC_LOAD_I64:
7634     return EmitAtomicLoad64(MI, BB);
7635
7636   case ARM::ATOMIC_LOAD_ADD_I64:
7637     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7638                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7639                               /*NeedsCarry*/ true);
7640   case ARM::ATOMIC_LOAD_SUB_I64:
7641     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7642                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7643                               /*NeedsCarry*/ true);
7644   case ARM::ATOMIC_LOAD_OR_I64:
7645     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7646                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7647   case ARM::ATOMIC_LOAD_XOR_I64:
7648     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7649                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7650   case ARM::ATOMIC_LOAD_AND_I64:
7651     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7652                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7653   case ARM::ATOMIC_STORE_I64:
7654   case ARM::ATOMIC_SWAP_I64:
7655     return EmitAtomicBinary64(MI, BB, 0, 0, false);
7656   case ARM::ATOMIC_CMP_SWAP_I64:
7657     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7658                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7659                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7660   case ARM::ATOMIC_LOAD_MIN_I64:
7661     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7662                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7663                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7664                               /*IsMinMax*/ true, ARMCC::LT);
7665   case ARM::ATOMIC_LOAD_MAX_I64:
7666     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7667                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7668                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7669                               /*IsMinMax*/ true, ARMCC::GE);
7670   case ARM::ATOMIC_LOAD_UMIN_I64:
7671     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7672                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7673                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7674                               /*IsMinMax*/ true, ARMCC::LO);
7675   case ARM::ATOMIC_LOAD_UMAX_I64:
7676     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7677                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7678                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7679                               /*IsMinMax*/ true, ARMCC::HS);
7680
7681   case ARM::tMOVCCr_pseudo: {
7682     // To "insert" a SELECT_CC instruction, we actually have to insert the
7683     // diamond control-flow pattern.  The incoming instruction knows the
7684     // destination vreg to set, the condition code register to branch on, the
7685     // true/false values to select between, and a branch opcode to use.
7686     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7687     MachineFunction::iterator It = BB;
7688     ++It;
7689
7690     //  thisMBB:
7691     //  ...
7692     //   TrueVal = ...
7693     //   cmpTY ccX, r1, r2
7694     //   bCC copy1MBB
7695     //   fallthrough --> copy0MBB
7696     MachineBasicBlock *thisMBB  = BB;
7697     MachineFunction *F = BB->getParent();
7698     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7699     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7700     F->insert(It, copy0MBB);
7701     F->insert(It, sinkMBB);
7702
7703     // Transfer the remainder of BB and its successor edges to sinkMBB.
7704     sinkMBB->splice(sinkMBB->begin(), BB,
7705                     llvm::next(MachineBasicBlock::iterator(MI)),
7706                     BB->end());
7707     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7708
7709     BB->addSuccessor(copy0MBB);
7710     BB->addSuccessor(sinkMBB);
7711
7712     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7713       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7714
7715     //  copy0MBB:
7716     //   %FalseValue = ...
7717     //   # fallthrough to sinkMBB
7718     BB = copy0MBB;
7719
7720     // Update machine-CFG edges
7721     BB->addSuccessor(sinkMBB);
7722
7723     //  sinkMBB:
7724     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7725     //  ...
7726     BB = sinkMBB;
7727     BuildMI(*BB, BB->begin(), dl,
7728             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7729       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7730       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7731
7732     MI->eraseFromParent();   // The pseudo instruction is gone now.
7733     return BB;
7734   }
7735
7736   case ARM::BCCi64:
7737   case ARM::BCCZi64: {
7738     // If there is an unconditional branch to the other successor, remove it.
7739     BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
7740
7741     // Compare both parts that make up the double comparison separately for
7742     // equality.
7743     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7744
7745     unsigned LHS1 = MI->getOperand(1).getReg();
7746     unsigned LHS2 = MI->getOperand(2).getReg();
7747     if (RHSisZero) {
7748       AddDefaultPred(BuildMI(BB, dl,
7749                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7750                      .addReg(LHS1).addImm(0));
7751       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7752         .addReg(LHS2).addImm(0)
7753         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7754     } else {
7755       unsigned RHS1 = MI->getOperand(3).getReg();
7756       unsigned RHS2 = MI->getOperand(4).getReg();
7757       AddDefaultPred(BuildMI(BB, dl,
7758                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7759                      .addReg(LHS1).addReg(RHS1));
7760       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7761         .addReg(LHS2).addReg(RHS2)
7762         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7763     }
7764
7765     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7766     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7767     if (MI->getOperand(0).getImm() == ARMCC::NE)
7768       std::swap(destMBB, exitMBB);
7769
7770     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7771       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7772     if (isThumb2)
7773       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7774     else
7775       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7776
7777     MI->eraseFromParent();   // The pseudo instruction is gone now.
7778     return BB;
7779   }
7780
7781   case ARM::Int_eh_sjlj_setjmp:
7782   case ARM::Int_eh_sjlj_setjmp_nofp:
7783   case ARM::tInt_eh_sjlj_setjmp:
7784   case ARM::t2Int_eh_sjlj_setjmp:
7785   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7786     EmitSjLjDispatchBlock(MI, BB);
7787     return BB;
7788
7789   case ARM::ABS:
7790   case ARM::t2ABS: {
7791     // To insert an ABS instruction, we have to insert the
7792     // diamond control-flow pattern.  The incoming instruction knows the
7793     // source vreg to test against 0, the destination vreg to set,
7794     // the condition code register to branch on, the
7795     // true/false values to select between, and a branch opcode to use.
7796     // It transforms
7797     //     V1 = ABS V0
7798     // into
7799     //     V2 = MOVS V0
7800     //     BCC                      (branch to SinkBB if V0 >= 0)
7801     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7802     //     SinkBB: V1 = PHI(V2, V3)
7803     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7804     MachineFunction::iterator BBI = BB;
7805     ++BBI;
7806     MachineFunction *Fn = BB->getParent();
7807     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7808     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7809     Fn->insert(BBI, RSBBB);
7810     Fn->insert(BBI, SinkBB);
7811
7812     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7813     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7814     bool isThumb2 = Subtarget->isThumb2();
7815     MachineRegisterInfo &MRI = Fn->getRegInfo();
7816     // In Thumb mode S must not be specified if source register is the SP or
7817     // PC and if destination register is the SP, so restrict register class
7818     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7819       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7820       (const TargetRegisterClass*)&ARM::GPRRegClass);
7821
7822     // Transfer the remainder of BB and its successor edges to sinkMBB.
7823     SinkBB->splice(SinkBB->begin(), BB,
7824       llvm::next(MachineBasicBlock::iterator(MI)),
7825       BB->end());
7826     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7827
7828     BB->addSuccessor(RSBBB);
7829     BB->addSuccessor(SinkBB);
7830
7831     // fall through to SinkMBB
7832     RSBBB->addSuccessor(SinkBB);
7833
7834     // insert a cmp at the end of BB
7835     AddDefaultPred(BuildMI(BB, dl,
7836                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7837                    .addReg(ABSSrcReg).addImm(0));
7838
7839     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7840     BuildMI(BB, dl,
7841       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7842       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7843
7844     // insert rsbri in RSBBB
7845     // Note: BCC and rsbri will be converted into predicated rsbmi
7846     // by if-conversion pass
7847     BuildMI(*RSBBB, RSBBB->begin(), dl,
7848       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7849       .addReg(ABSSrcReg, RegState::Kill)
7850       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7851
7852     // insert PHI in SinkBB,
7853     // reuse ABSDstReg to not change uses of ABS instruction
7854     BuildMI(*SinkBB, SinkBB->begin(), dl,
7855       TII->get(ARM::PHI), ABSDstReg)
7856       .addReg(NewRsbDstReg).addMBB(RSBBB)
7857       .addReg(ABSSrcReg).addMBB(BB);
7858
7859     // remove ABS instruction
7860     MI->eraseFromParent();
7861
7862     // return last added BB
7863     return SinkBB;
7864   }
7865   case ARM::COPY_STRUCT_BYVAL_I32:
7866     ++NumLoopByVals;
7867     return EmitStructByval(MI, BB);
7868   }
7869 }
7870
7871 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7872                                                       SDNode *Node) const {
7873   if (!MI->hasPostISelHook()) {
7874     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7875            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7876     return;
7877   }
7878
7879   const MCInstrDesc *MCID = &MI->getDesc();
7880   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7881   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7882   // operand is still set to noreg. If needed, set the optional operand's
7883   // register to CPSR, and remove the redundant implicit def.
7884   //
7885   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7886
7887   // Rename pseudo opcodes.
7888   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7889   if (NewOpc) {
7890     const ARMBaseInstrInfo *TII =
7891       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7892     MCID = &TII->get(NewOpc);
7893
7894     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7895            "converted opcode should be the same except for cc_out");
7896
7897     MI->setDesc(*MCID);
7898
7899     // Add the optional cc_out operand
7900     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7901   }
7902   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7903
7904   // Any ARM instruction that sets the 's' bit should specify an optional
7905   // "cc_out" operand in the last operand position.
7906   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7907     assert(!NewOpc && "Optional cc_out operand required");
7908     return;
7909   }
7910   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7911   // since we already have an optional CPSR def.
7912   bool definesCPSR = false;
7913   bool deadCPSR = false;
7914   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7915        i != e; ++i) {
7916     const MachineOperand &MO = MI->getOperand(i);
7917     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7918       definesCPSR = true;
7919       if (MO.isDead())
7920         deadCPSR = true;
7921       MI->RemoveOperand(i);
7922       break;
7923     }
7924   }
7925   if (!definesCPSR) {
7926     assert(!NewOpc && "Optional cc_out operand required");
7927     return;
7928   }
7929   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7930   if (deadCPSR) {
7931     assert(!MI->getOperand(ccOutIdx).getReg() &&
7932            "expect uninitialized optional cc_out operand");
7933     return;
7934   }
7935
7936   // If this instruction was defined with an optional CPSR def and its dag node
7937   // had a live implicit CPSR def, then activate the optional CPSR def.
7938   MachineOperand &MO = MI->getOperand(ccOutIdx);
7939   MO.setReg(ARM::CPSR);
7940   MO.setIsDef(true);
7941 }
7942
7943 //===----------------------------------------------------------------------===//
7944 //                           ARM Optimization Hooks
7945 //===----------------------------------------------------------------------===//
7946
7947 // Helper function that checks if N is a null or all ones constant.
7948 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7949   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7950   if (!C)
7951     return false;
7952   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7953 }
7954
7955 // Return true if N is conditionally 0 or all ones.
7956 // Detects these expressions where cc is an i1 value:
7957 //
7958 //   (select cc 0, y)   [AllOnes=0]
7959 //   (select cc y, 0)   [AllOnes=0]
7960 //   (zext cc)          [AllOnes=0]
7961 //   (sext cc)          [AllOnes=0/1]
7962 //   (select cc -1, y)  [AllOnes=1]
7963 //   (select cc y, -1)  [AllOnes=1]
7964 //
7965 // Invert is set when N is the null/all ones constant when CC is false.
7966 // OtherOp is set to the alternative value of N.
7967 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7968                                        SDValue &CC, bool &Invert,
7969                                        SDValue &OtherOp,
7970                                        SelectionDAG &DAG) {
7971   switch (N->getOpcode()) {
7972   default: return false;
7973   case ISD::SELECT: {
7974     CC = N->getOperand(0);
7975     SDValue N1 = N->getOperand(1);
7976     SDValue N2 = N->getOperand(2);
7977     if (isZeroOrAllOnes(N1, AllOnes)) {
7978       Invert = false;
7979       OtherOp = N2;
7980       return true;
7981     }
7982     if (isZeroOrAllOnes(N2, AllOnes)) {
7983       Invert = true;
7984       OtherOp = N1;
7985       return true;
7986     }
7987     return false;
7988   }
7989   case ISD::ZERO_EXTEND:
7990     // (zext cc) can never be the all ones value.
7991     if (AllOnes)
7992       return false;
7993     // Fall through.
7994   case ISD::SIGN_EXTEND: {
7995     EVT VT = N->getValueType(0);
7996     CC = N->getOperand(0);
7997     if (CC.getValueType() != MVT::i1)
7998       return false;
7999     Invert = !AllOnes;
8000     if (AllOnes)
8001       // When looking for an AllOnes constant, N is an sext, and the 'other'
8002       // value is 0.
8003       OtherOp = DAG.getConstant(0, VT);
8004     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8005       // When looking for a 0 constant, N can be zext or sext.
8006       OtherOp = DAG.getConstant(1, VT);
8007     else
8008       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
8009     return true;
8010   }
8011   }
8012 }
8013
8014 // Combine a constant select operand into its use:
8015 //
8016 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
8017 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
8018 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
8019 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
8020 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
8021 //
8022 // The transform is rejected if the select doesn't have a constant operand that
8023 // is null, or all ones when AllOnes is set.
8024 //
8025 // Also recognize sext/zext from i1:
8026 //
8027 //   (add (zext cc), x) -> (select cc (add x, 1), x)
8028 //   (add (sext cc), x) -> (select cc (add x, -1), x)
8029 //
8030 // These transformations eventually create predicated instructions.
8031 //
8032 // @param N       The node to transform.
8033 // @param Slct    The N operand that is a select.
8034 // @param OtherOp The other N operand (x above).
8035 // @param DCI     Context.
8036 // @param AllOnes Require the select constant to be all ones instead of null.
8037 // @returns The new node, or SDValue() on failure.
8038 static
8039 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8040                             TargetLowering::DAGCombinerInfo &DCI,
8041                             bool AllOnes = false) {
8042   SelectionDAG &DAG = DCI.DAG;
8043   EVT VT = N->getValueType(0);
8044   SDValue NonConstantVal;
8045   SDValue CCOp;
8046   bool SwapSelectOps;
8047   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8048                                   NonConstantVal, DAG))
8049     return SDValue();
8050
8051   // Slct is now know to be the desired identity constant when CC is true.
8052   SDValue TrueVal = OtherOp;
8053   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8054                                  OtherOp, NonConstantVal);
8055   // Unless SwapSelectOps says CC should be false.
8056   if (SwapSelectOps)
8057     std::swap(TrueVal, FalseVal);
8058
8059   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8060                      CCOp, TrueVal, FalseVal);
8061 }
8062
8063 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8064 static
8065 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8066                                        TargetLowering::DAGCombinerInfo &DCI) {
8067   SDValue N0 = N->getOperand(0);
8068   SDValue N1 = N->getOperand(1);
8069   if (N0.getNode()->hasOneUse()) {
8070     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8071     if (Result.getNode())
8072       return Result;
8073   }
8074   if (N1.getNode()->hasOneUse()) {
8075     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8076     if (Result.getNode())
8077       return Result;
8078   }
8079   return SDValue();
8080 }
8081
8082 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8083 // (only after legalization).
8084 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8085                                  TargetLowering::DAGCombinerInfo &DCI,
8086                                  const ARMSubtarget *Subtarget) {
8087
8088   // Only perform optimization if after legalize, and if NEON is available. We
8089   // also expected both operands to be BUILD_VECTORs.
8090   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8091       || N0.getOpcode() != ISD::BUILD_VECTOR
8092       || N1.getOpcode() != ISD::BUILD_VECTOR)
8093     return SDValue();
8094
8095   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8096   EVT VT = N->getValueType(0);
8097   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8098     return SDValue();
8099
8100   // Check that the vector operands are of the right form.
8101   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8102   // operands, where N is the size of the formed vector.
8103   // Each EXTRACT_VECTOR should have the same input vector and odd or even
8104   // index such that we have a pair wise add pattern.
8105
8106   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8107   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8108     return SDValue();
8109   SDValue Vec = N0->getOperand(0)->getOperand(0);
8110   SDNode *V = Vec.getNode();
8111   unsigned nextIndex = 0;
8112
8113   // For each operands to the ADD which are BUILD_VECTORs,
8114   // check to see if each of their operands are an EXTRACT_VECTOR with
8115   // the same vector and appropriate index.
8116   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8117     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8118         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8119
8120       SDValue ExtVec0 = N0->getOperand(i);
8121       SDValue ExtVec1 = N1->getOperand(i);
8122
8123       // First operand is the vector, verify its the same.
8124       if (V != ExtVec0->getOperand(0).getNode() ||
8125           V != ExtVec1->getOperand(0).getNode())
8126         return SDValue();
8127
8128       // Second is the constant, verify its correct.
8129       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8130       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8131
8132       // For the constant, we want to see all the even or all the odd.
8133       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8134           || C1->getZExtValue() != nextIndex+1)
8135         return SDValue();
8136
8137       // Increment index.
8138       nextIndex+=2;
8139     } else
8140       return SDValue();
8141   }
8142
8143   // Create VPADDL node.
8144   SelectionDAG &DAG = DCI.DAG;
8145   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8146
8147   // Build operand list.
8148   SmallVector<SDValue, 8> Ops;
8149   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
8150                                 TLI.getPointerTy()));
8151
8152   // Input is the vector.
8153   Ops.push_back(Vec);
8154
8155   // Get widened type and narrowed type.
8156   MVT widenType;
8157   unsigned numElem = VT.getVectorNumElements();
8158   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8159     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8160     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8161     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8162     default:
8163       llvm_unreachable("Invalid vector element type for padd optimization.");
8164   }
8165
8166   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
8167                             widenType, &Ops[0], Ops.size());
8168   return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, tmp);
8169 }
8170
8171 static SDValue findMUL_LOHI(SDValue V) {
8172   if (V->getOpcode() == ISD::UMUL_LOHI ||
8173       V->getOpcode() == ISD::SMUL_LOHI)
8174     return V;
8175   return SDValue();
8176 }
8177
8178 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8179                                      TargetLowering::DAGCombinerInfo &DCI,
8180                                      const ARMSubtarget *Subtarget) {
8181
8182   if (Subtarget->isThumb1Only()) return SDValue();
8183
8184   // Only perform the checks after legalize when the pattern is available.
8185   if (DCI.isBeforeLegalize()) return SDValue();
8186
8187   // Look for multiply add opportunities.
8188   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8189   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8190   // a glue link from the first add to the second add.
8191   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8192   // a S/UMLAL instruction.
8193   //          loAdd   UMUL_LOHI
8194   //            \    / :lo    \ :hi
8195   //             \  /          \          [no multiline comment]
8196   //              ADDC         |  hiAdd
8197   //                 \ :glue  /  /
8198   //                  \      /  /
8199   //                    ADDE
8200   //
8201   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8202   SDValue AddcOp0 = AddcNode->getOperand(0);
8203   SDValue AddcOp1 = AddcNode->getOperand(1);
8204
8205   // Check if the two operands are from the same mul_lohi node.
8206   if (AddcOp0.getNode() == AddcOp1.getNode())
8207     return SDValue();
8208
8209   assert(AddcNode->getNumValues() == 2 &&
8210          AddcNode->getValueType(0) == MVT::i32 &&
8211          "Expect ADDC with two result values. First: i32");
8212
8213   // Check that we have a glued ADDC node.
8214   if (AddcNode->getValueType(1) != MVT::Glue)
8215     return SDValue();
8216
8217   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8218   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8219       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8220       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8221       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8222     return SDValue();
8223
8224   // Look for the glued ADDE.
8225   SDNode* AddeNode = AddcNode->getGluedUser();
8226   if (AddeNode == NULL)
8227     return SDValue();
8228
8229   // Make sure it is really an ADDE.
8230   if (AddeNode->getOpcode() != ISD::ADDE)
8231     return SDValue();
8232
8233   assert(AddeNode->getNumOperands() == 3 &&
8234          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8235          "ADDE node has the wrong inputs");
8236
8237   // Check for the triangle shape.
8238   SDValue AddeOp0 = AddeNode->getOperand(0);
8239   SDValue AddeOp1 = AddeNode->getOperand(1);
8240
8241   // Make sure that the ADDE operands are not coming from the same node.
8242   if (AddeOp0.getNode() == AddeOp1.getNode())
8243     return SDValue();
8244
8245   // Find the MUL_LOHI node walking up ADDE's operands.
8246   bool IsLeftOperandMUL = false;
8247   SDValue MULOp = findMUL_LOHI(AddeOp0);
8248   if (MULOp == SDValue())
8249    MULOp = findMUL_LOHI(AddeOp1);
8250   else
8251     IsLeftOperandMUL = true;
8252   if (MULOp == SDValue())
8253      return SDValue();
8254
8255   // Figure out the right opcode.
8256   unsigned Opc = MULOp->getOpcode();
8257   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8258
8259   // Figure out the high and low input values to the MLAL node.
8260   SDValue* HiMul = &MULOp;
8261   SDValue* HiAdd = NULL;
8262   SDValue* LoMul = NULL;
8263   SDValue* LowAdd = NULL;
8264
8265   if (IsLeftOperandMUL)
8266     HiAdd = &AddeOp1;
8267   else
8268     HiAdd = &AddeOp0;
8269
8270
8271   if (AddcOp0->getOpcode() == Opc) {
8272     LoMul = &AddcOp0;
8273     LowAdd = &AddcOp1;
8274   }
8275   if (AddcOp1->getOpcode() == Opc) {
8276     LoMul = &AddcOp1;
8277     LowAdd = &AddcOp0;
8278   }
8279
8280   if (LoMul == NULL)
8281     return SDValue();
8282
8283   if (LoMul->getNode() != HiMul->getNode())
8284     return SDValue();
8285
8286   // Create the merged node.
8287   SelectionDAG &DAG = DCI.DAG;
8288
8289   // Build operand list.
8290   SmallVector<SDValue, 8> Ops;
8291   Ops.push_back(LoMul->getOperand(0));
8292   Ops.push_back(LoMul->getOperand(1));
8293   Ops.push_back(*LowAdd);
8294   Ops.push_back(*HiAdd);
8295
8296   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8297                                  DAG.getVTList(MVT::i32, MVT::i32),
8298                                  &Ops[0], Ops.size());
8299
8300   // Replace the ADDs' nodes uses by the MLA node's values.
8301   SDValue HiMLALResult(MLALNode.getNode(), 1);
8302   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8303
8304   SDValue LoMLALResult(MLALNode.getNode(), 0);
8305   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8306
8307   // Return original node to notify the driver to stop replacing.
8308   SDValue resNode(AddcNode, 0);
8309   return resNode;
8310 }
8311
8312 /// PerformADDCCombine - Target-specific dag combine transform from
8313 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8314 static SDValue PerformADDCCombine(SDNode *N,
8315                                  TargetLowering::DAGCombinerInfo &DCI,
8316                                  const ARMSubtarget *Subtarget) {
8317
8318   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8319
8320 }
8321
8322 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8323 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8324 /// called with the default operands, and if that fails, with commuted
8325 /// operands.
8326 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8327                                           TargetLowering::DAGCombinerInfo &DCI,
8328                                           const ARMSubtarget *Subtarget){
8329
8330   // Attempt to create vpaddl for this add.
8331   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8332   if (Result.getNode())
8333     return Result;
8334
8335   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8336   if (N0.getNode()->hasOneUse()) {
8337     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8338     if (Result.getNode()) return Result;
8339   }
8340   return SDValue();
8341 }
8342
8343 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8344 ///
8345 static SDValue PerformADDCombine(SDNode *N,
8346                                  TargetLowering::DAGCombinerInfo &DCI,
8347                                  const ARMSubtarget *Subtarget) {
8348   SDValue N0 = N->getOperand(0);
8349   SDValue N1 = N->getOperand(1);
8350
8351   // First try with the default operand order.
8352   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8353   if (Result.getNode())
8354     return Result;
8355
8356   // If that didn't work, try again with the operands commuted.
8357   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8358 }
8359
8360 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8361 ///
8362 static SDValue PerformSUBCombine(SDNode *N,
8363                                  TargetLowering::DAGCombinerInfo &DCI) {
8364   SDValue N0 = N->getOperand(0);
8365   SDValue N1 = N->getOperand(1);
8366
8367   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8368   if (N1.getNode()->hasOneUse()) {
8369     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8370     if (Result.getNode()) return Result;
8371   }
8372
8373   return SDValue();
8374 }
8375
8376 /// PerformVMULCombine
8377 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8378 /// special multiplier accumulator forwarding.
8379 ///   vmul d3, d0, d2
8380 ///   vmla d3, d1, d2
8381 /// is faster than
8382 ///   vadd d3, d0, d1
8383 ///   vmul d3, d3, d2
8384 //  However, for (A + B) * (A + B),
8385 //    vadd d2, d0, d1
8386 //    vmul d3, d0, d2
8387 //    vmla d3, d1, d2
8388 //  is slower than
8389 //    vadd d2, d0, d1
8390 //    vmul d3, d2, d2
8391 static SDValue PerformVMULCombine(SDNode *N,
8392                                   TargetLowering::DAGCombinerInfo &DCI,
8393                                   const ARMSubtarget *Subtarget) {
8394   if (!Subtarget->hasVMLxForwarding())
8395     return SDValue();
8396
8397   SelectionDAG &DAG = DCI.DAG;
8398   SDValue N0 = N->getOperand(0);
8399   SDValue N1 = N->getOperand(1);
8400   unsigned Opcode = N0.getOpcode();
8401   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8402       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8403     Opcode = N1.getOpcode();
8404     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8405         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8406       return SDValue();
8407     std::swap(N0, N1);
8408   }
8409
8410   if (N0 == N1)
8411     return SDValue();
8412
8413   EVT VT = N->getValueType(0);
8414   SDLoc DL(N);
8415   SDValue N00 = N0->getOperand(0);
8416   SDValue N01 = N0->getOperand(1);
8417   return DAG.getNode(Opcode, DL, VT,
8418                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8419                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8420 }
8421
8422 static SDValue PerformMULCombine(SDNode *N,
8423                                  TargetLowering::DAGCombinerInfo &DCI,
8424                                  const ARMSubtarget *Subtarget) {
8425   SelectionDAG &DAG = DCI.DAG;
8426
8427   if (Subtarget->isThumb1Only())
8428     return SDValue();
8429
8430   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8431     return SDValue();
8432
8433   EVT VT = N->getValueType(0);
8434   if (VT.is64BitVector() || VT.is128BitVector())
8435     return PerformVMULCombine(N, DCI, Subtarget);
8436   if (VT != MVT::i32)
8437     return SDValue();
8438
8439   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8440   if (!C)
8441     return SDValue();
8442
8443   int64_t MulAmt = C->getSExtValue();
8444   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8445
8446   ShiftAmt = ShiftAmt & (32 - 1);
8447   SDValue V = N->getOperand(0);
8448   SDLoc DL(N);
8449
8450   SDValue Res;
8451   MulAmt >>= ShiftAmt;
8452
8453   if (MulAmt >= 0) {
8454     if (isPowerOf2_32(MulAmt - 1)) {
8455       // (mul x, 2^N + 1) => (add (shl x, N), x)
8456       Res = DAG.getNode(ISD::ADD, DL, VT,
8457                         V,
8458                         DAG.getNode(ISD::SHL, DL, VT,
8459                                     V,
8460                                     DAG.getConstant(Log2_32(MulAmt - 1),
8461                                                     MVT::i32)));
8462     } else if (isPowerOf2_32(MulAmt + 1)) {
8463       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8464       Res = DAG.getNode(ISD::SUB, DL, VT,
8465                         DAG.getNode(ISD::SHL, DL, VT,
8466                                     V,
8467                                     DAG.getConstant(Log2_32(MulAmt + 1),
8468                                                     MVT::i32)),
8469                         V);
8470     } else
8471       return SDValue();
8472   } else {
8473     uint64_t MulAmtAbs = -MulAmt;
8474     if (isPowerOf2_32(MulAmtAbs + 1)) {
8475       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8476       Res = DAG.getNode(ISD::SUB, DL, VT,
8477                         V,
8478                         DAG.getNode(ISD::SHL, DL, VT,
8479                                     V,
8480                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8481                                                     MVT::i32)));
8482     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8483       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8484       Res = DAG.getNode(ISD::ADD, DL, VT,
8485                         V,
8486                         DAG.getNode(ISD::SHL, DL, VT,
8487                                     V,
8488                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8489                                                     MVT::i32)));
8490       Res = DAG.getNode(ISD::SUB, DL, VT,
8491                         DAG.getConstant(0, MVT::i32),Res);
8492
8493     } else
8494       return SDValue();
8495   }
8496
8497   if (ShiftAmt != 0)
8498     Res = DAG.getNode(ISD::SHL, DL, VT,
8499                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8500
8501   // Do not add new nodes to DAG combiner worklist.
8502   DCI.CombineTo(N, Res, false);
8503   return SDValue();
8504 }
8505
8506 static SDValue PerformANDCombine(SDNode *N,
8507                                  TargetLowering::DAGCombinerInfo &DCI,
8508                                  const ARMSubtarget *Subtarget) {
8509
8510   // Attempt to use immediate-form VBIC
8511   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8512   SDLoc dl(N);
8513   EVT VT = N->getValueType(0);
8514   SelectionDAG &DAG = DCI.DAG;
8515
8516   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8517     return SDValue();
8518
8519   APInt SplatBits, SplatUndef;
8520   unsigned SplatBitSize;
8521   bool HasAnyUndefs;
8522   if (BVN &&
8523       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8524     if (SplatBitSize <= 64) {
8525       EVT VbicVT;
8526       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8527                                       SplatUndef.getZExtValue(), SplatBitSize,
8528                                       DAG, VbicVT, VT.is128BitVector(),
8529                                       OtherModImm);
8530       if (Val.getNode()) {
8531         SDValue Input =
8532           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8533         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8534         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8535       }
8536     }
8537   }
8538
8539   if (!Subtarget->isThumb1Only()) {
8540     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8541     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8542     if (Result.getNode())
8543       return Result;
8544   }
8545
8546   return SDValue();
8547 }
8548
8549 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8550 static SDValue PerformORCombine(SDNode *N,
8551                                 TargetLowering::DAGCombinerInfo &DCI,
8552                                 const ARMSubtarget *Subtarget) {
8553   // Attempt to use immediate-form VORR
8554   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8555   SDLoc dl(N);
8556   EVT VT = N->getValueType(0);
8557   SelectionDAG &DAG = DCI.DAG;
8558
8559   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8560     return SDValue();
8561
8562   APInt SplatBits, SplatUndef;
8563   unsigned SplatBitSize;
8564   bool HasAnyUndefs;
8565   if (BVN && Subtarget->hasNEON() &&
8566       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8567     if (SplatBitSize <= 64) {
8568       EVT VorrVT;
8569       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8570                                       SplatUndef.getZExtValue(), SplatBitSize,
8571                                       DAG, VorrVT, VT.is128BitVector(),
8572                                       OtherModImm);
8573       if (Val.getNode()) {
8574         SDValue Input =
8575           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8576         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8577         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8578       }
8579     }
8580   }
8581
8582   if (!Subtarget->isThumb1Only()) {
8583     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8584     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8585     if (Result.getNode())
8586       return Result;
8587   }
8588
8589   // The code below optimizes (or (and X, Y), Z).
8590   // The AND operand needs to have a single user to make these optimizations
8591   // profitable.
8592   SDValue N0 = N->getOperand(0);
8593   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8594     return SDValue();
8595   SDValue N1 = N->getOperand(1);
8596
8597   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8598   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8599       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8600     APInt SplatUndef;
8601     unsigned SplatBitSize;
8602     bool HasAnyUndefs;
8603
8604     APInt SplatBits0, SplatBits1;
8605     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8606     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8607     // Ensure that the second operand of both ands are constants
8608     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8609                                       HasAnyUndefs) && !HasAnyUndefs) {
8610         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8611                                           HasAnyUndefs) && !HasAnyUndefs) {
8612             // Ensure that the bit width of the constants are the same and that
8613             // the splat arguments are logical inverses as per the pattern we
8614             // are trying to simplify.
8615             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8616                 SplatBits0 == ~SplatBits1) {
8617                 // Canonicalize the vector type to make instruction selection
8618                 // simpler.
8619                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8620                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8621                                              N0->getOperand(1),
8622                                              N0->getOperand(0),
8623                                              N1->getOperand(0));
8624                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8625             }
8626         }
8627     }
8628   }
8629
8630   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8631   // reasonable.
8632
8633   // BFI is only available on V6T2+
8634   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8635     return SDValue();
8636
8637   SDLoc DL(N);
8638   // 1) or (and A, mask), val => ARMbfi A, val, mask
8639   //      iff (val & mask) == val
8640   //
8641   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8642   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8643   //          && mask == ~mask2
8644   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8645   //          && ~mask == mask2
8646   //  (i.e., copy a bitfield value into another bitfield of the same width)
8647
8648   if (VT != MVT::i32)
8649     return SDValue();
8650
8651   SDValue N00 = N0.getOperand(0);
8652
8653   // The value and the mask need to be constants so we can verify this is
8654   // actually a bitfield set. If the mask is 0xffff, we can do better
8655   // via a movt instruction, so don't use BFI in that case.
8656   SDValue MaskOp = N0.getOperand(1);
8657   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8658   if (!MaskC)
8659     return SDValue();
8660   unsigned Mask = MaskC->getZExtValue();
8661   if (Mask == 0xffff)
8662     return SDValue();
8663   SDValue Res;
8664   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8665   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8666   if (N1C) {
8667     unsigned Val = N1C->getZExtValue();
8668     if ((Val & ~Mask) != Val)
8669       return SDValue();
8670
8671     if (ARM::isBitFieldInvertedMask(Mask)) {
8672       Val >>= countTrailingZeros(~Mask);
8673
8674       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8675                         DAG.getConstant(Val, MVT::i32),
8676                         DAG.getConstant(Mask, MVT::i32));
8677
8678       // Do not add new nodes to DAG combiner worklist.
8679       DCI.CombineTo(N, Res, false);
8680       return SDValue();
8681     }
8682   } else if (N1.getOpcode() == ISD::AND) {
8683     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8684     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8685     if (!N11C)
8686       return SDValue();
8687     unsigned Mask2 = N11C->getZExtValue();
8688
8689     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8690     // as is to match.
8691     if (ARM::isBitFieldInvertedMask(Mask) &&
8692         (Mask == ~Mask2)) {
8693       // The pack halfword instruction works better for masks that fit it,
8694       // so use that when it's available.
8695       if (Subtarget->hasT2ExtractPack() &&
8696           (Mask == 0xffff || Mask == 0xffff0000))
8697         return SDValue();
8698       // 2a
8699       unsigned amt = countTrailingZeros(Mask2);
8700       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8701                         DAG.getConstant(amt, MVT::i32));
8702       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8703                         DAG.getConstant(Mask, MVT::i32));
8704       // Do not add new nodes to DAG combiner worklist.
8705       DCI.CombineTo(N, Res, false);
8706       return SDValue();
8707     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8708                (~Mask == Mask2)) {
8709       // The pack halfword instruction works better for masks that fit it,
8710       // so use that when it's available.
8711       if (Subtarget->hasT2ExtractPack() &&
8712           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8713         return SDValue();
8714       // 2b
8715       unsigned lsb = countTrailingZeros(Mask);
8716       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8717                         DAG.getConstant(lsb, MVT::i32));
8718       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8719                         DAG.getConstant(Mask2, MVT::i32));
8720       // Do not add new nodes to DAG combiner worklist.
8721       DCI.CombineTo(N, Res, false);
8722       return SDValue();
8723     }
8724   }
8725
8726   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8727       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8728       ARM::isBitFieldInvertedMask(~Mask)) {
8729     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8730     // where lsb(mask) == #shamt and masked bits of B are known zero.
8731     SDValue ShAmt = N00.getOperand(1);
8732     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8733     unsigned LSB = countTrailingZeros(Mask);
8734     if (ShAmtC != LSB)
8735       return SDValue();
8736
8737     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8738                       DAG.getConstant(~Mask, MVT::i32));
8739
8740     // Do not add new nodes to DAG combiner worklist.
8741     DCI.CombineTo(N, Res, false);
8742   }
8743
8744   return SDValue();
8745 }
8746
8747 static SDValue PerformXORCombine(SDNode *N,
8748                                  TargetLowering::DAGCombinerInfo &DCI,
8749                                  const ARMSubtarget *Subtarget) {
8750   EVT VT = N->getValueType(0);
8751   SelectionDAG &DAG = DCI.DAG;
8752
8753   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8754     return SDValue();
8755
8756   if (!Subtarget->isThumb1Only()) {
8757     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8758     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8759     if (Result.getNode())
8760       return Result;
8761   }
8762
8763   return SDValue();
8764 }
8765
8766 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8767 /// the bits being cleared by the AND are not demanded by the BFI.
8768 static SDValue PerformBFICombine(SDNode *N,
8769                                  TargetLowering::DAGCombinerInfo &DCI) {
8770   SDValue N1 = N->getOperand(1);
8771   if (N1.getOpcode() == ISD::AND) {
8772     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8773     if (!N11C)
8774       return SDValue();
8775     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8776     unsigned LSB = countTrailingZeros(~InvMask);
8777     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8778     unsigned Mask = (1 << Width)-1;
8779     unsigned Mask2 = N11C->getZExtValue();
8780     if ((Mask & (~Mask2)) == 0)
8781       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8782                              N->getOperand(0), N1.getOperand(0),
8783                              N->getOperand(2));
8784   }
8785   return SDValue();
8786 }
8787
8788 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8789 /// ARMISD::VMOVRRD.
8790 static SDValue PerformVMOVRRDCombine(SDNode *N,
8791                                      TargetLowering::DAGCombinerInfo &DCI) {
8792   // vmovrrd(vmovdrr x, y) -> x,y
8793   SDValue InDouble = N->getOperand(0);
8794   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8795     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8796
8797   // vmovrrd(load f64) -> (load i32), (load i32)
8798   SDNode *InNode = InDouble.getNode();
8799   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8800       InNode->getValueType(0) == MVT::f64 &&
8801       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8802       !cast<LoadSDNode>(InNode)->isVolatile()) {
8803     // TODO: Should this be done for non-FrameIndex operands?
8804     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8805
8806     SelectionDAG &DAG = DCI.DAG;
8807     SDLoc DL(LD);
8808     SDValue BasePtr = LD->getBasePtr();
8809     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8810                                  LD->getPointerInfo(), LD->isVolatile(),
8811                                  LD->isNonTemporal(), LD->isInvariant(),
8812                                  LD->getAlignment());
8813
8814     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8815                                     DAG.getConstant(4, MVT::i32));
8816     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8817                                  LD->getPointerInfo(), LD->isVolatile(),
8818                                  LD->isNonTemporal(), LD->isInvariant(),
8819                                  std::min(4U, LD->getAlignment() / 2));
8820
8821     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8822     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8823     DCI.RemoveFromWorklist(LD);
8824     DAG.DeleteNode(LD);
8825     return Result;
8826   }
8827
8828   return SDValue();
8829 }
8830
8831 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8832 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8833 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8834   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8835   SDValue Op0 = N->getOperand(0);
8836   SDValue Op1 = N->getOperand(1);
8837   if (Op0.getOpcode() == ISD::BITCAST)
8838     Op0 = Op0.getOperand(0);
8839   if (Op1.getOpcode() == ISD::BITCAST)
8840     Op1 = Op1.getOperand(0);
8841   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8842       Op0.getNode() == Op1.getNode() &&
8843       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8844     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8845                        N->getValueType(0), Op0.getOperand(0));
8846   return SDValue();
8847 }
8848
8849 /// PerformSTORECombine - Target-specific dag combine xforms for
8850 /// ISD::STORE.
8851 static SDValue PerformSTORECombine(SDNode *N,
8852                                    TargetLowering::DAGCombinerInfo &DCI) {
8853   StoreSDNode *St = cast<StoreSDNode>(N);
8854   if (St->isVolatile())
8855     return SDValue();
8856
8857   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8858   // pack all of the elements in one place.  Next, store to memory in fewer
8859   // chunks.
8860   SDValue StVal = St->getValue();
8861   EVT VT = StVal.getValueType();
8862   if (St->isTruncatingStore() && VT.isVector()) {
8863     SelectionDAG &DAG = DCI.DAG;
8864     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8865     EVT StVT = St->getMemoryVT();
8866     unsigned NumElems = VT.getVectorNumElements();
8867     assert(StVT != VT && "Cannot truncate to the same type");
8868     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8869     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8870
8871     // From, To sizes and ElemCount must be pow of two
8872     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8873
8874     // We are going to use the original vector elt for storing.
8875     // Accumulated smaller vector elements must be a multiple of the store size.
8876     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8877
8878     unsigned SizeRatio  = FromEltSz / ToEltSz;
8879     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8880
8881     // Create a type on which we perform the shuffle.
8882     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8883                                      NumElems*SizeRatio);
8884     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8885
8886     SDLoc DL(St);
8887     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8888     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8889     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8890
8891     // Can't shuffle using an illegal type.
8892     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8893
8894     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8895                                 DAG.getUNDEF(WideVec.getValueType()),
8896                                 ShuffleVec.data());
8897     // At this point all of the data is stored at the bottom of the
8898     // register. We now need to save it to mem.
8899
8900     // Find the largest store unit
8901     MVT StoreType = MVT::i8;
8902     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8903          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8904       MVT Tp = (MVT::SimpleValueType)tp;
8905       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8906         StoreType = Tp;
8907     }
8908     // Didn't find a legal store type.
8909     if (!TLI.isTypeLegal(StoreType))
8910       return SDValue();
8911
8912     // Bitcast the original vector into a vector of store-size units
8913     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8914             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8915     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8916     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8917     SmallVector<SDValue, 8> Chains;
8918     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8919                                         TLI.getPointerTy());
8920     SDValue BasePtr = St->getBasePtr();
8921
8922     // Perform one or more big stores into memory.
8923     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8924     for (unsigned I = 0; I < E; I++) {
8925       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8926                                    StoreType, ShuffWide,
8927                                    DAG.getIntPtrConstant(I));
8928       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8929                                 St->getPointerInfo(), St->isVolatile(),
8930                                 St->isNonTemporal(), St->getAlignment());
8931       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8932                             Increment);
8933       Chains.push_back(Ch);
8934     }
8935     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
8936                        Chains.size());
8937   }
8938
8939   if (!ISD::isNormalStore(St))
8940     return SDValue();
8941
8942   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8943   // ARM stores of arguments in the same cache line.
8944   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8945       StVal.getNode()->hasOneUse()) {
8946     SelectionDAG  &DAG = DCI.DAG;
8947     SDLoc DL(St);
8948     SDValue BasePtr = St->getBasePtr();
8949     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8950                                   StVal.getNode()->getOperand(0), BasePtr,
8951                                   St->getPointerInfo(), St->isVolatile(),
8952                                   St->isNonTemporal(), St->getAlignment());
8953
8954     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8955                                     DAG.getConstant(4, MVT::i32));
8956     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
8957                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8958                         St->isNonTemporal(),
8959                         std::min(4U, St->getAlignment() / 2));
8960   }
8961
8962   if (StVal.getValueType() != MVT::i64 ||
8963       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8964     return SDValue();
8965
8966   // Bitcast an i64 store extracted from a vector to f64.
8967   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8968   SelectionDAG &DAG = DCI.DAG;
8969   SDLoc dl(StVal);
8970   SDValue IntVec = StVal.getOperand(0);
8971   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8972                                  IntVec.getValueType().getVectorNumElements());
8973   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8974   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8975                                Vec, StVal.getOperand(1));
8976   dl = SDLoc(N);
8977   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8978   // Make the DAGCombiner fold the bitcasts.
8979   DCI.AddToWorklist(Vec.getNode());
8980   DCI.AddToWorklist(ExtElt.getNode());
8981   DCI.AddToWorklist(V.getNode());
8982   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8983                       St->getPointerInfo(), St->isVolatile(),
8984                       St->isNonTemporal(), St->getAlignment(),
8985                       St->getTBAAInfo());
8986 }
8987
8988 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8989 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8990 /// i64 vector to have f64 elements, since the value can then be loaded
8991 /// directly into a VFP register.
8992 static bool hasNormalLoadOperand(SDNode *N) {
8993   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8994   for (unsigned i = 0; i < NumElts; ++i) {
8995     SDNode *Elt = N->getOperand(i).getNode();
8996     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8997       return true;
8998   }
8999   return false;
9000 }
9001
9002 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9003 /// ISD::BUILD_VECTOR.
9004 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9005                                           TargetLowering::DAGCombinerInfo &DCI){
9006   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9007   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
9008   // into a pair of GPRs, which is fine when the value is used as a scalar,
9009   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9010   SelectionDAG &DAG = DCI.DAG;
9011   if (N->getNumOperands() == 2) {
9012     SDValue RV = PerformVMOVDRRCombine(N, DAG);
9013     if (RV.getNode())
9014       return RV;
9015   }
9016
9017   // Load i64 elements as f64 values so that type legalization does not split
9018   // them up into i32 values.
9019   EVT VT = N->getValueType(0);
9020   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9021     return SDValue();
9022   SDLoc dl(N);
9023   SmallVector<SDValue, 8> Ops;
9024   unsigned NumElts = VT.getVectorNumElements();
9025   for (unsigned i = 0; i < NumElts; ++i) {
9026     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9027     Ops.push_back(V);
9028     // Make the DAGCombiner fold the bitcast.
9029     DCI.AddToWorklist(V.getNode());
9030   }
9031   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9032   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
9033   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9034 }
9035
9036 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9037 static SDValue
9038 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9039   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9040   // At that time, we may have inserted bitcasts from integer to float.
9041   // If these bitcasts have survived DAGCombine, change the lowering of this
9042   // BUILD_VECTOR in something more vector friendly, i.e., that does not
9043   // force to use floating point types.
9044
9045   // Make sure we can change the type of the vector.
9046   // This is possible iff:
9047   // 1. The vector is only used in a bitcast to a integer type. I.e.,
9048   //    1.1. Vector is used only once.
9049   //    1.2. Use is a bit convert to an integer type.
9050   // 2. The size of its operands are 32-bits (64-bits are not legal).
9051   EVT VT = N->getValueType(0);
9052   EVT EltVT = VT.getVectorElementType();
9053
9054   // Check 1.1. and 2.
9055   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9056     return SDValue();
9057
9058   // By construction, the input type must be float.
9059   assert(EltVT == MVT::f32 && "Unexpected type!");
9060
9061   // Check 1.2.
9062   SDNode *Use = *N->use_begin();
9063   if (Use->getOpcode() != ISD::BITCAST ||
9064       Use->getValueType(0).isFloatingPoint())
9065     return SDValue();
9066
9067   // Check profitability.
9068   // Model is, if more than half of the relevant operands are bitcast from
9069   // i32, turn the build_vector into a sequence of insert_vector_elt.
9070   // Relevant operands are everything that is not statically
9071   // (i.e., at compile time) bitcasted.
9072   unsigned NumOfBitCastedElts = 0;
9073   unsigned NumElts = VT.getVectorNumElements();
9074   unsigned NumOfRelevantElts = NumElts;
9075   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9076     SDValue Elt = N->getOperand(Idx);
9077     if (Elt->getOpcode() == ISD::BITCAST) {
9078       // Assume only bit cast to i32 will go away.
9079       if (Elt->getOperand(0).getValueType() == MVT::i32)
9080         ++NumOfBitCastedElts;
9081     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9082       // Constants are statically casted, thus do not count them as
9083       // relevant operands.
9084       --NumOfRelevantElts;
9085   }
9086
9087   // Check if more than half of the elements require a non-free bitcast.
9088   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9089     return SDValue();
9090
9091   SelectionDAG &DAG = DCI.DAG;
9092   // Create the new vector type.
9093   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9094   // Check if the type is legal.
9095   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9096   if (!TLI.isTypeLegal(VecVT))
9097     return SDValue();
9098
9099   // Combine:
9100   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9101   // => BITCAST INSERT_VECTOR_ELT
9102   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9103   //                      (BITCAST EN), N.
9104   SDValue Vec = DAG.getUNDEF(VecVT);
9105   SDLoc dl(N);
9106   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9107     SDValue V = N->getOperand(Idx);
9108     if (V.getOpcode() == ISD::UNDEF)
9109       continue;
9110     if (V.getOpcode() == ISD::BITCAST &&
9111         V->getOperand(0).getValueType() == MVT::i32)
9112       // Fold obvious case.
9113       V = V.getOperand(0);
9114     else {
9115       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 
9116       // Make the DAGCombiner fold the bitcasts.
9117       DCI.AddToWorklist(V.getNode());
9118     }
9119     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
9120     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9121   }
9122   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9123   // Make the DAGCombiner fold the bitcasts.
9124   DCI.AddToWorklist(Vec.getNode());
9125   return Vec;
9126 }
9127
9128 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9129 /// ISD::INSERT_VECTOR_ELT.
9130 static SDValue PerformInsertEltCombine(SDNode *N,
9131                                        TargetLowering::DAGCombinerInfo &DCI) {
9132   // Bitcast an i64 load inserted into a vector to f64.
9133   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9134   EVT VT = N->getValueType(0);
9135   SDNode *Elt = N->getOperand(1).getNode();
9136   if (VT.getVectorElementType() != MVT::i64 ||
9137       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9138     return SDValue();
9139
9140   SelectionDAG &DAG = DCI.DAG;
9141   SDLoc dl(N);
9142   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9143                                  VT.getVectorNumElements());
9144   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9145   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9146   // Make the DAGCombiner fold the bitcasts.
9147   DCI.AddToWorklist(Vec.getNode());
9148   DCI.AddToWorklist(V.getNode());
9149   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9150                                Vec, V, N->getOperand(2));
9151   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9152 }
9153
9154 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9155 /// ISD::VECTOR_SHUFFLE.
9156 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9157   // The LLVM shufflevector instruction does not require the shuffle mask
9158   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9159   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
9160   // operands do not match the mask length, they are extended by concatenating
9161   // them with undef vectors.  That is probably the right thing for other
9162   // targets, but for NEON it is better to concatenate two double-register
9163   // size vector operands into a single quad-register size vector.  Do that
9164   // transformation here:
9165   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
9166   //   shuffle(concat(v1, v2), undef)
9167   SDValue Op0 = N->getOperand(0);
9168   SDValue Op1 = N->getOperand(1);
9169   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9170       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9171       Op0.getNumOperands() != 2 ||
9172       Op1.getNumOperands() != 2)
9173     return SDValue();
9174   SDValue Concat0Op1 = Op0.getOperand(1);
9175   SDValue Concat1Op1 = Op1.getOperand(1);
9176   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9177       Concat1Op1.getOpcode() != ISD::UNDEF)
9178     return SDValue();
9179   // Skip the transformation if any of the types are illegal.
9180   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9181   EVT VT = N->getValueType(0);
9182   if (!TLI.isTypeLegal(VT) ||
9183       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9184       !TLI.isTypeLegal(Concat1Op1.getValueType()))
9185     return SDValue();
9186
9187   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9188                                   Op0.getOperand(0), Op1.getOperand(0));
9189   // Translate the shuffle mask.
9190   SmallVector<int, 16> NewMask;
9191   unsigned NumElts = VT.getVectorNumElements();
9192   unsigned HalfElts = NumElts/2;
9193   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9194   for (unsigned n = 0; n < NumElts; ++n) {
9195     int MaskElt = SVN->getMaskElt(n);
9196     int NewElt = -1;
9197     if (MaskElt < (int)HalfElts)
9198       NewElt = MaskElt;
9199     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9200       NewElt = HalfElts + MaskElt - NumElts;
9201     NewMask.push_back(NewElt);
9202   }
9203   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9204                               DAG.getUNDEF(VT), NewMask.data());
9205 }
9206
9207 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
9208 /// NEON load/store intrinsics to merge base address updates.
9209 static SDValue CombineBaseUpdate(SDNode *N,
9210                                  TargetLowering::DAGCombinerInfo &DCI) {
9211   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9212     return SDValue();
9213
9214   SelectionDAG &DAG = DCI.DAG;
9215   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9216                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9217   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
9218   SDValue Addr = N->getOperand(AddrOpIdx);
9219
9220   // Search for a use of the address operand that is an increment.
9221   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9222          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9223     SDNode *User = *UI;
9224     if (User->getOpcode() != ISD::ADD ||
9225         UI.getUse().getResNo() != Addr.getResNo())
9226       continue;
9227
9228     // Check that the add is independent of the load/store.  Otherwise, folding
9229     // it would create a cycle.
9230     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9231       continue;
9232
9233     // Find the new opcode for the updating load/store.
9234     bool isLoad = true;
9235     bool isLaneOp = false;
9236     unsigned NewOpc = 0;
9237     unsigned NumVecs = 0;
9238     if (isIntrinsic) {
9239       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9240       switch (IntNo) {
9241       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9242       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9243         NumVecs = 1; break;
9244       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9245         NumVecs = 2; break;
9246       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9247         NumVecs = 3; break;
9248       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9249         NumVecs = 4; break;
9250       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9251         NumVecs = 2; isLaneOp = true; break;
9252       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9253         NumVecs = 3; isLaneOp = true; break;
9254       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9255         NumVecs = 4; isLaneOp = true; break;
9256       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9257         NumVecs = 1; isLoad = false; break;
9258       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9259         NumVecs = 2; isLoad = false; break;
9260       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9261         NumVecs = 3; isLoad = false; break;
9262       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9263         NumVecs = 4; isLoad = false; break;
9264       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9265         NumVecs = 2; isLoad = false; isLaneOp = true; break;
9266       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9267         NumVecs = 3; isLoad = false; isLaneOp = true; break;
9268       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9269         NumVecs = 4; isLoad = false; isLaneOp = true; break;
9270       }
9271     } else {
9272       isLaneOp = true;
9273       switch (N->getOpcode()) {
9274       default: llvm_unreachable("unexpected opcode for Neon base update");
9275       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9276       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9277       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9278       }
9279     }
9280
9281     // Find the size of memory referenced by the load/store.
9282     EVT VecTy;
9283     if (isLoad)
9284       VecTy = N->getValueType(0);
9285     else
9286       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9287     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9288     if (isLaneOp)
9289       NumBytes /= VecTy.getVectorNumElements();
9290
9291     // If the increment is a constant, it must match the memory ref size.
9292     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9293     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9294       uint64_t IncVal = CInc->getZExtValue();
9295       if (IncVal != NumBytes)
9296         continue;
9297     } else if (NumBytes >= 3 * 16) {
9298       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9299       // separate instructions that make it harder to use a non-constant update.
9300       continue;
9301     }
9302
9303     // Create the new updating load/store node.
9304     EVT Tys[6];
9305     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
9306     unsigned n;
9307     for (n = 0; n < NumResultVecs; ++n)
9308       Tys[n] = VecTy;
9309     Tys[n++] = MVT::i32;
9310     Tys[n] = MVT::Other;
9311     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
9312     SmallVector<SDValue, 8> Ops;
9313     Ops.push_back(N->getOperand(0)); // incoming chain
9314     Ops.push_back(N->getOperand(AddrOpIdx));
9315     Ops.push_back(Inc);
9316     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
9317       Ops.push_back(N->getOperand(i));
9318     }
9319     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9320     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9321                                            Ops.data(), Ops.size(),
9322                                            MemInt->getMemoryVT(),
9323                                            MemInt->getMemOperand());
9324
9325     // Update the uses.
9326     std::vector<SDValue> NewResults;
9327     for (unsigned i = 0; i < NumResultVecs; ++i) {
9328       NewResults.push_back(SDValue(UpdN.getNode(), i));
9329     }
9330     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9331     DCI.CombineTo(N, NewResults);
9332     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9333
9334     break;
9335   }
9336   return SDValue();
9337 }
9338
9339 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9340 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9341 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9342 /// return true.
9343 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9344   SelectionDAG &DAG = DCI.DAG;
9345   EVT VT = N->getValueType(0);
9346   // vldN-dup instructions only support 64-bit vectors for N > 1.
9347   if (!VT.is64BitVector())
9348     return false;
9349
9350   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9351   SDNode *VLD = N->getOperand(0).getNode();
9352   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9353     return false;
9354   unsigned NumVecs = 0;
9355   unsigned NewOpc = 0;
9356   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9357   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9358     NumVecs = 2;
9359     NewOpc = ARMISD::VLD2DUP;
9360   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9361     NumVecs = 3;
9362     NewOpc = ARMISD::VLD3DUP;
9363   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9364     NumVecs = 4;
9365     NewOpc = ARMISD::VLD4DUP;
9366   } else {
9367     return false;
9368   }
9369
9370   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9371   // numbers match the load.
9372   unsigned VLDLaneNo =
9373     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9374   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9375        UI != UE; ++UI) {
9376     // Ignore uses of the chain result.
9377     if (UI.getUse().getResNo() == NumVecs)
9378       continue;
9379     SDNode *User = *UI;
9380     if (User->getOpcode() != ARMISD::VDUPLANE ||
9381         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9382       return false;
9383   }
9384
9385   // Create the vldN-dup node.
9386   EVT Tys[5];
9387   unsigned n;
9388   for (n = 0; n < NumVecs; ++n)
9389     Tys[n] = VT;
9390   Tys[n] = MVT::Other;
9391   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
9392   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9393   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9394   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9395                                            Ops, 2, VLDMemInt->getMemoryVT(),
9396                                            VLDMemInt->getMemOperand());
9397
9398   // Update the uses.
9399   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9400        UI != UE; ++UI) {
9401     unsigned ResNo = UI.getUse().getResNo();
9402     // Ignore uses of the chain result.
9403     if (ResNo == NumVecs)
9404       continue;
9405     SDNode *User = *UI;
9406     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9407   }
9408
9409   // Now the vldN-lane intrinsic is dead except for its chain result.
9410   // Update uses of the chain.
9411   std::vector<SDValue> VLDDupResults;
9412   for (unsigned n = 0; n < NumVecs; ++n)
9413     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9414   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9415   DCI.CombineTo(VLD, VLDDupResults);
9416
9417   return true;
9418 }
9419
9420 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9421 /// ARMISD::VDUPLANE.
9422 static SDValue PerformVDUPLANECombine(SDNode *N,
9423                                       TargetLowering::DAGCombinerInfo &DCI) {
9424   SDValue Op = N->getOperand(0);
9425
9426   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9427   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9428   if (CombineVLDDUP(N, DCI))
9429     return SDValue(N, 0);
9430
9431   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9432   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9433   while (Op.getOpcode() == ISD::BITCAST)
9434     Op = Op.getOperand(0);
9435   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9436     return SDValue();
9437
9438   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9439   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9440   // The canonical VMOV for a zero vector uses a 32-bit element size.
9441   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9442   unsigned EltBits;
9443   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9444     EltSize = 8;
9445   EVT VT = N->getValueType(0);
9446   if (EltSize > VT.getVectorElementType().getSizeInBits())
9447     return SDValue();
9448
9449   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9450 }
9451
9452 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9453 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9454 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9455 {
9456   integerPart cN;
9457   integerPart c0 = 0;
9458   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9459        I != E; I++) {
9460     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9461     if (!C)
9462       return false;
9463
9464     bool isExact;
9465     APFloat APF = C->getValueAPF();
9466     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9467         != APFloat::opOK || !isExact)
9468       return false;
9469
9470     c0 = (I == 0) ? cN : c0;
9471     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9472       return false;
9473   }
9474   C = c0;
9475   return true;
9476 }
9477
9478 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9479 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9480 /// when the VMUL has a constant operand that is a power of 2.
9481 ///
9482 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9483 ///  vmul.f32        d16, d17, d16
9484 ///  vcvt.s32.f32    d16, d16
9485 /// becomes:
9486 ///  vcvt.s32.f32    d16, d16, #3
9487 static SDValue PerformVCVTCombine(SDNode *N,
9488                                   TargetLowering::DAGCombinerInfo &DCI,
9489                                   const ARMSubtarget *Subtarget) {
9490   SelectionDAG &DAG = DCI.DAG;
9491   SDValue Op = N->getOperand(0);
9492
9493   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9494       Op.getOpcode() != ISD::FMUL)
9495     return SDValue();
9496
9497   uint64_t C;
9498   SDValue N0 = Op->getOperand(0);
9499   SDValue ConstVec = Op->getOperand(1);
9500   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9501
9502   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9503       !isConstVecPow2(ConstVec, isSigned, C))
9504     return SDValue();
9505
9506   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9507   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9508   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9509     // These instructions only exist converting from f32 to i32. We can handle
9510     // smaller integers by generating an extra truncate, but larger ones would
9511     // be lossy.
9512     return SDValue();
9513   }
9514
9515   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9516     Intrinsic::arm_neon_vcvtfp2fxu;
9517   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9518   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9519                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9520                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9521                                  DAG.getConstant(Log2_64(C), MVT::i32));
9522
9523   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9524     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9525
9526   return FixConv;
9527 }
9528
9529 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9530 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9531 /// when the VDIV has a constant operand that is a power of 2.
9532 ///
9533 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9534 ///  vcvt.f32.s32    d16, d16
9535 ///  vdiv.f32        d16, d17, d16
9536 /// becomes:
9537 ///  vcvt.f32.s32    d16, d16, #3
9538 static SDValue PerformVDIVCombine(SDNode *N,
9539                                   TargetLowering::DAGCombinerInfo &DCI,
9540                                   const ARMSubtarget *Subtarget) {
9541   SelectionDAG &DAG = DCI.DAG;
9542   SDValue Op = N->getOperand(0);
9543   unsigned OpOpcode = Op.getNode()->getOpcode();
9544
9545   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9546       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9547     return SDValue();
9548
9549   uint64_t C;
9550   SDValue ConstVec = N->getOperand(1);
9551   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9552
9553   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9554       !isConstVecPow2(ConstVec, isSigned, C))
9555     return SDValue();
9556
9557   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9558   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9559   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9560     // These instructions only exist converting from i32 to f32. We can handle
9561     // smaller integers by generating an extra extend, but larger ones would
9562     // be lossy.
9563     return SDValue();
9564   }
9565
9566   SDValue ConvInput = Op.getOperand(0);
9567   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9568   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9569     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9570                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9571                             ConvInput);
9572
9573   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9574     Intrinsic::arm_neon_vcvtfxu2fp;
9575   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9576                      Op.getValueType(),
9577                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9578                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9579 }
9580
9581 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9582 /// operand of a vector shift operation, where all the elements of the
9583 /// build_vector must have the same constant integer value.
9584 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9585   // Ignore bit_converts.
9586   while (Op.getOpcode() == ISD::BITCAST)
9587     Op = Op.getOperand(0);
9588   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9589   APInt SplatBits, SplatUndef;
9590   unsigned SplatBitSize;
9591   bool HasAnyUndefs;
9592   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9593                                       HasAnyUndefs, ElementBits) ||
9594       SplatBitSize > ElementBits)
9595     return false;
9596   Cnt = SplatBits.getSExtValue();
9597   return true;
9598 }
9599
9600 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9601 /// operand of a vector shift left operation.  That value must be in the range:
9602 ///   0 <= Value < ElementBits for a left shift; or
9603 ///   0 <= Value <= ElementBits for a long left shift.
9604 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9605   assert(VT.isVector() && "vector shift count is not a vector type");
9606   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9607   if (! getVShiftImm(Op, ElementBits, Cnt))
9608     return false;
9609   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9610 }
9611
9612 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9613 /// operand of a vector shift right operation.  For a shift opcode, the value
9614 /// is positive, but for an intrinsic the value count must be negative. The
9615 /// absolute value must be in the range:
9616 ///   1 <= |Value| <= ElementBits for a right shift; or
9617 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9618 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9619                          int64_t &Cnt) {
9620   assert(VT.isVector() && "vector shift count is not a vector type");
9621   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9622   if (! getVShiftImm(Op, ElementBits, Cnt))
9623     return false;
9624   if (isIntrinsic)
9625     Cnt = -Cnt;
9626   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9627 }
9628
9629 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9630 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9631   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9632   switch (IntNo) {
9633   default:
9634     // Don't do anything for most intrinsics.
9635     break;
9636
9637   // Vector shifts: check for immediate versions and lower them.
9638   // Note: This is done during DAG combining instead of DAG legalizing because
9639   // the build_vectors for 64-bit vector element shift counts are generally
9640   // not legal, and it is hard to see their values after they get legalized to
9641   // loads from a constant pool.
9642   case Intrinsic::arm_neon_vshifts:
9643   case Intrinsic::arm_neon_vshiftu:
9644   case Intrinsic::arm_neon_vshiftls:
9645   case Intrinsic::arm_neon_vshiftlu:
9646   case Intrinsic::arm_neon_vshiftn:
9647   case Intrinsic::arm_neon_vrshifts:
9648   case Intrinsic::arm_neon_vrshiftu:
9649   case Intrinsic::arm_neon_vrshiftn:
9650   case Intrinsic::arm_neon_vqshifts:
9651   case Intrinsic::arm_neon_vqshiftu:
9652   case Intrinsic::arm_neon_vqshiftsu:
9653   case Intrinsic::arm_neon_vqshiftns:
9654   case Intrinsic::arm_neon_vqshiftnu:
9655   case Intrinsic::arm_neon_vqshiftnsu:
9656   case Intrinsic::arm_neon_vqrshiftns:
9657   case Intrinsic::arm_neon_vqrshiftnu:
9658   case Intrinsic::arm_neon_vqrshiftnsu: {
9659     EVT VT = N->getOperand(1).getValueType();
9660     int64_t Cnt;
9661     unsigned VShiftOpc = 0;
9662
9663     switch (IntNo) {
9664     case Intrinsic::arm_neon_vshifts:
9665     case Intrinsic::arm_neon_vshiftu:
9666       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9667         VShiftOpc = ARMISD::VSHL;
9668         break;
9669       }
9670       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9671         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9672                      ARMISD::VSHRs : ARMISD::VSHRu);
9673         break;
9674       }
9675       return SDValue();
9676
9677     case Intrinsic::arm_neon_vshiftls:
9678     case Intrinsic::arm_neon_vshiftlu:
9679       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
9680         break;
9681       llvm_unreachable("invalid shift count for vshll intrinsic");
9682
9683     case Intrinsic::arm_neon_vrshifts:
9684     case Intrinsic::arm_neon_vrshiftu:
9685       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9686         break;
9687       return SDValue();
9688
9689     case Intrinsic::arm_neon_vqshifts:
9690     case Intrinsic::arm_neon_vqshiftu:
9691       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9692         break;
9693       return SDValue();
9694
9695     case Intrinsic::arm_neon_vqshiftsu:
9696       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9697         break;
9698       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9699
9700     case Intrinsic::arm_neon_vshiftn:
9701     case Intrinsic::arm_neon_vrshiftn:
9702     case Intrinsic::arm_neon_vqshiftns:
9703     case Intrinsic::arm_neon_vqshiftnu:
9704     case Intrinsic::arm_neon_vqshiftnsu:
9705     case Intrinsic::arm_neon_vqrshiftns:
9706     case Intrinsic::arm_neon_vqrshiftnu:
9707     case Intrinsic::arm_neon_vqrshiftnsu:
9708       // Narrowing shifts require an immediate right shift.
9709       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9710         break;
9711       llvm_unreachable("invalid shift count for narrowing vector shift "
9712                        "intrinsic");
9713
9714     default:
9715       llvm_unreachable("unhandled vector shift");
9716     }
9717
9718     switch (IntNo) {
9719     case Intrinsic::arm_neon_vshifts:
9720     case Intrinsic::arm_neon_vshiftu:
9721       // Opcode already set above.
9722       break;
9723     case Intrinsic::arm_neon_vshiftls:
9724     case Intrinsic::arm_neon_vshiftlu:
9725       if (Cnt == VT.getVectorElementType().getSizeInBits())
9726         VShiftOpc = ARMISD::VSHLLi;
9727       else
9728         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
9729                      ARMISD::VSHLLs : ARMISD::VSHLLu);
9730       break;
9731     case Intrinsic::arm_neon_vshiftn:
9732       VShiftOpc = ARMISD::VSHRN; break;
9733     case Intrinsic::arm_neon_vrshifts:
9734       VShiftOpc = ARMISD::VRSHRs; break;
9735     case Intrinsic::arm_neon_vrshiftu:
9736       VShiftOpc = ARMISD::VRSHRu; break;
9737     case Intrinsic::arm_neon_vrshiftn:
9738       VShiftOpc = ARMISD::VRSHRN; break;
9739     case Intrinsic::arm_neon_vqshifts:
9740       VShiftOpc = ARMISD::VQSHLs; break;
9741     case Intrinsic::arm_neon_vqshiftu:
9742       VShiftOpc = ARMISD::VQSHLu; break;
9743     case Intrinsic::arm_neon_vqshiftsu:
9744       VShiftOpc = ARMISD::VQSHLsu; break;
9745     case Intrinsic::arm_neon_vqshiftns:
9746       VShiftOpc = ARMISD::VQSHRNs; break;
9747     case Intrinsic::arm_neon_vqshiftnu:
9748       VShiftOpc = ARMISD::VQSHRNu; break;
9749     case Intrinsic::arm_neon_vqshiftnsu:
9750       VShiftOpc = ARMISD::VQSHRNsu; break;
9751     case Intrinsic::arm_neon_vqrshiftns:
9752       VShiftOpc = ARMISD::VQRSHRNs; break;
9753     case Intrinsic::arm_neon_vqrshiftnu:
9754       VShiftOpc = ARMISD::VQRSHRNu; break;
9755     case Intrinsic::arm_neon_vqrshiftnsu:
9756       VShiftOpc = ARMISD::VQRSHRNsu; break;
9757     }
9758
9759     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9760                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9761   }
9762
9763   case Intrinsic::arm_neon_vshiftins: {
9764     EVT VT = N->getOperand(1).getValueType();
9765     int64_t Cnt;
9766     unsigned VShiftOpc = 0;
9767
9768     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9769       VShiftOpc = ARMISD::VSLI;
9770     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9771       VShiftOpc = ARMISD::VSRI;
9772     else {
9773       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9774     }
9775
9776     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9777                        N->getOperand(1), N->getOperand(2),
9778                        DAG.getConstant(Cnt, MVT::i32));
9779   }
9780
9781   case Intrinsic::arm_neon_vqrshifts:
9782   case Intrinsic::arm_neon_vqrshiftu:
9783     // No immediate versions of these to check for.
9784     break;
9785   }
9786
9787   return SDValue();
9788 }
9789
9790 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9791 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9792 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9793 /// vector element shift counts are generally not legal, and it is hard to see
9794 /// their values after they get legalized to loads from a constant pool.
9795 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9796                                    const ARMSubtarget *ST) {
9797   EVT VT = N->getValueType(0);
9798   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9799     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9800     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9801     SDValue N1 = N->getOperand(1);
9802     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9803       SDValue N0 = N->getOperand(0);
9804       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9805           DAG.MaskedValueIsZero(N0.getOperand(0),
9806                                 APInt::getHighBitsSet(32, 16)))
9807         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9808     }
9809   }
9810
9811   // Nothing to be done for scalar shifts.
9812   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9813   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9814     return SDValue();
9815
9816   assert(ST->hasNEON() && "unexpected vector shift");
9817   int64_t Cnt;
9818
9819   switch (N->getOpcode()) {
9820   default: llvm_unreachable("unexpected shift opcode");
9821
9822   case ISD::SHL:
9823     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9824       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9825                          DAG.getConstant(Cnt, MVT::i32));
9826     break;
9827
9828   case ISD::SRA:
9829   case ISD::SRL:
9830     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9831       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9832                             ARMISD::VSHRs : ARMISD::VSHRu);
9833       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9834                          DAG.getConstant(Cnt, MVT::i32));
9835     }
9836   }
9837   return SDValue();
9838 }
9839
9840 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9841 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9842 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9843                                     const ARMSubtarget *ST) {
9844   SDValue N0 = N->getOperand(0);
9845
9846   // Check for sign- and zero-extensions of vector extract operations of 8-
9847   // and 16-bit vector elements.  NEON supports these directly.  They are
9848   // handled during DAG combining because type legalization will promote them
9849   // to 32-bit types and it is messy to recognize the operations after that.
9850   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9851     SDValue Vec = N0.getOperand(0);
9852     SDValue Lane = N0.getOperand(1);
9853     EVT VT = N->getValueType(0);
9854     EVT EltVT = N0.getValueType();
9855     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9856
9857     if (VT == MVT::i32 &&
9858         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9859         TLI.isTypeLegal(Vec.getValueType()) &&
9860         isa<ConstantSDNode>(Lane)) {
9861
9862       unsigned Opc = 0;
9863       switch (N->getOpcode()) {
9864       default: llvm_unreachable("unexpected opcode");
9865       case ISD::SIGN_EXTEND:
9866         Opc = ARMISD::VGETLANEs;
9867         break;
9868       case ISD::ZERO_EXTEND:
9869       case ISD::ANY_EXTEND:
9870         Opc = ARMISD::VGETLANEu;
9871         break;
9872       }
9873       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9874     }
9875   }
9876
9877   return SDValue();
9878 }
9879
9880 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9881 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9882 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9883                                        const ARMSubtarget *ST) {
9884   // If the target supports NEON, try to use vmax/vmin instructions for f32
9885   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9886   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9887   // a NaN; only do the transformation when it matches that behavior.
9888
9889   // For now only do this when using NEON for FP operations; if using VFP, it
9890   // is not obvious that the benefit outweighs the cost of switching to the
9891   // NEON pipeline.
9892   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9893       N->getValueType(0) != MVT::f32)
9894     return SDValue();
9895
9896   SDValue CondLHS = N->getOperand(0);
9897   SDValue CondRHS = N->getOperand(1);
9898   SDValue LHS = N->getOperand(2);
9899   SDValue RHS = N->getOperand(3);
9900   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9901
9902   unsigned Opcode = 0;
9903   bool IsReversed;
9904   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9905     IsReversed = false; // x CC y ? x : y
9906   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9907     IsReversed = true ; // x CC y ? y : x
9908   } else {
9909     return SDValue();
9910   }
9911
9912   bool IsUnordered;
9913   switch (CC) {
9914   default: break;
9915   case ISD::SETOLT:
9916   case ISD::SETOLE:
9917   case ISD::SETLT:
9918   case ISD::SETLE:
9919   case ISD::SETULT:
9920   case ISD::SETULE:
9921     // If LHS is NaN, an ordered comparison will be false and the result will
9922     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9923     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9924     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9925     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9926       break;
9927     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9928     // will return -0, so vmin can only be used for unsafe math or if one of
9929     // the operands is known to be nonzero.
9930     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9931         !DAG.getTarget().Options.UnsafeFPMath &&
9932         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9933       break;
9934     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9935     break;
9936
9937   case ISD::SETOGT:
9938   case ISD::SETOGE:
9939   case ISD::SETGT:
9940   case ISD::SETGE:
9941   case ISD::SETUGT:
9942   case ISD::SETUGE:
9943     // If LHS is NaN, an ordered comparison will be false and the result will
9944     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9945     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9946     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9947     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9948       break;
9949     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9950     // will return +0, so vmax can only be used for unsafe math or if one of
9951     // the operands is known to be nonzero.
9952     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9953         !DAG.getTarget().Options.UnsafeFPMath &&
9954         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9955       break;
9956     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9957     break;
9958   }
9959
9960   if (!Opcode)
9961     return SDValue();
9962   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9963 }
9964
9965 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9966 SDValue
9967 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9968   SDValue Cmp = N->getOperand(4);
9969   if (Cmp.getOpcode() != ARMISD::CMPZ)
9970     // Only looking at EQ and NE cases.
9971     return SDValue();
9972
9973   EVT VT = N->getValueType(0);
9974   SDLoc dl(N);
9975   SDValue LHS = Cmp.getOperand(0);
9976   SDValue RHS = Cmp.getOperand(1);
9977   SDValue FalseVal = N->getOperand(0);
9978   SDValue TrueVal = N->getOperand(1);
9979   SDValue ARMcc = N->getOperand(2);
9980   ARMCC::CondCodes CC =
9981     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9982
9983   // Simplify
9984   //   mov     r1, r0
9985   //   cmp     r1, x
9986   //   mov     r0, y
9987   //   moveq   r0, x
9988   // to
9989   //   cmp     r0, x
9990   //   movne   r0, y
9991   //
9992   //   mov     r1, r0
9993   //   cmp     r1, x
9994   //   mov     r0, x
9995   //   movne   r0, y
9996   // to
9997   //   cmp     r0, x
9998   //   movne   r0, y
9999   /// FIXME: Turn this into a target neutral optimization?
10000   SDValue Res;
10001   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10002     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10003                       N->getOperand(3), Cmp);
10004   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10005     SDValue ARMcc;
10006     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10007     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10008                       N->getOperand(3), NewCmp);
10009   }
10010
10011   if (Res.getNode()) {
10012     APInt KnownZero, KnownOne;
10013     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
10014     // Capture demanded bits information that would be otherwise lost.
10015     if (KnownZero == 0xfffffffe)
10016       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10017                         DAG.getValueType(MVT::i1));
10018     else if (KnownZero == 0xffffff00)
10019       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10020                         DAG.getValueType(MVT::i8));
10021     else if (KnownZero == 0xffff0000)
10022       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10023                         DAG.getValueType(MVT::i16));
10024   }
10025
10026   return Res;
10027 }
10028
10029 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10030                                              DAGCombinerInfo &DCI) const {
10031   switch (N->getOpcode()) {
10032   default: break;
10033   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
10034   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
10035   case ISD::SUB:        return PerformSUBCombine(N, DCI);
10036   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
10037   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
10038   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
10039   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
10040   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
10041   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
10042   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10043   case ISD::STORE:      return PerformSTORECombine(N, DCI);
10044   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
10045   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10046   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10047   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10048   case ISD::FP_TO_SINT:
10049   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10050   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
10051   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10052   case ISD::SHL:
10053   case ISD::SRA:
10054   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10055   case ISD::SIGN_EXTEND:
10056   case ISD::ZERO_EXTEND:
10057   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10058   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
10059   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10060   case ARMISD::VLD2DUP:
10061   case ARMISD::VLD3DUP:
10062   case ARMISD::VLD4DUP:
10063     return CombineBaseUpdate(N, DCI);
10064   case ARMISD::BUILD_VECTOR:
10065     return PerformARMBUILD_VECTORCombine(N, DCI);
10066   case ISD::INTRINSIC_VOID:
10067   case ISD::INTRINSIC_W_CHAIN:
10068     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10069     case Intrinsic::arm_neon_vld1:
10070     case Intrinsic::arm_neon_vld2:
10071     case Intrinsic::arm_neon_vld3:
10072     case Intrinsic::arm_neon_vld4:
10073     case Intrinsic::arm_neon_vld2lane:
10074     case Intrinsic::arm_neon_vld3lane:
10075     case Intrinsic::arm_neon_vld4lane:
10076     case Intrinsic::arm_neon_vst1:
10077     case Intrinsic::arm_neon_vst2:
10078     case Intrinsic::arm_neon_vst3:
10079     case Intrinsic::arm_neon_vst4:
10080     case Intrinsic::arm_neon_vst2lane:
10081     case Intrinsic::arm_neon_vst3lane:
10082     case Intrinsic::arm_neon_vst4lane:
10083       return CombineBaseUpdate(N, DCI);
10084     default: break;
10085     }
10086     break;
10087   }
10088   return SDValue();
10089 }
10090
10091 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10092                                                           EVT VT) const {
10093   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10094 }
10095
10096 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
10097   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10098   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10099
10100   switch (VT.getSimpleVT().SimpleTy) {
10101   default:
10102     return false;
10103   case MVT::i8:
10104   case MVT::i16:
10105   case MVT::i32: {
10106     // Unaligned access can use (for example) LRDB, LRDH, LDR
10107     if (AllowsUnaligned) {
10108       if (Fast)
10109         *Fast = Subtarget->hasV7Ops();
10110       return true;
10111     }
10112     return false;
10113   }
10114   case MVT::f64:
10115   case MVT::v2f64: {
10116     // For any little-endian targets with neon, we can support unaligned ld/st
10117     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10118     // A big-endian target may also explictly support unaligned accesses
10119     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
10120       if (Fast)
10121         *Fast = true;
10122       return true;
10123     }
10124     return false;
10125   }
10126   }
10127 }
10128
10129 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10130                        unsigned AlignCheck) {
10131   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10132           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10133 }
10134
10135 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10136                                            unsigned DstAlign, unsigned SrcAlign,
10137                                            bool IsMemset, bool ZeroMemset,
10138                                            bool MemcpyStrSrc,
10139                                            MachineFunction &MF) const {
10140   const Function *F = MF.getFunction();
10141
10142   // See if we can use NEON instructions for this...
10143   if ((!IsMemset || ZeroMemset) &&
10144       Subtarget->hasNEON() &&
10145       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
10146                                        Attribute::NoImplicitFloat)) {
10147     bool Fast;
10148     if (Size >= 16 &&
10149         (memOpAlign(SrcAlign, DstAlign, 16) ||
10150          (allowsUnalignedMemoryAccesses(MVT::v2f64, &Fast) && Fast))) {
10151       return MVT::v2f64;
10152     } else if (Size >= 8 &&
10153                (memOpAlign(SrcAlign, DstAlign, 8) ||
10154                 (allowsUnalignedMemoryAccesses(MVT::f64, &Fast) && Fast))) {
10155       return MVT::f64;
10156     }
10157   }
10158
10159   // Lowering to i32/i16 if the size permits.
10160   if (Size >= 4)
10161     return MVT::i32;
10162   else if (Size >= 2)
10163     return MVT::i16;
10164
10165   // Let the target-independent logic figure it out.
10166   return MVT::Other;
10167 }
10168
10169 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10170   if (Val.getOpcode() != ISD::LOAD)
10171     return false;
10172
10173   EVT VT1 = Val.getValueType();
10174   if (!VT1.isSimple() || !VT1.isInteger() ||
10175       !VT2.isSimple() || !VT2.isInteger())
10176     return false;
10177
10178   switch (VT1.getSimpleVT().SimpleTy) {
10179   default: break;
10180   case MVT::i1:
10181   case MVT::i8:
10182   case MVT::i16:
10183     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10184     return true;
10185   }
10186
10187   return false;
10188 }
10189
10190 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10191   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10192     return false;
10193
10194   if (!isTypeLegal(EVT::getEVT(Ty1)))
10195     return false;
10196
10197   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10198
10199   // Assuming the caller doesn't have a zeroext or signext return parameter,
10200   // truncation all the way down to i1 is valid.
10201   return true;
10202 }
10203
10204
10205 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10206   if (V < 0)
10207     return false;
10208
10209   unsigned Scale = 1;
10210   switch (VT.getSimpleVT().SimpleTy) {
10211   default: return false;
10212   case MVT::i1:
10213   case MVT::i8:
10214     // Scale == 1;
10215     break;
10216   case MVT::i16:
10217     // Scale == 2;
10218     Scale = 2;
10219     break;
10220   case MVT::i32:
10221     // Scale == 4;
10222     Scale = 4;
10223     break;
10224   }
10225
10226   if ((V & (Scale - 1)) != 0)
10227     return false;
10228   V /= Scale;
10229   return V == (V & ((1LL << 5) - 1));
10230 }
10231
10232 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10233                                       const ARMSubtarget *Subtarget) {
10234   bool isNeg = false;
10235   if (V < 0) {
10236     isNeg = true;
10237     V = - V;
10238   }
10239
10240   switch (VT.getSimpleVT().SimpleTy) {
10241   default: return false;
10242   case MVT::i1:
10243   case MVT::i8:
10244   case MVT::i16:
10245   case MVT::i32:
10246     // + imm12 or - imm8
10247     if (isNeg)
10248       return V == (V & ((1LL << 8) - 1));
10249     return V == (V & ((1LL << 12) - 1));
10250   case MVT::f32:
10251   case MVT::f64:
10252     // Same as ARM mode. FIXME: NEON?
10253     if (!Subtarget->hasVFP2())
10254       return false;
10255     if ((V & 3) != 0)
10256       return false;
10257     V >>= 2;
10258     return V == (V & ((1LL << 8) - 1));
10259   }
10260 }
10261
10262 /// isLegalAddressImmediate - Return true if the integer value can be used
10263 /// as the offset of the target addressing mode for load / store of the
10264 /// given type.
10265 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10266                                     const ARMSubtarget *Subtarget) {
10267   if (V == 0)
10268     return true;
10269
10270   if (!VT.isSimple())
10271     return false;
10272
10273   if (Subtarget->isThumb1Only())
10274     return isLegalT1AddressImmediate(V, VT);
10275   else if (Subtarget->isThumb2())
10276     return isLegalT2AddressImmediate(V, VT, Subtarget);
10277
10278   // ARM mode.
10279   if (V < 0)
10280     V = - V;
10281   switch (VT.getSimpleVT().SimpleTy) {
10282   default: return false;
10283   case MVT::i1:
10284   case MVT::i8:
10285   case MVT::i32:
10286     // +- imm12
10287     return V == (V & ((1LL << 12) - 1));
10288   case MVT::i16:
10289     // +- imm8
10290     return V == (V & ((1LL << 8) - 1));
10291   case MVT::f32:
10292   case MVT::f64:
10293     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10294       return false;
10295     if ((V & 3) != 0)
10296       return false;
10297     V >>= 2;
10298     return V == (V & ((1LL << 8) - 1));
10299   }
10300 }
10301
10302 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10303                                                       EVT VT) const {
10304   int Scale = AM.Scale;
10305   if (Scale < 0)
10306     return false;
10307
10308   switch (VT.getSimpleVT().SimpleTy) {
10309   default: return false;
10310   case MVT::i1:
10311   case MVT::i8:
10312   case MVT::i16:
10313   case MVT::i32:
10314     if (Scale == 1)
10315       return true;
10316     // r + r << imm
10317     Scale = Scale & ~1;
10318     return Scale == 2 || Scale == 4 || Scale == 8;
10319   case MVT::i64:
10320     // r + r
10321     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10322       return true;
10323     return false;
10324   case MVT::isVoid:
10325     // Note, we allow "void" uses (basically, uses that aren't loads or
10326     // stores), because arm allows folding a scale into many arithmetic
10327     // operations.  This should be made more precise and revisited later.
10328
10329     // Allow r << imm, but the imm has to be a multiple of two.
10330     if (Scale & 1) return false;
10331     return isPowerOf2_32(Scale);
10332   }
10333 }
10334
10335 /// isLegalAddressingMode - Return true if the addressing mode represented
10336 /// by AM is legal for this target, for a load/store of the specified type.
10337 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10338                                               Type *Ty) const {
10339   EVT VT = getValueType(Ty, true);
10340   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10341     return false;
10342
10343   // Can never fold addr of global into load/store.
10344   if (AM.BaseGV)
10345     return false;
10346
10347   switch (AM.Scale) {
10348   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10349     break;
10350   case 1:
10351     if (Subtarget->isThumb1Only())
10352       return false;
10353     // FALL THROUGH.
10354   default:
10355     // ARM doesn't support any R+R*scale+imm addr modes.
10356     if (AM.BaseOffs)
10357       return false;
10358
10359     if (!VT.isSimple())
10360       return false;
10361
10362     if (Subtarget->isThumb2())
10363       return isLegalT2ScaledAddressingMode(AM, VT);
10364
10365     int Scale = AM.Scale;
10366     switch (VT.getSimpleVT().SimpleTy) {
10367     default: return false;
10368     case MVT::i1:
10369     case MVT::i8:
10370     case MVT::i32:
10371       if (Scale < 0) Scale = -Scale;
10372       if (Scale == 1)
10373         return true;
10374       // r + r << imm
10375       return isPowerOf2_32(Scale & ~1);
10376     case MVT::i16:
10377     case MVT::i64:
10378       // r + r
10379       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10380         return true;
10381       return false;
10382
10383     case MVT::isVoid:
10384       // Note, we allow "void" uses (basically, uses that aren't loads or
10385       // stores), because arm allows folding a scale into many arithmetic
10386       // operations.  This should be made more precise and revisited later.
10387
10388       // Allow r << imm, but the imm has to be a multiple of two.
10389       if (Scale & 1) return false;
10390       return isPowerOf2_32(Scale);
10391     }
10392   }
10393   return true;
10394 }
10395
10396 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10397 /// icmp immediate, that is the target has icmp instructions which can compare
10398 /// a register against the immediate without having to materialize the
10399 /// immediate into a register.
10400 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10401   // Thumb2 and ARM modes can use cmn for negative immediates.
10402   if (!Subtarget->isThumb())
10403     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10404   if (Subtarget->isThumb2())
10405     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10406   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10407   return Imm >= 0 && Imm <= 255;
10408 }
10409
10410 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10411 /// *or sub* immediate, that is the target has add or sub instructions which can
10412 /// add a register with the immediate without having to materialize the
10413 /// immediate into a register.
10414 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10415   // Same encoding for add/sub, just flip the sign.
10416   int64_t AbsImm = llvm::abs64(Imm);
10417   if (!Subtarget->isThumb())
10418     return ARM_AM::getSOImmVal(AbsImm) != -1;
10419   if (Subtarget->isThumb2())
10420     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10421   // Thumb1 only has 8-bit unsigned immediate.
10422   return AbsImm >= 0 && AbsImm <= 255;
10423 }
10424
10425 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10426                                       bool isSEXTLoad, SDValue &Base,
10427                                       SDValue &Offset, bool &isInc,
10428                                       SelectionDAG &DAG) {
10429   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10430     return false;
10431
10432   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10433     // AddressingMode 3
10434     Base = Ptr->getOperand(0);
10435     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10436       int RHSC = (int)RHS->getZExtValue();
10437       if (RHSC < 0 && RHSC > -256) {
10438         assert(Ptr->getOpcode() == ISD::ADD);
10439         isInc = false;
10440         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10441         return true;
10442       }
10443     }
10444     isInc = (Ptr->getOpcode() == ISD::ADD);
10445     Offset = Ptr->getOperand(1);
10446     return true;
10447   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10448     // AddressingMode 2
10449     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10450       int RHSC = (int)RHS->getZExtValue();
10451       if (RHSC < 0 && RHSC > -0x1000) {
10452         assert(Ptr->getOpcode() == ISD::ADD);
10453         isInc = false;
10454         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10455         Base = Ptr->getOperand(0);
10456         return true;
10457       }
10458     }
10459
10460     if (Ptr->getOpcode() == ISD::ADD) {
10461       isInc = true;
10462       ARM_AM::ShiftOpc ShOpcVal=
10463         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10464       if (ShOpcVal != ARM_AM::no_shift) {
10465         Base = Ptr->getOperand(1);
10466         Offset = Ptr->getOperand(0);
10467       } else {
10468         Base = Ptr->getOperand(0);
10469         Offset = Ptr->getOperand(1);
10470       }
10471       return true;
10472     }
10473
10474     isInc = (Ptr->getOpcode() == ISD::ADD);
10475     Base = Ptr->getOperand(0);
10476     Offset = Ptr->getOperand(1);
10477     return true;
10478   }
10479
10480   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10481   return false;
10482 }
10483
10484 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10485                                      bool isSEXTLoad, SDValue &Base,
10486                                      SDValue &Offset, bool &isInc,
10487                                      SelectionDAG &DAG) {
10488   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10489     return false;
10490
10491   Base = Ptr->getOperand(0);
10492   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10493     int RHSC = (int)RHS->getZExtValue();
10494     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10495       assert(Ptr->getOpcode() == ISD::ADD);
10496       isInc = false;
10497       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10498       return true;
10499     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10500       isInc = Ptr->getOpcode() == ISD::ADD;
10501       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10502       return true;
10503     }
10504   }
10505
10506   return false;
10507 }
10508
10509 /// getPreIndexedAddressParts - returns true by value, base pointer and
10510 /// offset pointer and addressing mode by reference if the node's address
10511 /// can be legally represented as pre-indexed load / store address.
10512 bool
10513 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10514                                              SDValue &Offset,
10515                                              ISD::MemIndexedMode &AM,
10516                                              SelectionDAG &DAG) const {
10517   if (Subtarget->isThumb1Only())
10518     return false;
10519
10520   EVT VT;
10521   SDValue Ptr;
10522   bool isSEXTLoad = false;
10523   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10524     Ptr = LD->getBasePtr();
10525     VT  = LD->getMemoryVT();
10526     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10527   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10528     Ptr = ST->getBasePtr();
10529     VT  = ST->getMemoryVT();
10530   } else
10531     return false;
10532
10533   bool isInc;
10534   bool isLegal = false;
10535   if (Subtarget->isThumb2())
10536     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10537                                        Offset, isInc, DAG);
10538   else
10539     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10540                                         Offset, isInc, DAG);
10541   if (!isLegal)
10542     return false;
10543
10544   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10545   return true;
10546 }
10547
10548 /// getPostIndexedAddressParts - returns true by value, base pointer and
10549 /// offset pointer and addressing mode by reference if this node can be
10550 /// combined with a load / store to form a post-indexed load / store.
10551 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10552                                                    SDValue &Base,
10553                                                    SDValue &Offset,
10554                                                    ISD::MemIndexedMode &AM,
10555                                                    SelectionDAG &DAG) const {
10556   if (Subtarget->isThumb1Only())
10557     return false;
10558
10559   EVT VT;
10560   SDValue Ptr;
10561   bool isSEXTLoad = false;
10562   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10563     VT  = LD->getMemoryVT();
10564     Ptr = LD->getBasePtr();
10565     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10566   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10567     VT  = ST->getMemoryVT();
10568     Ptr = ST->getBasePtr();
10569   } else
10570     return false;
10571
10572   bool isInc;
10573   bool isLegal = false;
10574   if (Subtarget->isThumb2())
10575     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10576                                        isInc, DAG);
10577   else
10578     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10579                                         isInc, DAG);
10580   if (!isLegal)
10581     return false;
10582
10583   if (Ptr != Base) {
10584     // Swap base ptr and offset to catch more post-index load / store when
10585     // it's legal. In Thumb2 mode, offset must be an immediate.
10586     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10587         !Subtarget->isThumb2())
10588       std::swap(Base, Offset);
10589
10590     // Post-indexed load / store update the base pointer.
10591     if (Ptr != Base)
10592       return false;
10593   }
10594
10595   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10596   return true;
10597 }
10598
10599 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10600                                                        APInt &KnownZero,
10601                                                        APInt &KnownOne,
10602                                                        const SelectionDAG &DAG,
10603                                                        unsigned Depth) const {
10604   unsigned BitWidth = KnownOne.getBitWidth();
10605   KnownZero = KnownOne = APInt(BitWidth, 0);
10606   switch (Op.getOpcode()) {
10607   default: break;
10608   case ARMISD::ADDC:
10609   case ARMISD::ADDE:
10610   case ARMISD::SUBC:
10611   case ARMISD::SUBE:
10612     // These nodes' second result is a boolean
10613     if (Op.getResNo() == 0)
10614       break;
10615     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10616     break;
10617   case ARMISD::CMOV: {
10618     // Bits are known zero/one if known on the LHS and RHS.
10619     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10620     if (KnownZero == 0 && KnownOne == 0) return;
10621
10622     APInt KnownZeroRHS, KnownOneRHS;
10623     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10624     KnownZero &= KnownZeroRHS;
10625     KnownOne  &= KnownOneRHS;
10626     return;
10627   }
10628   }
10629 }
10630
10631 //===----------------------------------------------------------------------===//
10632 //                           ARM Inline Assembly Support
10633 //===----------------------------------------------------------------------===//
10634
10635 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10636   // Looking for "rev" which is V6+.
10637   if (!Subtarget->hasV6Ops())
10638     return false;
10639
10640   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10641   std::string AsmStr = IA->getAsmString();
10642   SmallVector<StringRef, 4> AsmPieces;
10643   SplitString(AsmStr, AsmPieces, ";\n");
10644
10645   switch (AsmPieces.size()) {
10646   default: return false;
10647   case 1:
10648     AsmStr = AsmPieces[0];
10649     AsmPieces.clear();
10650     SplitString(AsmStr, AsmPieces, " \t,");
10651
10652     // rev $0, $1
10653     if (AsmPieces.size() == 3 &&
10654         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10655         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10656       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10657       if (Ty && Ty->getBitWidth() == 32)
10658         return IntrinsicLowering::LowerToByteSwap(CI);
10659     }
10660     break;
10661   }
10662
10663   return false;
10664 }
10665
10666 /// getConstraintType - Given a constraint letter, return the type of
10667 /// constraint it is for this target.
10668 ARMTargetLowering::ConstraintType
10669 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10670   if (Constraint.size() == 1) {
10671     switch (Constraint[0]) {
10672     default:  break;
10673     case 'l': return C_RegisterClass;
10674     case 'w': return C_RegisterClass;
10675     case 'h': return C_RegisterClass;
10676     case 'x': return C_RegisterClass;
10677     case 't': return C_RegisterClass;
10678     case 'j': return C_Other; // Constant for movw.
10679       // An address with a single base register. Due to the way we
10680       // currently handle addresses it is the same as an 'r' memory constraint.
10681     case 'Q': return C_Memory;
10682     }
10683   } else if (Constraint.size() == 2) {
10684     switch (Constraint[0]) {
10685     default: break;
10686     // All 'U+' constraints are addresses.
10687     case 'U': return C_Memory;
10688     }
10689   }
10690   return TargetLowering::getConstraintType(Constraint);
10691 }
10692
10693 /// Examine constraint type and operand type and determine a weight value.
10694 /// This object must already have been set up with the operand type
10695 /// and the current alternative constraint selected.
10696 TargetLowering::ConstraintWeight
10697 ARMTargetLowering::getSingleConstraintMatchWeight(
10698     AsmOperandInfo &info, const char *constraint) const {
10699   ConstraintWeight weight = CW_Invalid;
10700   Value *CallOperandVal = info.CallOperandVal;
10701     // If we don't have a value, we can't do a match,
10702     // but allow it at the lowest weight.
10703   if (CallOperandVal == NULL)
10704     return CW_Default;
10705   Type *type = CallOperandVal->getType();
10706   // Look at the constraint type.
10707   switch (*constraint) {
10708   default:
10709     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10710     break;
10711   case 'l':
10712     if (type->isIntegerTy()) {
10713       if (Subtarget->isThumb())
10714         weight = CW_SpecificReg;
10715       else
10716         weight = CW_Register;
10717     }
10718     break;
10719   case 'w':
10720     if (type->isFloatingPointTy())
10721       weight = CW_Register;
10722     break;
10723   }
10724   return weight;
10725 }
10726
10727 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10728 RCPair
10729 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10730                                                 MVT VT) const {
10731   if (Constraint.size() == 1) {
10732     // GCC ARM Constraint Letters
10733     switch (Constraint[0]) {
10734     case 'l': // Low regs or general regs.
10735       if (Subtarget->isThumb())
10736         return RCPair(0U, &ARM::tGPRRegClass);
10737       return RCPair(0U, &ARM::GPRRegClass);
10738     case 'h': // High regs or no regs.
10739       if (Subtarget->isThumb())
10740         return RCPair(0U, &ARM::hGPRRegClass);
10741       break;
10742     case 'r':
10743       return RCPair(0U, &ARM::GPRRegClass);
10744     case 'w':
10745       if (VT == MVT::f32)
10746         return RCPair(0U, &ARM::SPRRegClass);
10747       if (VT.getSizeInBits() == 64)
10748         return RCPair(0U, &ARM::DPRRegClass);
10749       if (VT.getSizeInBits() == 128)
10750         return RCPair(0U, &ARM::QPRRegClass);
10751       break;
10752     case 'x':
10753       if (VT == MVT::f32)
10754         return RCPair(0U, &ARM::SPR_8RegClass);
10755       if (VT.getSizeInBits() == 64)
10756         return RCPair(0U, &ARM::DPR_8RegClass);
10757       if (VT.getSizeInBits() == 128)
10758         return RCPair(0U, &ARM::QPR_8RegClass);
10759       break;
10760     case 't':
10761       if (VT == MVT::f32)
10762         return RCPair(0U, &ARM::SPRRegClass);
10763       break;
10764     }
10765   }
10766   if (StringRef("{cc}").equals_lower(Constraint))
10767     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10768
10769   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10770 }
10771
10772 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10773 /// vector.  If it is invalid, don't add anything to Ops.
10774 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10775                                                      std::string &Constraint,
10776                                                      std::vector<SDValue>&Ops,
10777                                                      SelectionDAG &DAG) const {
10778   SDValue Result(0, 0);
10779
10780   // Currently only support length 1 constraints.
10781   if (Constraint.length() != 1) return;
10782
10783   char ConstraintLetter = Constraint[0];
10784   switch (ConstraintLetter) {
10785   default: break;
10786   case 'j':
10787   case 'I': case 'J': case 'K': case 'L':
10788   case 'M': case 'N': case 'O':
10789     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10790     if (!C)
10791       return;
10792
10793     int64_t CVal64 = C->getSExtValue();
10794     int CVal = (int) CVal64;
10795     // None of these constraints allow values larger than 32 bits.  Check
10796     // that the value fits in an int.
10797     if (CVal != CVal64)
10798       return;
10799
10800     switch (ConstraintLetter) {
10801       case 'j':
10802         // Constant suitable for movw, must be between 0 and
10803         // 65535.
10804         if (Subtarget->hasV6T2Ops())
10805           if (CVal >= 0 && CVal <= 65535)
10806             break;
10807         return;
10808       case 'I':
10809         if (Subtarget->isThumb1Only()) {
10810           // This must be a constant between 0 and 255, for ADD
10811           // immediates.
10812           if (CVal >= 0 && CVal <= 255)
10813             break;
10814         } else if (Subtarget->isThumb2()) {
10815           // A constant that can be used as an immediate value in a
10816           // data-processing instruction.
10817           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10818             break;
10819         } else {
10820           // A constant that can be used as an immediate value in a
10821           // data-processing instruction.
10822           if (ARM_AM::getSOImmVal(CVal) != -1)
10823             break;
10824         }
10825         return;
10826
10827       case 'J':
10828         if (Subtarget->isThumb()) {  // FIXME thumb2
10829           // This must be a constant between -255 and -1, for negated ADD
10830           // immediates. This can be used in GCC with an "n" modifier that
10831           // prints the negated value, for use with SUB instructions. It is
10832           // not useful otherwise but is implemented for compatibility.
10833           if (CVal >= -255 && CVal <= -1)
10834             break;
10835         } else {
10836           // This must be a constant between -4095 and 4095. It is not clear
10837           // what this constraint is intended for. Implemented for
10838           // compatibility with GCC.
10839           if (CVal >= -4095 && CVal <= 4095)
10840             break;
10841         }
10842         return;
10843
10844       case 'K':
10845         if (Subtarget->isThumb1Only()) {
10846           // A 32-bit value where only one byte has a nonzero value. Exclude
10847           // zero to match GCC. This constraint is used by GCC internally for
10848           // constants that can be loaded with a move/shift combination.
10849           // It is not useful otherwise but is implemented for compatibility.
10850           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10851             break;
10852         } else if (Subtarget->isThumb2()) {
10853           // A constant whose bitwise inverse can be used as an immediate
10854           // value in a data-processing instruction. This can be used in GCC
10855           // with a "B" modifier that prints the inverted value, for use with
10856           // BIC and MVN instructions. It is not useful otherwise but is
10857           // implemented for compatibility.
10858           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10859             break;
10860         } else {
10861           // A constant whose bitwise inverse can be used as an immediate
10862           // value in a data-processing instruction. This can be used in GCC
10863           // with a "B" modifier that prints the inverted value, for use with
10864           // BIC and MVN instructions. It is not useful otherwise but is
10865           // implemented for compatibility.
10866           if (ARM_AM::getSOImmVal(~CVal) != -1)
10867             break;
10868         }
10869         return;
10870
10871       case 'L':
10872         if (Subtarget->isThumb1Only()) {
10873           // This must be a constant between -7 and 7,
10874           // for 3-operand ADD/SUB immediate instructions.
10875           if (CVal >= -7 && CVal < 7)
10876             break;
10877         } else if (Subtarget->isThumb2()) {
10878           // A constant whose negation can be used as an immediate value in a
10879           // data-processing instruction. This can be used in GCC with an "n"
10880           // modifier that prints the negated value, for use with SUB
10881           // instructions. It is not useful otherwise but is implemented for
10882           // compatibility.
10883           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10884             break;
10885         } else {
10886           // A constant whose negation can be used as an immediate value in a
10887           // data-processing instruction. This can be used in GCC with an "n"
10888           // modifier that prints the negated value, for use with SUB
10889           // instructions. It is not useful otherwise but is implemented for
10890           // compatibility.
10891           if (ARM_AM::getSOImmVal(-CVal) != -1)
10892             break;
10893         }
10894         return;
10895
10896       case 'M':
10897         if (Subtarget->isThumb()) { // FIXME thumb2
10898           // This must be a multiple of 4 between 0 and 1020, for
10899           // ADD sp + immediate.
10900           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10901             break;
10902         } else {
10903           // A power of two or a constant between 0 and 32.  This is used in
10904           // GCC for the shift amount on shifted register operands, but it is
10905           // useful in general for any shift amounts.
10906           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10907             break;
10908         }
10909         return;
10910
10911       case 'N':
10912         if (Subtarget->isThumb()) {  // FIXME thumb2
10913           // This must be a constant between 0 and 31, for shift amounts.
10914           if (CVal >= 0 && CVal <= 31)
10915             break;
10916         }
10917         return;
10918
10919       case 'O':
10920         if (Subtarget->isThumb()) {  // FIXME thumb2
10921           // This must be a multiple of 4 between -508 and 508, for
10922           // ADD/SUB sp = sp + immediate.
10923           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10924             break;
10925         }
10926         return;
10927     }
10928     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10929     break;
10930   }
10931
10932   if (Result.getNode()) {
10933     Ops.push_back(Result);
10934     return;
10935   }
10936   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10937 }
10938
10939 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10940   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10941   unsigned Opcode = Op->getOpcode();
10942   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10943       "Invalid opcode for Div/Rem lowering");
10944   bool isSigned = (Opcode == ISD::SDIVREM);
10945   EVT VT = Op->getValueType(0);
10946   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10947
10948   RTLIB::Libcall LC;
10949   switch (VT.getSimpleVT().SimpleTy) {
10950   default: llvm_unreachable("Unexpected request for libcall!");
10951   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10952   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10953   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10954   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10955   }
10956
10957   SDValue InChain = DAG.getEntryNode();
10958
10959   TargetLowering::ArgListTy Args;
10960   TargetLowering::ArgListEntry Entry;
10961   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10962     EVT ArgVT = Op->getOperand(i).getValueType();
10963     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10964     Entry.Node = Op->getOperand(i);
10965     Entry.Ty = ArgTy;
10966     Entry.isSExt = isSigned;
10967     Entry.isZExt = !isSigned;
10968     Args.push_back(Entry);
10969   }
10970
10971   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10972                                          getPointerTy());
10973
10974   Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10975
10976   SDLoc dl(Op);
10977   TargetLowering::
10978   CallLoweringInfo CLI(InChain, RetTy, isSigned, !isSigned, false, true,
10979                     0, getLibcallCallingConv(LC), /*isTailCall=*/false,
10980                     /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
10981                     Callee, Args, DAG, dl);
10982   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10983
10984   return CallInfo.first;
10985 }
10986
10987 bool
10988 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10989   // The ARM target isn't yet aware of offsets.
10990   return false;
10991 }
10992
10993 bool ARM::isBitFieldInvertedMask(unsigned v) {
10994   if (v == 0xffffffff)
10995     return false;
10996
10997   // there can be 1's on either or both "outsides", all the "inside"
10998   // bits must be 0's
10999   unsigned TO = CountTrailingOnes_32(v);
11000   unsigned LO = CountLeadingOnes_32(v);
11001   v = (v >> TO) << TO;
11002   v = (v << LO) >> LO;
11003   return v == 0;
11004 }
11005
11006 /// isFPImmLegal - Returns true if the target can instruction select the
11007 /// specified FP immediate natively. If false, the legalizer will
11008 /// materialize the FP immediate as a load from a constant pool.
11009 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11010   if (!Subtarget->hasVFP3())
11011     return false;
11012   if (VT == MVT::f32)
11013     return ARM_AM::getFP32Imm(Imm) != -1;
11014   if (VT == MVT::f64)
11015     return ARM_AM::getFP64Imm(Imm) != -1;
11016   return false;
11017 }
11018
11019 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11020 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11021 /// specified in the intrinsic calls.
11022 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11023                                            const CallInst &I,
11024                                            unsigned Intrinsic) const {
11025   switch (Intrinsic) {
11026   case Intrinsic::arm_neon_vld1:
11027   case Intrinsic::arm_neon_vld2:
11028   case Intrinsic::arm_neon_vld3:
11029   case Intrinsic::arm_neon_vld4:
11030   case Intrinsic::arm_neon_vld2lane:
11031   case Intrinsic::arm_neon_vld3lane:
11032   case Intrinsic::arm_neon_vld4lane: {
11033     Info.opc = ISD::INTRINSIC_W_CHAIN;
11034     // Conservatively set memVT to the entire set of vectors loaded.
11035     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
11036     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11037     Info.ptrVal = I.getArgOperand(0);
11038     Info.offset = 0;
11039     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11040     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11041     Info.vol = false; // volatile loads with NEON intrinsics not supported
11042     Info.readMem = true;
11043     Info.writeMem = false;
11044     return true;
11045   }
11046   case Intrinsic::arm_neon_vst1:
11047   case Intrinsic::arm_neon_vst2:
11048   case Intrinsic::arm_neon_vst3:
11049   case Intrinsic::arm_neon_vst4:
11050   case Intrinsic::arm_neon_vst2lane:
11051   case Intrinsic::arm_neon_vst3lane:
11052   case Intrinsic::arm_neon_vst4lane: {
11053     Info.opc = ISD::INTRINSIC_VOID;
11054     // Conservatively set memVT to the entire set of vectors stored.
11055     unsigned NumElts = 0;
11056     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11057       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11058       if (!ArgTy->isVectorTy())
11059         break;
11060       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
11061     }
11062     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11063     Info.ptrVal = I.getArgOperand(0);
11064     Info.offset = 0;
11065     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11066     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11067     Info.vol = false; // volatile stores with NEON intrinsics not supported
11068     Info.readMem = false;
11069     Info.writeMem = true;
11070     return true;
11071   }
11072   case Intrinsic::arm_ldrex: {
11073     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11074     Info.opc = ISD::INTRINSIC_W_CHAIN;
11075     Info.memVT = MVT::getVT(PtrTy->getElementType());
11076     Info.ptrVal = I.getArgOperand(0);
11077     Info.offset = 0;
11078     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11079     Info.vol = true;
11080     Info.readMem = true;
11081     Info.writeMem = false;
11082     return true;
11083   }
11084   case Intrinsic::arm_strex: {
11085     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11086     Info.opc = ISD::INTRINSIC_W_CHAIN;
11087     Info.memVT = MVT::getVT(PtrTy->getElementType());
11088     Info.ptrVal = I.getArgOperand(1);
11089     Info.offset = 0;
11090     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11091     Info.vol = true;
11092     Info.readMem = false;
11093     Info.writeMem = true;
11094     return true;
11095   }
11096   case Intrinsic::arm_strexd: {
11097     Info.opc = ISD::INTRINSIC_W_CHAIN;
11098     Info.memVT = MVT::i64;
11099     Info.ptrVal = I.getArgOperand(2);
11100     Info.offset = 0;
11101     Info.align = 8;
11102     Info.vol = true;
11103     Info.readMem = false;
11104     Info.writeMem = true;
11105     return true;
11106   }
11107   case Intrinsic::arm_ldrexd: {
11108     Info.opc = ISD::INTRINSIC_W_CHAIN;
11109     Info.memVT = MVT::i64;
11110     Info.ptrVal = I.getArgOperand(0);
11111     Info.offset = 0;
11112     Info.align = 8;
11113     Info.vol = true;
11114     Info.readMem = true;
11115     Info.writeMem = false;
11116     return true;
11117   }
11118   default:
11119     break;
11120   }
11121
11122   return false;
11123 }