Fix PR 17368: disable vector mul distribution for square of add/sub for ARM
[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     // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
773     setInsertFencesForAtomic(true);
774   } else {
775     // Set them all for expansion, which will force libcalls.
776     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
777     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
778     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
779     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
780     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
781     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
782     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
783     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
784     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
785     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
786     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
787     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
788     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
789     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
790     // Unordered/Monotonic case.
791     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
792     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
793   }
794
795   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
796
797   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
798   if (!Subtarget->hasV6Ops()) {
799     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
800     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
801   }
802   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
803
804   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
805       !Subtarget->isThumb1Only()) {
806     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
807     // iff target supports vfp2.
808     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
809     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
810   }
811
812   // We want to custom lower some of our intrinsics.
813   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
814   if (Subtarget->isTargetDarwin()) {
815     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
816     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
817     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
818   }
819
820   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
821   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
822   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
823   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
824   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
825   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
826   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
827   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
828   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
829
830   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
831   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
832   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
833   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
834   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
835
836   // We don't support sin/cos/fmod/copysign/pow
837   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
838   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
839   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
840   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
841   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
842   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
843   setOperationAction(ISD::FREM,      MVT::f64, Expand);
844   setOperationAction(ISD::FREM,      MVT::f32, Expand);
845   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
846       !Subtarget->isThumb1Only()) {
847     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
848     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
849   }
850   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
851   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
852
853   if (!Subtarget->hasVFP4()) {
854     setOperationAction(ISD::FMA, MVT::f64, Expand);
855     setOperationAction(ISD::FMA, MVT::f32, Expand);
856   }
857
858   // Various VFP goodness
859   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
860     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
861     if (Subtarget->hasVFP2()) {
862       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
863       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
864       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
865       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
866     }
867     // Special handling for half-precision FP.
868     if (!Subtarget->hasFP16()) {
869       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
870       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
871     }
872   }
873
874   // We have target-specific dag combine patterns for the following nodes:
875   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
876   setTargetDAGCombine(ISD::ADD);
877   setTargetDAGCombine(ISD::SUB);
878   setTargetDAGCombine(ISD::MUL);
879   setTargetDAGCombine(ISD::AND);
880   setTargetDAGCombine(ISD::OR);
881   setTargetDAGCombine(ISD::XOR);
882
883   if (Subtarget->hasV6Ops())
884     setTargetDAGCombine(ISD::SRL);
885
886   setStackPointerRegisterToSaveRestore(ARM::SP);
887
888   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
889       !Subtarget->hasVFP2())
890     setSchedulingPreference(Sched::RegPressure);
891   else
892     setSchedulingPreference(Sched::Hybrid);
893
894   //// temporary - rewrite interface to use type
895   MaxStoresPerMemset = 8;
896   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
897   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
898   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
899   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
900   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
901
902   // On ARM arguments smaller than 4 bytes are extended, so all arguments
903   // are at least 4 bytes aligned.
904   setMinStackArgumentAlignment(4);
905
906   // Prefer likely predicted branches to selects on out-of-order cores.
907   PredictableSelectIsExpensive = Subtarget->isLikeA9();
908
909   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
910 }
911
912 // FIXME: It might make sense to define the representative register class as the
913 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
914 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
915 // SPR's representative would be DPR_VFP2. This should work well if register
916 // pressure tracking were modified such that a register use would increment the
917 // pressure of the register class's representative and all of it's super
918 // classes' representatives transitively. We have not implemented this because
919 // of the difficulty prior to coalescing of modeling operand register classes
920 // due to the common occurrence of cross class copies and subregister insertions
921 // and extractions.
922 std::pair<const TargetRegisterClass*, uint8_t>
923 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
924   const TargetRegisterClass *RRC = 0;
925   uint8_t Cost = 1;
926   switch (VT.SimpleTy) {
927   default:
928     return TargetLowering::findRepresentativeClass(VT);
929   // Use DPR as representative register class for all floating point
930   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
931   // the cost is 1 for both f32 and f64.
932   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
933   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
934     RRC = &ARM::DPRRegClass;
935     // When NEON is used for SP, only half of the register file is available
936     // because operations that define both SP and DP results will be constrained
937     // to the VFP2 class (D0-D15). We currently model this constraint prior to
938     // coalescing by double-counting the SP regs. See the FIXME above.
939     if (Subtarget->useNEONForSinglePrecisionFP())
940       Cost = 2;
941     break;
942   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
943   case MVT::v4f32: case MVT::v2f64:
944     RRC = &ARM::DPRRegClass;
945     Cost = 2;
946     break;
947   case MVT::v4i64:
948     RRC = &ARM::DPRRegClass;
949     Cost = 4;
950     break;
951   case MVT::v8i64:
952     RRC = &ARM::DPRRegClass;
953     Cost = 8;
954     break;
955   }
956   return std::make_pair(RRC, Cost);
957 }
958
959 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
960   switch (Opcode) {
961   default: return 0;
962   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
963   case ARMISD::WrapperDYN:    return "ARMISD::WrapperDYN";
964   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
965   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
966   case ARMISD::CALL:          return "ARMISD::CALL";
967   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
968   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
969   case ARMISD::tCALL:         return "ARMISD::tCALL";
970   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
971   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
972   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
973   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
974   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
975   case ARMISD::CMP:           return "ARMISD::CMP";
976   case ARMISD::CMN:           return "ARMISD::CMN";
977   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
978   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
979   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
980   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
981   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
982
983   case ARMISD::CMOV:          return "ARMISD::CMOV";
984
985   case ARMISD::RBIT:          return "ARMISD::RBIT";
986
987   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
988   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
989   case ARMISD::SITOF:         return "ARMISD::SITOF";
990   case ARMISD::UITOF:         return "ARMISD::UITOF";
991
992   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
993   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
994   case ARMISD::RRX:           return "ARMISD::RRX";
995
996   case ARMISD::ADDC:          return "ARMISD::ADDC";
997   case ARMISD::ADDE:          return "ARMISD::ADDE";
998   case ARMISD::SUBC:          return "ARMISD::SUBC";
999   case ARMISD::SUBE:          return "ARMISD::SUBE";
1000
1001   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1002   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1003
1004   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1005   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1006
1007   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1008
1009   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1010
1011   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1012
1013   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1014
1015   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1016
1017   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1018   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1019   case ARMISD::VCGE:          return "ARMISD::VCGE";
1020   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1021   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1022   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1023   case ARMISD::VCGT:          return "ARMISD::VCGT";
1024   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1025   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1026   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1027   case ARMISD::VTST:          return "ARMISD::VTST";
1028
1029   case ARMISD::VSHL:          return "ARMISD::VSHL";
1030   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1031   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1032   case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
1033   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
1034   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
1035   case ARMISD::VSHRN:         return "ARMISD::VSHRN";
1036   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1037   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1038   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1039   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1040   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1041   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1042   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1043   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1044   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1045   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1046   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1047   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1048   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1049   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1050   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1051   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1052   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1053   case ARMISD::VDUP:          return "ARMISD::VDUP";
1054   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1055   case ARMISD::VEXT:          return "ARMISD::VEXT";
1056   case ARMISD::VREV64:        return "ARMISD::VREV64";
1057   case ARMISD::VREV32:        return "ARMISD::VREV32";
1058   case ARMISD::VREV16:        return "ARMISD::VREV16";
1059   case ARMISD::VZIP:          return "ARMISD::VZIP";
1060   case ARMISD::VUZP:          return "ARMISD::VUZP";
1061   case ARMISD::VTRN:          return "ARMISD::VTRN";
1062   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1063   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1064   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1065   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1066   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1067   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1068   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1069   case ARMISD::FMAX:          return "ARMISD::FMAX";
1070   case ARMISD::FMIN:          return "ARMISD::FMIN";
1071   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1072   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1073   case ARMISD::BFI:           return "ARMISD::BFI";
1074   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1075   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1076   case ARMISD::VBSL:          return "ARMISD::VBSL";
1077   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1078   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1079   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1080   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1081   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1082   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1083   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1084   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1085   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1086   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1087   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1088   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1089   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1090   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1091   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1092   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1093   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1094   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1095   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1096   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1097
1098   case ARMISD::ATOMADD64_DAG:     return "ATOMADD64_DAG";
1099   case ARMISD::ATOMSUB64_DAG:     return "ATOMSUB64_DAG";
1100   case ARMISD::ATOMOR64_DAG:      return "ATOMOR64_DAG";
1101   case ARMISD::ATOMXOR64_DAG:     return "ATOMXOR64_DAG";
1102   case ARMISD::ATOMAND64_DAG:     return "ATOMAND64_DAG";
1103   case ARMISD::ATOMNAND64_DAG:    return "ATOMNAND64_DAG";
1104   case ARMISD::ATOMSWAP64_DAG:    return "ATOMSWAP64_DAG";
1105   case ARMISD::ATOMCMPXCHG64_DAG: return "ATOMCMPXCHG64_DAG";
1106   case ARMISD::ATOMMIN64_DAG:     return "ATOMMIN64_DAG";
1107   case ARMISD::ATOMUMIN64_DAG:    return "ATOMUMIN64_DAG";
1108   case ARMISD::ATOMMAX64_DAG:     return "ATOMMAX64_DAG";
1109   case ARMISD::ATOMUMAX64_DAG:    return "ATOMUMAX64_DAG";
1110   }
1111 }
1112
1113 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1114   if (!VT.isVector()) return getPointerTy();
1115   return VT.changeVectorElementTypeToInteger();
1116 }
1117
1118 /// getRegClassFor - Return the register class that should be used for the
1119 /// specified value type.
1120 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1121   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1122   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1123   // load / store 4 to 8 consecutive D registers.
1124   if (Subtarget->hasNEON()) {
1125     if (VT == MVT::v4i64)
1126       return &ARM::QQPRRegClass;
1127     if (VT == MVT::v8i64)
1128       return &ARM::QQQQPRRegClass;
1129   }
1130   return TargetLowering::getRegClassFor(VT);
1131 }
1132
1133 // Create a fast isel object.
1134 FastISel *
1135 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1136                                   const TargetLibraryInfo *libInfo) const {
1137   return ARM::createFastISel(funcInfo, libInfo);
1138 }
1139
1140 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1141 /// be used for loads / stores from the global.
1142 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1143   return (Subtarget->isThumb1Only() ? 127 : 4095);
1144 }
1145
1146 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1147   unsigned NumVals = N->getNumValues();
1148   if (!NumVals)
1149     return Sched::RegPressure;
1150
1151   for (unsigned i = 0; i != NumVals; ++i) {
1152     EVT VT = N->getValueType(i);
1153     if (VT == MVT::Glue || VT == MVT::Other)
1154       continue;
1155     if (VT.isFloatingPoint() || VT.isVector())
1156       return Sched::ILP;
1157   }
1158
1159   if (!N->isMachineOpcode())
1160     return Sched::RegPressure;
1161
1162   // Load are scheduled for latency even if there instruction itinerary
1163   // is not available.
1164   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1165   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1166
1167   if (MCID.getNumDefs() == 0)
1168     return Sched::RegPressure;
1169   if (!Itins->isEmpty() &&
1170       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1171     return Sched::ILP;
1172
1173   return Sched::RegPressure;
1174 }
1175
1176 //===----------------------------------------------------------------------===//
1177 // Lowering Code
1178 //===----------------------------------------------------------------------===//
1179
1180 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1181 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1182   switch (CC) {
1183   default: llvm_unreachable("Unknown condition code!");
1184   case ISD::SETNE:  return ARMCC::NE;
1185   case ISD::SETEQ:  return ARMCC::EQ;
1186   case ISD::SETGT:  return ARMCC::GT;
1187   case ISD::SETGE:  return ARMCC::GE;
1188   case ISD::SETLT:  return ARMCC::LT;
1189   case ISD::SETLE:  return ARMCC::LE;
1190   case ISD::SETUGT: return ARMCC::HI;
1191   case ISD::SETUGE: return ARMCC::HS;
1192   case ISD::SETULT: return ARMCC::LO;
1193   case ISD::SETULE: return ARMCC::LS;
1194   }
1195 }
1196
1197 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1198 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1199                         ARMCC::CondCodes &CondCode2) {
1200   CondCode2 = ARMCC::AL;
1201   switch (CC) {
1202   default: llvm_unreachable("Unknown FP condition!");
1203   case ISD::SETEQ:
1204   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1205   case ISD::SETGT:
1206   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1207   case ISD::SETGE:
1208   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1209   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1210   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1211   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1212   case ISD::SETO:   CondCode = ARMCC::VC; break;
1213   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1214   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1215   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1216   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1217   case ISD::SETLT:
1218   case ISD::SETULT: CondCode = ARMCC::LT; break;
1219   case ISD::SETLE:
1220   case ISD::SETULE: CondCode = ARMCC::LE; break;
1221   case ISD::SETNE:
1222   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1223   }
1224 }
1225
1226 //===----------------------------------------------------------------------===//
1227 //                      Calling Convention Implementation
1228 //===----------------------------------------------------------------------===//
1229
1230 #include "ARMGenCallingConv.inc"
1231
1232 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1233 /// given CallingConvention value.
1234 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1235                                                  bool Return,
1236                                                  bool isVarArg) const {
1237   switch (CC) {
1238   default:
1239     llvm_unreachable("Unsupported calling convention");
1240   case CallingConv::Fast:
1241     if (Subtarget->hasVFP2() && !isVarArg) {
1242       if (!Subtarget->isAAPCS_ABI())
1243         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1244       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1245       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1246     }
1247     // Fallthrough
1248   case CallingConv::C: {
1249     // Use target triple & subtarget features to do actual dispatch.
1250     if (!Subtarget->isAAPCS_ABI())
1251       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1252     else if (Subtarget->hasVFP2() &&
1253              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1254              !isVarArg)
1255       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1256     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1257   }
1258   case CallingConv::ARM_AAPCS_VFP:
1259     if (!isVarArg)
1260       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1261     // Fallthrough
1262   case CallingConv::ARM_AAPCS:
1263     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1264   case CallingConv::ARM_APCS:
1265     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1266   case CallingConv::GHC:
1267     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1268   }
1269 }
1270
1271 /// LowerCallResult - Lower the result values of a call into the
1272 /// appropriate copies out of appropriate physical registers.
1273 SDValue
1274 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1275                                    CallingConv::ID CallConv, bool isVarArg,
1276                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1277                                    SDLoc dl, SelectionDAG &DAG,
1278                                    SmallVectorImpl<SDValue> &InVals,
1279                                    bool isThisReturn, SDValue ThisVal) const {
1280
1281   // Assign locations to each value returned by this call.
1282   SmallVector<CCValAssign, 16> RVLocs;
1283   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1284                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1285   CCInfo.AnalyzeCallResult(Ins,
1286                            CCAssignFnForNode(CallConv, /* Return*/ true,
1287                                              isVarArg));
1288
1289   // Copy all of the result registers out of their specified physreg.
1290   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1291     CCValAssign VA = RVLocs[i];
1292
1293     // Pass 'this' value directly from the argument to return value, to avoid
1294     // reg unit interference
1295     if (i == 0 && isThisReturn) {
1296       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1297              "unexpected return calling convention register assignment");
1298       InVals.push_back(ThisVal);
1299       continue;
1300     }
1301
1302     SDValue Val;
1303     if (VA.needsCustom()) {
1304       // Handle f64 or half of a v2f64.
1305       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1306                                       InFlag);
1307       Chain = Lo.getValue(1);
1308       InFlag = Lo.getValue(2);
1309       VA = RVLocs[++i]; // skip ahead to next loc
1310       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1311                                       InFlag);
1312       Chain = Hi.getValue(1);
1313       InFlag = Hi.getValue(2);
1314       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1315
1316       if (VA.getLocVT() == MVT::v2f64) {
1317         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1318         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1319                           DAG.getConstant(0, MVT::i32));
1320
1321         VA = RVLocs[++i]; // skip ahead to next loc
1322         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1323         Chain = Lo.getValue(1);
1324         InFlag = Lo.getValue(2);
1325         VA = RVLocs[++i]; // skip ahead to next loc
1326         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1327         Chain = Hi.getValue(1);
1328         InFlag = Hi.getValue(2);
1329         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1330         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1331                           DAG.getConstant(1, MVT::i32));
1332       }
1333     } else {
1334       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1335                                InFlag);
1336       Chain = Val.getValue(1);
1337       InFlag = Val.getValue(2);
1338     }
1339
1340     switch (VA.getLocInfo()) {
1341     default: llvm_unreachable("Unknown loc info!");
1342     case CCValAssign::Full: break;
1343     case CCValAssign::BCvt:
1344       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1345       break;
1346     }
1347
1348     InVals.push_back(Val);
1349   }
1350
1351   return Chain;
1352 }
1353
1354 /// LowerMemOpCallTo - Store the argument to the stack.
1355 SDValue
1356 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1357                                     SDValue StackPtr, SDValue Arg,
1358                                     SDLoc dl, SelectionDAG &DAG,
1359                                     const CCValAssign &VA,
1360                                     ISD::ArgFlagsTy Flags) const {
1361   unsigned LocMemOffset = VA.getLocMemOffset();
1362   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1363   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1364   return DAG.getStore(Chain, dl, Arg, PtrOff,
1365                       MachinePointerInfo::getStack(LocMemOffset),
1366                       false, false, 0);
1367 }
1368
1369 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1370                                          SDValue Chain, SDValue &Arg,
1371                                          RegsToPassVector &RegsToPass,
1372                                          CCValAssign &VA, CCValAssign &NextVA,
1373                                          SDValue &StackPtr,
1374                                          SmallVectorImpl<SDValue> &MemOpChains,
1375                                          ISD::ArgFlagsTy Flags) const {
1376
1377   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1378                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1379   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1380
1381   if (NextVA.isRegLoc())
1382     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1383   else {
1384     assert(NextVA.isMemLoc());
1385     if (StackPtr.getNode() == 0)
1386       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1387
1388     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1389                                            dl, DAG, NextVA,
1390                                            Flags));
1391   }
1392 }
1393
1394 /// LowerCall - Lowering a call into a callseq_start <-
1395 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1396 /// nodes.
1397 SDValue
1398 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1399                              SmallVectorImpl<SDValue> &InVals) const {
1400   SelectionDAG &DAG                     = CLI.DAG;
1401   SDLoc &dl                          = CLI.DL;
1402   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1403   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1404   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1405   SDValue Chain                         = CLI.Chain;
1406   SDValue Callee                        = CLI.Callee;
1407   bool &isTailCall                      = CLI.IsTailCall;
1408   CallingConv::ID CallConv              = CLI.CallConv;
1409   bool doesNotRet                       = CLI.DoesNotReturn;
1410   bool isVarArg                         = CLI.IsVarArg;
1411
1412   MachineFunction &MF = DAG.getMachineFunction();
1413   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1414   bool isThisReturn   = false;
1415   bool isSibCall      = false;
1416   // Disable tail calls if they're not supported.
1417   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1418     isTailCall = false;
1419   if (isTailCall) {
1420     // Check if it's really possible to do a tail call.
1421     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1422                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1423                                                    Outs, OutVals, Ins, DAG);
1424     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1425     // detected sibcalls.
1426     if (isTailCall) {
1427       ++NumTailCalls;
1428       isSibCall = true;
1429     }
1430   }
1431
1432   // Analyze operands of the call, assigning locations to each operand.
1433   SmallVector<CCValAssign, 16> ArgLocs;
1434   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1435                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1436   CCInfo.AnalyzeCallOperands(Outs,
1437                              CCAssignFnForNode(CallConv, /* Return*/ false,
1438                                                isVarArg));
1439
1440   // Get a count of how many bytes are to be pushed on the stack.
1441   unsigned NumBytes = CCInfo.getNextStackOffset();
1442
1443   // For tail calls, memory operands are available in our caller's stack.
1444   if (isSibCall)
1445     NumBytes = 0;
1446
1447   // Adjust the stack pointer for the new arguments...
1448   // These operations are automatically eliminated by the prolog/epilog pass
1449   if (!isSibCall)
1450     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1451                                  dl);
1452
1453   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1454
1455   RegsToPassVector RegsToPass;
1456   SmallVector<SDValue, 8> MemOpChains;
1457
1458   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1459   // of tail call optimization, arguments are handled later.
1460   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1461        i != e;
1462        ++i, ++realArgIdx) {
1463     CCValAssign &VA = ArgLocs[i];
1464     SDValue Arg = OutVals[realArgIdx];
1465     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1466     bool isByVal = Flags.isByVal();
1467
1468     // Promote the value if needed.
1469     switch (VA.getLocInfo()) {
1470     default: llvm_unreachable("Unknown loc info!");
1471     case CCValAssign::Full: break;
1472     case CCValAssign::SExt:
1473       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1474       break;
1475     case CCValAssign::ZExt:
1476       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1477       break;
1478     case CCValAssign::AExt:
1479       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1480       break;
1481     case CCValAssign::BCvt:
1482       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1483       break;
1484     }
1485
1486     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1487     if (VA.needsCustom()) {
1488       if (VA.getLocVT() == MVT::v2f64) {
1489         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1490                                   DAG.getConstant(0, MVT::i32));
1491         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1492                                   DAG.getConstant(1, MVT::i32));
1493
1494         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1495                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1496
1497         VA = ArgLocs[++i]; // skip ahead to next loc
1498         if (VA.isRegLoc()) {
1499           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1500                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1501         } else {
1502           assert(VA.isMemLoc());
1503
1504           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1505                                                  dl, DAG, VA, Flags));
1506         }
1507       } else {
1508         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1509                          StackPtr, MemOpChains, Flags);
1510       }
1511     } else if (VA.isRegLoc()) {
1512       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1513         assert(VA.getLocVT() == MVT::i32 &&
1514                "unexpected calling convention register assignment");
1515         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1516                "unexpected use of 'returned'");
1517         isThisReturn = true;
1518       }
1519       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1520     } else if (isByVal) {
1521       assert(VA.isMemLoc());
1522       unsigned offset = 0;
1523
1524       // True if this byval aggregate will be split between registers
1525       // and memory.
1526       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1527       unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1528
1529       if (CurByValIdx < ByValArgsCount) {
1530
1531         unsigned RegBegin, RegEnd;
1532         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1533
1534         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1535         unsigned int i, j;
1536         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1537           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1538           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1539           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1540                                      MachinePointerInfo(),
1541                                      false, false, false, 0);
1542           MemOpChains.push_back(Load.getValue(1));
1543           RegsToPass.push_back(std::make_pair(j, Load));
1544         }
1545
1546         // If parameter size outsides register area, "offset" value
1547         // helps us to calculate stack slot for remained part properly.
1548         offset = RegEnd - RegBegin;
1549
1550         CCInfo.nextInRegsParam();
1551       }
1552
1553       if (Flags.getByValSize() > 4*offset) {
1554         unsigned LocMemOffset = VA.getLocMemOffset();
1555         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1556         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1557                                   StkPtrOff);
1558         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1559         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1560         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1561                                            MVT::i32);
1562         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1563
1564         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1565         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1566         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1567                                           Ops, array_lengthof(Ops)));
1568       }
1569     } else if (!isSibCall) {
1570       assert(VA.isMemLoc());
1571
1572       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1573                                              dl, DAG, VA, Flags));
1574     }
1575   }
1576
1577   if (!MemOpChains.empty())
1578     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1579                         &MemOpChains[0], MemOpChains.size());
1580
1581   // Build a sequence of copy-to-reg nodes chained together with token chain
1582   // and flag operands which copy the outgoing args into the appropriate regs.
1583   SDValue InFlag;
1584   // Tail call byval lowering might overwrite argument registers so in case of
1585   // tail call optimization the copies to registers are lowered later.
1586   if (!isTailCall)
1587     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1588       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1589                                RegsToPass[i].second, InFlag);
1590       InFlag = Chain.getValue(1);
1591     }
1592
1593   // For tail calls lower the arguments to the 'real' stack slot.
1594   if (isTailCall) {
1595     // Force all the incoming stack arguments to be loaded from the stack
1596     // before any new outgoing arguments are stored to the stack, because the
1597     // outgoing stack slots may alias the incoming argument stack slots, and
1598     // the alias isn't otherwise explicit. This is slightly more conservative
1599     // than necessary, because it means that each store effectively depends
1600     // on every argument instead of just those arguments it would clobber.
1601
1602     // Do not flag preceding copytoreg stuff together with the following stuff.
1603     InFlag = SDValue();
1604     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1605       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1606                                RegsToPass[i].second, InFlag);
1607       InFlag = Chain.getValue(1);
1608     }
1609     InFlag = SDValue();
1610   }
1611
1612   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1613   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1614   // node so that legalize doesn't hack it.
1615   bool isDirect = false;
1616   bool isARMFunc = false;
1617   bool isLocalARMFunc = false;
1618   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1619
1620   if (EnableARMLongCalls) {
1621     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1622             && "long-calls with non-static relocation model!");
1623     // Handle a global address or an external symbol. If it's not one of
1624     // those, the target's already in a register, so we don't need to do
1625     // anything extra.
1626     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1627       const GlobalValue *GV = G->getGlobal();
1628       // Create a constant pool entry for the callee address
1629       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1630       ARMConstantPoolValue *CPV =
1631         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1632
1633       // Get the address of the callee into a register
1634       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1635       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1636       Callee = DAG.getLoad(getPointerTy(), dl,
1637                            DAG.getEntryNode(), CPAddr,
1638                            MachinePointerInfo::getConstantPool(),
1639                            false, false, false, 0);
1640     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1641       const char *Sym = S->getSymbol();
1642
1643       // Create a constant pool entry for the callee address
1644       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1645       ARMConstantPoolValue *CPV =
1646         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1647                                       ARMPCLabelIndex, 0);
1648       // Get the address of the callee into a register
1649       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1650       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1651       Callee = DAG.getLoad(getPointerTy(), dl,
1652                            DAG.getEntryNode(), CPAddr,
1653                            MachinePointerInfo::getConstantPool(),
1654                            false, false, false, 0);
1655     }
1656   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1657     const GlobalValue *GV = G->getGlobal();
1658     isDirect = true;
1659     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1660     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1661                    getTargetMachine().getRelocationModel() != Reloc::Static;
1662     isARMFunc = !Subtarget->isThumb() || isStub;
1663     // ARM call to a local ARM function is predicable.
1664     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1665     // tBX takes a register source operand.
1666     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1667       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1668       ARMConstantPoolValue *CPV =
1669         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1670       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1671       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1672       Callee = DAG.getLoad(getPointerTy(), dl,
1673                            DAG.getEntryNode(), CPAddr,
1674                            MachinePointerInfo::getConstantPool(),
1675                            false, false, false, 0);
1676       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1677       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1678                            getPointerTy(), Callee, PICLabel);
1679     } else {
1680       // On ELF targets for PIC code, direct calls should go through the PLT
1681       unsigned OpFlags = 0;
1682       if (Subtarget->isTargetELF() &&
1683           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1684         OpFlags = ARMII::MO_PLT;
1685       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1686     }
1687   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1688     isDirect = true;
1689     bool isStub = Subtarget->isTargetDarwin() &&
1690                   getTargetMachine().getRelocationModel() != Reloc::Static;
1691     isARMFunc = !Subtarget->isThumb() || isStub;
1692     // tBX takes a register source operand.
1693     const char *Sym = S->getSymbol();
1694     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1695       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1696       ARMConstantPoolValue *CPV =
1697         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1698                                       ARMPCLabelIndex, 4);
1699       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1700       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1701       Callee = DAG.getLoad(getPointerTy(), dl,
1702                            DAG.getEntryNode(), CPAddr,
1703                            MachinePointerInfo::getConstantPool(),
1704                            false, false, false, 0);
1705       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1706       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1707                            getPointerTy(), Callee, PICLabel);
1708     } else {
1709       unsigned OpFlags = 0;
1710       // On ELF targets for PIC code, direct calls should go through the PLT
1711       if (Subtarget->isTargetELF() &&
1712                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1713         OpFlags = ARMII::MO_PLT;
1714       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1715     }
1716   }
1717
1718   // FIXME: handle tail calls differently.
1719   unsigned CallOpc;
1720   bool HasMinSizeAttr = MF.getFunction()->getAttributes().
1721     hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
1722   if (Subtarget->isThumb()) {
1723     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1724       CallOpc = ARMISD::CALL_NOLINK;
1725     else
1726       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1727   } else {
1728     if (!isDirect && !Subtarget->hasV5TOps())
1729       CallOpc = ARMISD::CALL_NOLINK;
1730     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1731                // Emit regular call when code size is the priority
1732                !HasMinSizeAttr)
1733       // "mov lr, pc; b _foo" to avoid confusing the RSP
1734       CallOpc = ARMISD::CALL_NOLINK;
1735     else
1736       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1737   }
1738
1739   std::vector<SDValue> Ops;
1740   Ops.push_back(Chain);
1741   Ops.push_back(Callee);
1742
1743   // Add argument registers to the end of the list so that they are known live
1744   // into the call.
1745   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1746     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1747                                   RegsToPass[i].second.getValueType()));
1748
1749   // Add a register mask operand representing the call-preserved registers.
1750   const uint32_t *Mask;
1751   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1752   const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1753   if (isThisReturn) {
1754     // For 'this' returns, use the R0-preserving mask if applicable
1755     Mask = ARI->getThisReturnPreservedMask(CallConv);
1756     if (!Mask) {
1757       // Set isThisReturn to false if the calling convention is not one that
1758       // allows 'returned' to be modeled in this way, so LowerCallResult does
1759       // not try to pass 'this' straight through 
1760       isThisReturn = false;
1761       Mask = ARI->getCallPreservedMask(CallConv);
1762     }
1763   } else
1764     Mask = ARI->getCallPreservedMask(CallConv);
1765
1766   assert(Mask && "Missing call preserved mask for calling convention");
1767   Ops.push_back(DAG.getRegisterMask(Mask));
1768
1769   if (InFlag.getNode())
1770     Ops.push_back(InFlag);
1771
1772   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1773   if (isTailCall)
1774     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1775
1776   // Returns a chain and a flag for retval copy to use.
1777   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1778   InFlag = Chain.getValue(1);
1779
1780   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1781                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1782   if (!Ins.empty())
1783     InFlag = Chain.getValue(1);
1784
1785   // Handle result values, copying them out of physregs into vregs that we
1786   // return.
1787   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1788                          InVals, isThisReturn,
1789                          isThisReturn ? OutVals[0] : SDValue());
1790 }
1791
1792 /// HandleByVal - Every parameter *after* a byval parameter is passed
1793 /// on the stack.  Remember the next parameter register to allocate,
1794 /// and then confiscate the rest of the parameter registers to insure
1795 /// this.
1796 void
1797 ARMTargetLowering::HandleByVal(
1798     CCState *State, unsigned &size, unsigned Align) const {
1799   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1800   assert((State->getCallOrPrologue() == Prologue ||
1801           State->getCallOrPrologue() == Call) &&
1802          "unhandled ParmContext");
1803
1804   // For in-prologue parameters handling, we also introduce stack offset
1805   // for byval registers: see CallingConvLower.cpp, CCState::HandleByVal.
1806   // This behaviour outsides AAPCS rules (5.5 Parameters Passing) of how
1807   // NSAA should be evaluted (NSAA means "next stacked argument address").
1808   // So: NextStackOffset = NSAAOffset + SizeOfByValParamsStoredInRegs.
1809   // Then: NSAAOffset = NextStackOffset - SizeOfByValParamsStoredInRegs.
1810   unsigned NSAAOffset = State->getNextStackOffset();
1811   if (State->getCallOrPrologue() != Call) {
1812     for (unsigned i = 0, e = State->getInRegsParamsCount(); i != e; ++i) {
1813       unsigned RB, RE;
1814       State->getInRegsParamInfo(i, RB, RE);
1815       assert(NSAAOffset >= (RE-RB)*4 &&
1816              "Stack offset for byval regs doesn't introduced anymore?");
1817       NSAAOffset -= (RE-RB)*4;
1818     }
1819   }
1820   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1821     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1822       unsigned AlignInRegs = Align / 4;
1823       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1824       for (unsigned i = 0; i < Waste; ++i)
1825         reg = State->AllocateReg(GPRArgRegs, 4);
1826     }
1827     if (reg != 0) {
1828       unsigned excess = 4 * (ARM::R4 - reg);
1829
1830       // Special case when NSAA != SP and parameter size greater than size of
1831       // all remained GPR regs. In that case we can't split parameter, we must
1832       // send it to stack. We also must set NCRN to R4, so waste all
1833       // remained registers.
1834       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1835         while (State->AllocateReg(GPRArgRegs, 4))
1836           ;
1837         return;
1838       }
1839
1840       // First register for byval parameter is the first register that wasn't
1841       // allocated before this method call, so it would be "reg".
1842       // If parameter is small enough to be saved in range [reg, r4), then
1843       // the end (first after last) register would be reg + param-size-in-regs,
1844       // else parameter would be splitted between registers and stack,
1845       // end register would be r4 in this case.
1846       unsigned ByValRegBegin = reg;
1847       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1848       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1849       // Note, first register is allocated in the beginning of function already,
1850       // allocate remained amount of registers we need.
1851       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1852         State->AllocateReg(GPRArgRegs, 4);
1853       // At a call site, a byval parameter that is split between
1854       // registers and memory needs its size truncated here.  In a
1855       // function prologue, such byval parameters are reassembled in
1856       // memory, and are not truncated.
1857       if (State->getCallOrPrologue() == Call) {
1858         // Make remained size equal to 0 in case, when
1859         // the whole structure may be stored into registers.
1860         if (size < excess)
1861           size = 0;
1862         else
1863           size -= excess;
1864       }
1865     }
1866   }
1867 }
1868
1869 /// MatchingStackOffset - Return true if the given stack call argument is
1870 /// already available in the same position (relatively) of the caller's
1871 /// incoming argument stack.
1872 static
1873 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1874                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1875                          const TargetInstrInfo *TII) {
1876   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1877   int FI = INT_MAX;
1878   if (Arg.getOpcode() == ISD::CopyFromReg) {
1879     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1880     if (!TargetRegisterInfo::isVirtualRegister(VR))
1881       return false;
1882     MachineInstr *Def = MRI->getVRegDef(VR);
1883     if (!Def)
1884       return false;
1885     if (!Flags.isByVal()) {
1886       if (!TII->isLoadFromStackSlot(Def, FI))
1887         return false;
1888     } else {
1889       return false;
1890     }
1891   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1892     if (Flags.isByVal())
1893       // ByVal argument is passed in as a pointer but it's now being
1894       // dereferenced. e.g.
1895       // define @foo(%struct.X* %A) {
1896       //   tail call @bar(%struct.X* byval %A)
1897       // }
1898       return false;
1899     SDValue Ptr = Ld->getBasePtr();
1900     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1901     if (!FINode)
1902       return false;
1903     FI = FINode->getIndex();
1904   } else
1905     return false;
1906
1907   assert(FI != INT_MAX);
1908   if (!MFI->isFixedObjectIndex(FI))
1909     return false;
1910   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1911 }
1912
1913 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1914 /// for tail call optimization. Targets which want to do tail call
1915 /// optimization should implement this function.
1916 bool
1917 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1918                                                      CallingConv::ID CalleeCC,
1919                                                      bool isVarArg,
1920                                                      bool isCalleeStructRet,
1921                                                      bool isCallerStructRet,
1922                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1923                                     const SmallVectorImpl<SDValue> &OutVals,
1924                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1925                                                      SelectionDAG& DAG) const {
1926   const Function *CallerF = DAG.getMachineFunction().getFunction();
1927   CallingConv::ID CallerCC = CallerF->getCallingConv();
1928   bool CCMatch = CallerCC == CalleeCC;
1929
1930   // Look for obvious safe cases to perform tail call optimization that do not
1931   // require ABI changes. This is what gcc calls sibcall.
1932
1933   // Do not sibcall optimize vararg calls unless the call site is not passing
1934   // any arguments.
1935   if (isVarArg && !Outs.empty())
1936     return false;
1937
1938   // Also avoid sibcall optimization if either caller or callee uses struct
1939   // return semantics.
1940   if (isCalleeStructRet || isCallerStructRet)
1941     return false;
1942
1943   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1944   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1945   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1946   // support in the assembler and linker to be used. This would need to be
1947   // fixed to fully support tail calls in Thumb1.
1948   //
1949   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1950   // LR.  This means if we need to reload LR, it takes an extra instructions,
1951   // which outweighs the value of the tail call; but here we don't know yet
1952   // whether LR is going to be used.  Probably the right approach is to
1953   // generate the tail call here and turn it back into CALL/RET in
1954   // emitEpilogue if LR is used.
1955
1956   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1957   // but we need to make sure there are enough registers; the only valid
1958   // registers are the 4 used for parameters.  We don't currently do this
1959   // case.
1960   if (Subtarget->isThumb1Only())
1961     return false;
1962
1963   // If the calling conventions do not match, then we'd better make sure the
1964   // results are returned in the same way as what the caller expects.
1965   if (!CCMatch) {
1966     SmallVector<CCValAssign, 16> RVLocs1;
1967     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1968                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1969     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1970
1971     SmallVector<CCValAssign, 16> RVLocs2;
1972     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1973                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1974     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1975
1976     if (RVLocs1.size() != RVLocs2.size())
1977       return false;
1978     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1979       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1980         return false;
1981       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1982         return false;
1983       if (RVLocs1[i].isRegLoc()) {
1984         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1985           return false;
1986       } else {
1987         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1988           return false;
1989       }
1990     }
1991   }
1992
1993   // If Caller's vararg or byval argument has been split between registers and
1994   // stack, do not perform tail call, since part of the argument is in caller's
1995   // local frame.
1996   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1997                                       getInfo<ARMFunctionInfo>();
1998   if (AFI_Caller->getArgRegsSaveSize())
1999     return false;
2000
2001   // If the callee takes no arguments then go on to check the results of the
2002   // call.
2003   if (!Outs.empty()) {
2004     // Check if stack adjustment is needed. For now, do not do this if any
2005     // argument is passed on the stack.
2006     SmallVector<CCValAssign, 16> ArgLocs;
2007     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2008                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
2009     CCInfo.AnalyzeCallOperands(Outs,
2010                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2011     if (CCInfo.getNextStackOffset()) {
2012       MachineFunction &MF = DAG.getMachineFunction();
2013
2014       // Check if the arguments are already laid out in the right way as
2015       // the caller's fixed stack objects.
2016       MachineFrameInfo *MFI = MF.getFrameInfo();
2017       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2018       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2019       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2020            i != e;
2021            ++i, ++realArgIdx) {
2022         CCValAssign &VA = ArgLocs[i];
2023         EVT RegVT = VA.getLocVT();
2024         SDValue Arg = OutVals[realArgIdx];
2025         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2026         if (VA.getLocInfo() == CCValAssign::Indirect)
2027           return false;
2028         if (VA.needsCustom()) {
2029           // f64 and vector types are split into multiple registers or
2030           // register/stack-slot combinations.  The types will not match
2031           // the registers; give up on memory f64 refs until we figure
2032           // out what to do about this.
2033           if (!VA.isRegLoc())
2034             return false;
2035           if (!ArgLocs[++i].isRegLoc())
2036             return false;
2037           if (RegVT == MVT::v2f64) {
2038             if (!ArgLocs[++i].isRegLoc())
2039               return false;
2040             if (!ArgLocs[++i].isRegLoc())
2041               return false;
2042           }
2043         } else if (!VA.isRegLoc()) {
2044           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2045                                    MFI, MRI, TII))
2046             return false;
2047         }
2048       }
2049     }
2050   }
2051
2052   return true;
2053 }
2054
2055 bool
2056 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2057                                   MachineFunction &MF, bool isVarArg,
2058                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2059                                   LLVMContext &Context) const {
2060   SmallVector<CCValAssign, 16> RVLocs;
2061   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2062   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2063                                                     isVarArg));
2064 }
2065
2066 SDValue
2067 ARMTargetLowering::LowerReturn(SDValue Chain,
2068                                CallingConv::ID CallConv, bool isVarArg,
2069                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2070                                const SmallVectorImpl<SDValue> &OutVals,
2071                                SDLoc dl, SelectionDAG &DAG) const {
2072
2073   // CCValAssign - represent the assignment of the return value to a location.
2074   SmallVector<CCValAssign, 16> RVLocs;
2075
2076   // CCState - Info about the registers and stack slots.
2077   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2078                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2079
2080   // Analyze outgoing return values.
2081   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2082                                                isVarArg));
2083
2084   SDValue Flag;
2085   SmallVector<SDValue, 4> RetOps;
2086   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2087
2088   // Copy the result values into the output registers.
2089   for (unsigned i = 0, realRVLocIdx = 0;
2090        i != RVLocs.size();
2091        ++i, ++realRVLocIdx) {
2092     CCValAssign &VA = RVLocs[i];
2093     assert(VA.isRegLoc() && "Can only return in registers!");
2094
2095     SDValue Arg = OutVals[realRVLocIdx];
2096
2097     switch (VA.getLocInfo()) {
2098     default: llvm_unreachable("Unknown loc info!");
2099     case CCValAssign::Full: break;
2100     case CCValAssign::BCvt:
2101       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2102       break;
2103     }
2104
2105     if (VA.needsCustom()) {
2106       if (VA.getLocVT() == MVT::v2f64) {
2107         // Extract the first half and return it in two registers.
2108         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2109                                    DAG.getConstant(0, MVT::i32));
2110         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2111                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2112
2113         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
2114         Flag = Chain.getValue(1);
2115         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2116         VA = RVLocs[++i]; // skip ahead to next loc
2117         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2118                                  HalfGPRs.getValue(1), Flag);
2119         Flag = Chain.getValue(1);
2120         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2121         VA = RVLocs[++i]; // skip ahead to next loc
2122
2123         // Extract the 2nd half and fall through to handle it as an f64 value.
2124         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2125                           DAG.getConstant(1, MVT::i32));
2126       }
2127       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2128       // available.
2129       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2130                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
2131       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
2132       Flag = Chain.getValue(1);
2133       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2134       VA = RVLocs[++i]; // skip ahead to next loc
2135       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
2136                                Flag);
2137     } else
2138       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2139
2140     // Guarantee that all emitted copies are
2141     // stuck together, avoiding something bad.
2142     Flag = Chain.getValue(1);
2143     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2144   }
2145
2146   // Update chain and glue.
2147   RetOps[0] = Chain;
2148   if (Flag.getNode())
2149     RetOps.push_back(Flag);
2150
2151   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
2152                      RetOps.data(), RetOps.size());
2153 }
2154
2155 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2156   if (N->getNumValues() != 1)
2157     return false;
2158   if (!N->hasNUsesOfValue(1, 0))
2159     return false;
2160
2161   SDValue TCChain = Chain;
2162   SDNode *Copy = *N->use_begin();
2163   if (Copy->getOpcode() == ISD::CopyToReg) {
2164     // If the copy has a glue operand, we conservatively assume it isn't safe to
2165     // perform a tail call.
2166     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2167       return false;
2168     TCChain = Copy->getOperand(0);
2169   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2170     SDNode *VMov = Copy;
2171     // f64 returned in a pair of GPRs.
2172     SmallPtrSet<SDNode*, 2> Copies;
2173     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2174          UI != UE; ++UI) {
2175       if (UI->getOpcode() != ISD::CopyToReg)
2176         return false;
2177       Copies.insert(*UI);
2178     }
2179     if (Copies.size() > 2)
2180       return false;
2181
2182     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2183          UI != UE; ++UI) {
2184       SDValue UseChain = UI->getOperand(0);
2185       if (Copies.count(UseChain.getNode()))
2186         // Second CopyToReg
2187         Copy = *UI;
2188       else
2189         // First CopyToReg
2190         TCChain = UseChain;
2191     }
2192   } else if (Copy->getOpcode() == ISD::BITCAST) {
2193     // f32 returned in a single GPR.
2194     if (!Copy->hasOneUse())
2195       return false;
2196     Copy = *Copy->use_begin();
2197     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2198       return false;
2199     TCChain = Copy->getOperand(0);
2200   } else {
2201     return false;
2202   }
2203
2204   bool HasRet = false;
2205   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2206        UI != UE; ++UI) {
2207     if (UI->getOpcode() != ARMISD::RET_FLAG)
2208       return false;
2209     HasRet = true;
2210   }
2211
2212   if (!HasRet)
2213     return false;
2214
2215   Chain = TCChain;
2216   return true;
2217 }
2218
2219 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2220   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2221     return false;
2222
2223   if (!CI->isTailCall())
2224     return false;
2225
2226   return !Subtarget->isThumb1Only();
2227 }
2228
2229 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2230 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2231 // one of the above mentioned nodes. It has to be wrapped because otherwise
2232 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2233 // be used to form addressing mode. These wrapped nodes will be selected
2234 // into MOVi.
2235 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2236   EVT PtrVT = Op.getValueType();
2237   // FIXME there is no actual debug info here
2238   SDLoc dl(Op);
2239   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2240   SDValue Res;
2241   if (CP->isMachineConstantPoolEntry())
2242     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2243                                     CP->getAlignment());
2244   else
2245     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2246                                     CP->getAlignment());
2247   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2248 }
2249
2250 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2251   return MachineJumpTableInfo::EK_Inline;
2252 }
2253
2254 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2255                                              SelectionDAG &DAG) const {
2256   MachineFunction &MF = DAG.getMachineFunction();
2257   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2258   unsigned ARMPCLabelIndex = 0;
2259   SDLoc DL(Op);
2260   EVT PtrVT = getPointerTy();
2261   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2262   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2263   SDValue CPAddr;
2264   if (RelocM == Reloc::Static) {
2265     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2266   } else {
2267     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2268     ARMPCLabelIndex = AFI->createPICLabelUId();
2269     ARMConstantPoolValue *CPV =
2270       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2271                                       ARMCP::CPBlockAddress, PCAdj);
2272     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2273   }
2274   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2275   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2276                                MachinePointerInfo::getConstantPool(),
2277                                false, false, false, 0);
2278   if (RelocM == Reloc::Static)
2279     return Result;
2280   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2281   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2282 }
2283
2284 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2285 SDValue
2286 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2287                                                  SelectionDAG &DAG) const {
2288   SDLoc dl(GA);
2289   EVT PtrVT = getPointerTy();
2290   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2291   MachineFunction &MF = DAG.getMachineFunction();
2292   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2293   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2294   ARMConstantPoolValue *CPV =
2295     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2296                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2297   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2298   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2299   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2300                          MachinePointerInfo::getConstantPool(),
2301                          false, false, false, 0);
2302   SDValue Chain = Argument.getValue(1);
2303
2304   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2305   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2306
2307   // call __tls_get_addr.
2308   ArgListTy Args;
2309   ArgListEntry Entry;
2310   Entry.Node = Argument;
2311   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2312   Args.push_back(Entry);
2313   // FIXME: is there useful debug info available here?
2314   TargetLowering::CallLoweringInfo CLI(Chain,
2315                 (Type *) Type::getInt32Ty(*DAG.getContext()),
2316                 false, false, false, false,
2317                 0, CallingConv::C, /*isTailCall=*/false,
2318                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2319                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2320   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2321   return CallResult.first;
2322 }
2323
2324 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2325 // "local exec" model.
2326 SDValue
2327 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2328                                         SelectionDAG &DAG,
2329                                         TLSModel::Model model) const {
2330   const GlobalValue *GV = GA->getGlobal();
2331   SDLoc dl(GA);
2332   SDValue Offset;
2333   SDValue Chain = DAG.getEntryNode();
2334   EVT PtrVT = getPointerTy();
2335   // Get the Thread Pointer
2336   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2337
2338   if (model == TLSModel::InitialExec) {
2339     MachineFunction &MF = DAG.getMachineFunction();
2340     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2341     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2342     // Initial exec model.
2343     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2344     ARMConstantPoolValue *CPV =
2345       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2346                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2347                                       true);
2348     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2349     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2350     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2351                          MachinePointerInfo::getConstantPool(),
2352                          false, false, false, 0);
2353     Chain = Offset.getValue(1);
2354
2355     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2356     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2357
2358     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2359                          MachinePointerInfo::getConstantPool(),
2360                          false, false, false, 0);
2361   } else {
2362     // local exec model
2363     assert(model == TLSModel::LocalExec);
2364     ARMConstantPoolValue *CPV =
2365       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2366     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2367     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2368     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2369                          MachinePointerInfo::getConstantPool(),
2370                          false, false, false, 0);
2371   }
2372
2373   // The address of the thread local variable is the add of the thread
2374   // pointer with the offset of the variable.
2375   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2376 }
2377
2378 SDValue
2379 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2380   // TODO: implement the "local dynamic" model
2381   assert(Subtarget->isTargetELF() &&
2382          "TLS not implemented for non-ELF targets");
2383   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2384
2385   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2386
2387   switch (model) {
2388     case TLSModel::GeneralDynamic:
2389     case TLSModel::LocalDynamic:
2390       return LowerToTLSGeneralDynamicModel(GA, DAG);
2391     case TLSModel::InitialExec:
2392     case TLSModel::LocalExec:
2393       return LowerToTLSExecModels(GA, DAG, model);
2394   }
2395   llvm_unreachable("bogus TLS model");
2396 }
2397
2398 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2399                                                  SelectionDAG &DAG) const {
2400   EVT PtrVT = getPointerTy();
2401   SDLoc dl(Op);
2402   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2403   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2404     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2405     ARMConstantPoolValue *CPV =
2406       ARMConstantPoolConstant::Create(GV,
2407                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2408     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2409     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2410     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2411                                  CPAddr,
2412                                  MachinePointerInfo::getConstantPool(),
2413                                  false, false, false, 0);
2414     SDValue Chain = Result.getValue(1);
2415     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2416     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2417     if (!UseGOTOFF)
2418       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2419                            MachinePointerInfo::getGOT(),
2420                            false, false, false, 0);
2421     return Result;
2422   }
2423
2424   // If we have T2 ops, we can materialize the address directly via movt/movw
2425   // pair. This is always cheaper.
2426   if (Subtarget->useMovt()) {
2427     ++NumMovwMovt;
2428     // FIXME: Once remat is capable of dealing with instructions with register
2429     // operands, expand this into two nodes.
2430     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2431                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2432   } else {
2433     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2434     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2435     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2436                        MachinePointerInfo::getConstantPool(),
2437                        false, false, false, 0);
2438   }
2439 }
2440
2441 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2442                                                     SelectionDAG &DAG) const {
2443   EVT PtrVT = getPointerTy();
2444   SDLoc dl(Op);
2445   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2446   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2447
2448   // FIXME: Enable this for static codegen when tool issues are fixed.  Also
2449   // update ARMFastISel::ARMMaterializeGV.
2450   if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2451     ++NumMovwMovt;
2452     // FIXME: Once remat is capable of dealing with instructions with register
2453     // operands, expand this into two nodes.
2454     if (RelocM == Reloc::Static)
2455       return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2456                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2457
2458     unsigned Wrapper = (RelocM == Reloc::PIC_)
2459       ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2460     SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2461                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2462     if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2463       Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2464                            MachinePointerInfo::getGOT(),
2465                            false, false, false, 0);
2466     return Result;
2467   }
2468
2469   unsigned ARMPCLabelIndex = 0;
2470   SDValue CPAddr;
2471   if (RelocM == Reloc::Static) {
2472     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2473   } else {
2474     ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2475     ARMPCLabelIndex = AFI->createPICLabelUId();
2476     unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2477     ARMConstantPoolValue *CPV =
2478       ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2479                                       PCAdj);
2480     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2481   }
2482   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2483
2484   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2485                                MachinePointerInfo::getConstantPool(),
2486                                false, false, false, 0);
2487   SDValue Chain = Result.getValue(1);
2488
2489   if (RelocM == Reloc::PIC_) {
2490     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2491     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2492   }
2493
2494   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2495     Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2496                          false, false, false, 0);
2497
2498   return Result;
2499 }
2500
2501 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2502                                                     SelectionDAG &DAG) const {
2503   assert(Subtarget->isTargetELF() &&
2504          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2505   MachineFunction &MF = DAG.getMachineFunction();
2506   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2507   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2508   EVT PtrVT = getPointerTy();
2509   SDLoc dl(Op);
2510   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2511   ARMConstantPoolValue *CPV =
2512     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2513                                   ARMPCLabelIndex, PCAdj);
2514   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2515   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2516   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2517                                MachinePointerInfo::getConstantPool(),
2518                                false, false, false, 0);
2519   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2520   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2521 }
2522
2523 SDValue
2524 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2525   SDLoc dl(Op);
2526   SDValue Val = DAG.getConstant(0, MVT::i32);
2527   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2528                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2529                      Op.getOperand(1), Val);
2530 }
2531
2532 SDValue
2533 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2534   SDLoc dl(Op);
2535   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2536                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2537 }
2538
2539 SDValue
2540 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2541                                           const ARMSubtarget *Subtarget) const {
2542   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2543   SDLoc dl(Op);
2544   switch (IntNo) {
2545   default: return SDValue();    // Don't custom lower most intrinsics.
2546   case Intrinsic::arm_thread_pointer: {
2547     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2548     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2549   }
2550   case Intrinsic::eh_sjlj_lsda: {
2551     MachineFunction &MF = DAG.getMachineFunction();
2552     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2553     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2554     EVT PtrVT = getPointerTy();
2555     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2556     SDValue CPAddr;
2557     unsigned PCAdj = (RelocM != Reloc::PIC_)
2558       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2559     ARMConstantPoolValue *CPV =
2560       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2561                                       ARMCP::CPLSDA, PCAdj);
2562     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2563     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2564     SDValue Result =
2565       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2566                   MachinePointerInfo::getConstantPool(),
2567                   false, false, false, 0);
2568
2569     if (RelocM == Reloc::PIC_) {
2570       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2571       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2572     }
2573     return Result;
2574   }
2575   case Intrinsic::arm_neon_vmulls:
2576   case Intrinsic::arm_neon_vmullu: {
2577     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2578       ? ARMISD::VMULLs : ARMISD::VMULLu;
2579     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2580                        Op.getOperand(1), Op.getOperand(2));
2581   }
2582   }
2583 }
2584
2585 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2586                                  const ARMSubtarget *Subtarget) {
2587   // FIXME: handle "fence singlethread" more efficiently.
2588   SDLoc dl(Op);
2589   if (!Subtarget->hasDataBarrier()) {
2590     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2591     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2592     // here.
2593     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2594            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2595     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2596                        DAG.getConstant(0, MVT::i32));
2597   }
2598
2599   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2600   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2601   unsigned Domain = ARM_MB::ISH;
2602   if (Subtarget->isMClass()) {
2603     // Only a full system barrier exists in the M-class architectures.
2604     Domain = ARM_MB::SY;
2605   } else if (Subtarget->isSwift() && Ord == Release) {
2606     // Swift happens to implement ISHST barriers in a way that's compatible with
2607     // Release semantics but weaker than ISH so we'd be fools not to use
2608     // it. Beware: other processors probably don't!
2609     Domain = ARM_MB::ISHST;
2610   }
2611
2612   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2613                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2614                      DAG.getConstant(Domain, MVT::i32));
2615 }
2616
2617 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2618                              const ARMSubtarget *Subtarget) {
2619   // ARM pre v5TE and Thumb1 does not have preload instructions.
2620   if (!(Subtarget->isThumb2() ||
2621         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2622     // Just preserve the chain.
2623     return Op.getOperand(0);
2624
2625   SDLoc dl(Op);
2626   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2627   if (!isRead &&
2628       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2629     // ARMv7 with MP extension has PLDW.
2630     return Op.getOperand(0);
2631
2632   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2633   if (Subtarget->isThumb()) {
2634     // Invert the bits.
2635     isRead = ~isRead & 1;
2636     isData = ~isData & 1;
2637   }
2638
2639   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2640                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2641                      DAG.getConstant(isData, MVT::i32));
2642 }
2643
2644 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2645   MachineFunction &MF = DAG.getMachineFunction();
2646   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2647
2648   // vastart just stores the address of the VarArgsFrameIndex slot into the
2649   // memory location argument.
2650   SDLoc dl(Op);
2651   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2652   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2653   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2654   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2655                       MachinePointerInfo(SV), false, false, 0);
2656 }
2657
2658 SDValue
2659 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2660                                         SDValue &Root, SelectionDAG &DAG,
2661                                         SDLoc dl) const {
2662   MachineFunction &MF = DAG.getMachineFunction();
2663   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2664
2665   const TargetRegisterClass *RC;
2666   if (AFI->isThumb1OnlyFunction())
2667     RC = &ARM::tGPRRegClass;
2668   else
2669     RC = &ARM::GPRRegClass;
2670
2671   // Transform the arguments stored in physical registers into virtual ones.
2672   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2673   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2674
2675   SDValue ArgValue2;
2676   if (NextVA.isMemLoc()) {
2677     MachineFrameInfo *MFI = MF.getFrameInfo();
2678     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2679
2680     // Create load node to retrieve arguments from the stack.
2681     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2682     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2683                             MachinePointerInfo::getFixedStack(FI),
2684                             false, false, false, 0);
2685   } else {
2686     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2687     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2688   }
2689
2690   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2691 }
2692
2693 void
2694 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2695                                   unsigned InRegsParamRecordIdx,
2696                                   unsigned ArgSize,
2697                                   unsigned &ArgRegsSize,
2698                                   unsigned &ArgRegsSaveSize)
2699   const {
2700   unsigned NumGPRs;
2701   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2702     unsigned RBegin, REnd;
2703     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2704     NumGPRs = REnd - RBegin;
2705   } else {
2706     unsigned int firstUnalloced;
2707     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2708                                                 sizeof(GPRArgRegs) /
2709                                                 sizeof(GPRArgRegs[0]));
2710     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2711   }
2712
2713   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2714   ArgRegsSize = NumGPRs * 4;
2715
2716   // If parameter is split between stack and GPRs...
2717   if (NumGPRs && Align == 8 &&
2718       (ArgRegsSize < ArgSize ||
2719         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2720     // Add padding for part of param recovered from GPRs, so
2721     // its last byte must be at address K*8 - 1.
2722     // We need to do it, since remained (stack) part of parameter has
2723     // stack alignment, and we need to "attach" "GPRs head" without gaps
2724     // to it:
2725     // Stack:
2726     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2727     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2728     //
2729     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2730     unsigned Padding =
2731         ((ArgRegsSize + AFI->getArgRegsSaveSize() + Align - 1) & ~(Align-1)) -
2732         (ArgRegsSize + AFI->getArgRegsSaveSize());
2733     ArgRegsSaveSize = ArgRegsSize + Padding;
2734   } else
2735     // We don't need to extend regs save size for byval parameters if they
2736     // are passed via GPRs only.
2737     ArgRegsSaveSize = ArgRegsSize;
2738 }
2739
2740 // The remaining GPRs hold either the beginning of variable-argument
2741 // data, or the beginning of an aggregate passed by value (usually
2742 // byval).  Either way, we allocate stack slots adjacent to the data
2743 // provided by our caller, and store the unallocated registers there.
2744 // If this is a variadic function, the va_list pointer will begin with
2745 // these values; otherwise, this reassembles a (byval) structure that
2746 // was split between registers and memory.
2747 // Return: The frame index registers were stored into.
2748 int
2749 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2750                                   SDLoc dl, SDValue &Chain,
2751                                   const Value *OrigArg,
2752                                   unsigned InRegsParamRecordIdx,
2753                                   unsigned OffsetFromOrigArg,
2754                                   unsigned ArgOffset,
2755                                   unsigned ArgSize,
2756                                   bool ForceMutable) const {
2757
2758   // Currently, two use-cases possible:
2759   // Case #1. Non var-args function, and we meet first byval parameter.
2760   //          Setup first unallocated register as first byval register;
2761   //          eat all remained registers
2762   //          (these two actions are performed by HandleByVal method).
2763   //          Then, here, we initialize stack frame with
2764   //          "store-reg" instructions.
2765   // Case #2. Var-args function, that doesn't contain byval parameters.
2766   //          The same: eat all remained unallocated registers,
2767   //          initialize stack frame.
2768
2769   MachineFunction &MF = DAG.getMachineFunction();
2770   MachineFrameInfo *MFI = MF.getFrameInfo();
2771   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2772   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2773   unsigned RBegin, REnd;
2774   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2775     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2776     firstRegToSaveIndex = RBegin - ARM::R0;
2777     lastRegToSaveIndex = REnd - ARM::R0;
2778   } else {
2779     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2780       (GPRArgRegs, array_lengthof(GPRArgRegs));
2781     lastRegToSaveIndex = 4;
2782   }
2783
2784   unsigned ArgRegsSize, ArgRegsSaveSize;
2785   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2786                  ArgRegsSize, ArgRegsSaveSize);
2787
2788   // Store any by-val regs to their spots on the stack so that they may be
2789   // loaded by deferencing the result of formal parameter pointer or va_next.
2790   // Note: once stack area for byval/varargs registers
2791   // was initialized, it can't be initialized again.
2792   if (ArgRegsSaveSize) {
2793
2794     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2795
2796     if (Padding) {
2797       assert(AFI->getStoredByValParamsPadding() == 0 &&
2798              "The only parameter may be padded.");
2799       AFI->setStoredByValParamsPadding(Padding);
2800     }
2801
2802     int FrameIndex = MFI->CreateFixedObject(
2803                       ArgRegsSaveSize,
2804                       Padding + ArgOffset,
2805                       false);
2806     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2807
2808     SmallVector<SDValue, 4> MemOps;
2809     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2810          ++firstRegToSaveIndex, ++i) {
2811       const TargetRegisterClass *RC;
2812       if (AFI->isThumb1OnlyFunction())
2813         RC = &ARM::tGPRRegClass;
2814       else
2815         RC = &ARM::GPRRegClass;
2816
2817       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2818       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2819       SDValue Store =
2820         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2821                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2822                      false, false, 0);
2823       MemOps.push_back(Store);
2824       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2825                         DAG.getConstant(4, getPointerTy()));
2826     }
2827
2828     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2829
2830     if (!MemOps.empty())
2831       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2832                           &MemOps[0], MemOps.size());
2833     return FrameIndex;
2834   } else
2835     // This will point to the next argument passed via stack.
2836     return MFI->CreateFixedObject(
2837         4, AFI->getStoredByValParamsPadding() + ArgOffset, !ForceMutable);
2838 }
2839
2840 // Setup stack frame, the va_list pointer will start from.
2841 void
2842 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2843                                         SDLoc dl, SDValue &Chain,
2844                                         unsigned ArgOffset,
2845                                         bool ForceMutable) const {
2846   MachineFunction &MF = DAG.getMachineFunction();
2847   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2848
2849   // Try to store any remaining integer argument regs
2850   // to their spots on the stack so that they may be loaded by deferencing
2851   // the result of va_next.
2852   // If there is no regs to be stored, just point address after last
2853   // argument passed via stack.
2854   int FrameIndex =
2855     StoreByValRegs(CCInfo, DAG, dl, Chain, 0, CCInfo.getInRegsParamsCount(),
2856                    0, ArgOffset, 0, ForceMutable);
2857
2858   AFI->setVarArgsFrameIndex(FrameIndex);
2859 }
2860
2861 SDValue
2862 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2863                                         CallingConv::ID CallConv, bool isVarArg,
2864                                         const SmallVectorImpl<ISD::InputArg>
2865                                           &Ins,
2866                                         SDLoc dl, SelectionDAG &DAG,
2867                                         SmallVectorImpl<SDValue> &InVals)
2868                                           const {
2869   MachineFunction &MF = DAG.getMachineFunction();
2870   MachineFrameInfo *MFI = MF.getFrameInfo();
2871
2872   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2873
2874   // Assign locations to all of the incoming arguments.
2875   SmallVector<CCValAssign, 16> ArgLocs;
2876   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2877                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2878   CCInfo.AnalyzeFormalArguments(Ins,
2879                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2880                                                   isVarArg));
2881
2882   SmallVector<SDValue, 16> ArgValues;
2883   int lastInsIndex = -1;
2884   SDValue ArgValue;
2885   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2886   unsigned CurArgIdx = 0;
2887
2888   // Initially ArgRegsSaveSize is zero.
2889   // Then we increase this value each time we meet byval parameter.
2890   // We also increase this value in case of varargs function.
2891   AFI->setArgRegsSaveSize(0);
2892
2893   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2894     CCValAssign &VA = ArgLocs[i];
2895     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2896     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2897     // Arguments stored in registers.
2898     if (VA.isRegLoc()) {
2899       EVT RegVT = VA.getLocVT();
2900
2901       if (VA.needsCustom()) {
2902         // f64 and vector types are split up into multiple registers or
2903         // combinations of registers and stack slots.
2904         if (VA.getLocVT() == MVT::v2f64) {
2905           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2906                                                    Chain, DAG, dl);
2907           VA = ArgLocs[++i]; // skip ahead to next loc
2908           SDValue ArgValue2;
2909           if (VA.isMemLoc()) {
2910             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2911             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2912             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2913                                     MachinePointerInfo::getFixedStack(FI),
2914                                     false, false, false, 0);
2915           } else {
2916             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2917                                              Chain, DAG, dl);
2918           }
2919           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2920           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2921                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2922           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2923                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2924         } else
2925           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2926
2927       } else {
2928         const TargetRegisterClass *RC;
2929
2930         if (RegVT == MVT::f32)
2931           RC = &ARM::SPRRegClass;
2932         else if (RegVT == MVT::f64)
2933           RC = &ARM::DPRRegClass;
2934         else if (RegVT == MVT::v2f64)
2935           RC = &ARM::QPRRegClass;
2936         else if (RegVT == MVT::i32)
2937           RC = AFI->isThumb1OnlyFunction() ?
2938             (const TargetRegisterClass*)&ARM::tGPRRegClass :
2939             (const TargetRegisterClass*)&ARM::GPRRegClass;
2940         else
2941           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2942
2943         // Transform the arguments in physical registers into virtual ones.
2944         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2945         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2946       }
2947
2948       // If this is an 8 or 16-bit value, it is really passed promoted
2949       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2950       // truncate to the right size.
2951       switch (VA.getLocInfo()) {
2952       default: llvm_unreachable("Unknown loc info!");
2953       case CCValAssign::Full: break;
2954       case CCValAssign::BCvt:
2955         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2956         break;
2957       case CCValAssign::SExt:
2958         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2959                                DAG.getValueType(VA.getValVT()));
2960         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2961         break;
2962       case CCValAssign::ZExt:
2963         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2964                                DAG.getValueType(VA.getValVT()));
2965         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2966         break;
2967       }
2968
2969       InVals.push_back(ArgValue);
2970
2971     } else { // VA.isRegLoc()
2972
2973       // sanity check
2974       assert(VA.isMemLoc());
2975       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2976
2977       int index = ArgLocs[i].getValNo();
2978
2979       // Some Ins[] entries become multiple ArgLoc[] entries.
2980       // Process them only once.
2981       if (index != lastInsIndex)
2982         {
2983           ISD::ArgFlagsTy Flags = Ins[index].Flags;
2984           // FIXME: For now, all byval parameter objects are marked mutable.
2985           // This can be changed with more analysis.
2986           // In case of tail call optimization mark all arguments mutable.
2987           // Since they could be overwritten by lowering of arguments in case of
2988           // a tail call.
2989           if (Flags.isByVal()) {
2990             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
2991             int FrameIndex = StoreByValRegs(
2992                 CCInfo, DAG, dl, Chain, CurOrigArg,
2993                 CurByValIndex,
2994                 Ins[VA.getValNo()].PartOffset,
2995                 VA.getLocMemOffset(),
2996                 Flags.getByValSize(),
2997                 true /*force mutable frames*/);
2998             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
2999             CCInfo.nextInRegsParam();
3000           } else {
3001             unsigned FIOffset = VA.getLocMemOffset() +
3002                                 AFI->getStoredByValParamsPadding();
3003             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3004                                             FIOffset, true);
3005
3006             // Create load nodes to retrieve arguments from the stack.
3007             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3008             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3009                                          MachinePointerInfo::getFixedStack(FI),
3010                                          false, false, false, 0));
3011           }
3012           lastInsIndex = index;
3013         }
3014     }
3015   }
3016
3017   // varargs
3018   if (isVarArg)
3019     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3020                          CCInfo.getNextStackOffset());
3021
3022   return Chain;
3023 }
3024
3025 /// isFloatingPointZero - Return true if this is +0.0.
3026 static bool isFloatingPointZero(SDValue Op) {
3027   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3028     return CFP->getValueAPF().isPosZero();
3029   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3030     // Maybe this has already been legalized into the constant pool?
3031     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3032       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3033       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3034         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3035           return CFP->getValueAPF().isPosZero();
3036     }
3037   }
3038   return false;
3039 }
3040
3041 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3042 /// the given operands.
3043 SDValue
3044 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3045                              SDValue &ARMcc, SelectionDAG &DAG,
3046                              SDLoc dl) const {
3047   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3048     unsigned C = RHSC->getZExtValue();
3049     if (!isLegalICmpImmediate(C)) {
3050       // Constant does not fit, try adjusting it by one?
3051       switch (CC) {
3052       default: break;
3053       case ISD::SETLT:
3054       case ISD::SETGE:
3055         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3056           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3057           RHS = DAG.getConstant(C-1, MVT::i32);
3058         }
3059         break;
3060       case ISD::SETULT:
3061       case ISD::SETUGE:
3062         if (C != 0 && isLegalICmpImmediate(C-1)) {
3063           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3064           RHS = DAG.getConstant(C-1, MVT::i32);
3065         }
3066         break;
3067       case ISD::SETLE:
3068       case ISD::SETGT:
3069         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3070           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3071           RHS = DAG.getConstant(C+1, MVT::i32);
3072         }
3073         break;
3074       case ISD::SETULE:
3075       case ISD::SETUGT:
3076         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3077           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3078           RHS = DAG.getConstant(C+1, MVT::i32);
3079         }
3080         break;
3081       }
3082     }
3083   }
3084
3085   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3086   ARMISD::NodeType CompareType;
3087   switch (CondCode) {
3088   default:
3089     CompareType = ARMISD::CMP;
3090     break;
3091   case ARMCC::EQ:
3092   case ARMCC::NE:
3093     // Uses only Z Flag
3094     CompareType = ARMISD::CMPZ;
3095     break;
3096   }
3097   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3098   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3099 }
3100
3101 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3102 SDValue
3103 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3104                              SDLoc dl) const {
3105   SDValue Cmp;
3106   if (!isFloatingPointZero(RHS))
3107     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3108   else
3109     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3110   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3111 }
3112
3113 /// duplicateCmp - Glue values can have only one use, so this function
3114 /// duplicates a comparison node.
3115 SDValue
3116 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3117   unsigned Opc = Cmp.getOpcode();
3118   SDLoc DL(Cmp);
3119   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3120     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3121
3122   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3123   Cmp = Cmp.getOperand(0);
3124   Opc = Cmp.getOpcode();
3125   if (Opc == ARMISD::CMPFP)
3126     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3127   else {
3128     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3129     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3130   }
3131   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3132 }
3133
3134 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3135   SDValue Cond = Op.getOperand(0);
3136   SDValue SelectTrue = Op.getOperand(1);
3137   SDValue SelectFalse = Op.getOperand(2);
3138   SDLoc dl(Op);
3139
3140   // Convert:
3141   //
3142   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3143   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3144   //
3145   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3146     const ConstantSDNode *CMOVTrue =
3147       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3148     const ConstantSDNode *CMOVFalse =
3149       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3150
3151     if (CMOVTrue && CMOVFalse) {
3152       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3153       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3154
3155       SDValue True;
3156       SDValue False;
3157       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3158         True = SelectTrue;
3159         False = SelectFalse;
3160       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3161         True = SelectFalse;
3162         False = SelectTrue;
3163       }
3164
3165       if (True.getNode() && False.getNode()) {
3166         EVT VT = Op.getValueType();
3167         SDValue ARMcc = Cond.getOperand(2);
3168         SDValue CCR = Cond.getOperand(3);
3169         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3170         assert(True.getValueType() == VT);
3171         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3172       }
3173     }
3174   }
3175
3176   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3177   // undefined bits before doing a full-word comparison with zero.
3178   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3179                      DAG.getConstant(1, Cond.getValueType()));
3180
3181   return DAG.getSelectCC(dl, Cond,
3182                          DAG.getConstant(0, Cond.getValueType()),
3183                          SelectTrue, SelectFalse, ISD::SETNE);
3184 }
3185
3186 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3187   if (CC == ISD::SETNE)
3188     return ISD::SETEQ;
3189   return ISD::getSetCCSwappedOperands(CC);
3190 }
3191
3192 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3193                                  bool &swpCmpOps, bool &swpVselOps) {
3194   // Start by selecting the GE condition code for opcodes that return true for
3195   // 'equality'
3196   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3197       CC == ISD::SETULE)
3198     CondCode = ARMCC::GE;
3199
3200   // and GT for opcodes that return false for 'equality'.
3201   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3202            CC == ISD::SETULT)
3203     CondCode = ARMCC::GT;
3204
3205   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3206   // to swap the compare operands.
3207   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3208       CC == ISD::SETULT)
3209     swpCmpOps = true;
3210
3211   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3212   // If we have an unordered opcode, we need to swap the operands to the VSEL
3213   // instruction (effectively negating the condition).
3214   //
3215   // This also has the effect of swapping which one of 'less' or 'greater'
3216   // returns true, so we also swap the compare operands. It also switches
3217   // whether we return true for 'equality', so we compensate by picking the
3218   // opposite condition code to our original choice.
3219   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3220       CC == ISD::SETUGT) {
3221     swpCmpOps = !swpCmpOps;
3222     swpVselOps = !swpVselOps;
3223     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3224   }
3225
3226   // 'ordered' is 'anything but unordered', so use the VS condition code and
3227   // swap the VSEL operands.
3228   if (CC == ISD::SETO) {
3229     CondCode = ARMCC::VS;
3230     swpVselOps = true;
3231   }
3232
3233   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3234   // code and swap the VSEL operands.
3235   if (CC == ISD::SETUNE) {
3236     CondCode = ARMCC::EQ;
3237     swpVselOps = true;
3238   }
3239 }
3240
3241 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3242   EVT VT = Op.getValueType();
3243   SDValue LHS = Op.getOperand(0);
3244   SDValue RHS = Op.getOperand(1);
3245   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3246   SDValue TrueVal = Op.getOperand(2);
3247   SDValue FalseVal = Op.getOperand(3);
3248   SDLoc dl(Op);
3249
3250   if (LHS.getValueType() == MVT::i32) {
3251     // Try to generate VSEL on ARMv8.
3252     // The VSEL instruction can't use all the usual ARM condition
3253     // codes: it only has two bits to select the condition code, so it's
3254     // constrained to use only GE, GT, VS and EQ.
3255     //
3256     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3257     // swap the operands of the previous compare instruction (effectively
3258     // inverting the compare condition, swapping 'less' and 'greater') and
3259     // sometimes need to swap the operands to the VSEL (which inverts the
3260     // condition in the sense of firing whenever the previous condition didn't)
3261     if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3262                                       TrueVal.getValueType() == MVT::f64)) {
3263       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3264       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3265           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3266         CC = getInverseCCForVSEL(CC);
3267         std::swap(TrueVal, FalseVal);
3268       }
3269     }
3270
3271     SDValue ARMcc;
3272     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3273     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3274     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3275                        Cmp);
3276   }
3277
3278   ARMCC::CondCodes CondCode, CondCode2;
3279   FPCCToARMCC(CC, CondCode, CondCode2);
3280
3281   // Try to generate VSEL on ARMv8.
3282   if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3283                                     TrueVal.getValueType() == MVT::f64)) {
3284     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3285     // same operands, as follows:
3286     //   c = fcmp [ogt, olt, ugt, ult] a, b
3287     //   select c, a, b
3288     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3289     // handled differently than the original code sequence.
3290     if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3291         RHS == FalseVal) {
3292       if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3293         return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3294       if (CC == ISD::SETOLT || CC == ISD::SETULT)
3295         return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3296     }
3297
3298     bool swpCmpOps = false;
3299     bool swpVselOps = false;
3300     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3301
3302     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3303         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3304       if (swpCmpOps)
3305         std::swap(LHS, RHS);
3306       if (swpVselOps)
3307         std::swap(TrueVal, FalseVal);
3308     }
3309   }
3310
3311   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3312   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3313   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3314   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3315                                ARMcc, CCR, Cmp);
3316   if (CondCode2 != ARMCC::AL) {
3317     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3318     // FIXME: Needs another CMP because flag can have but one use.
3319     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3320     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3321                          Result, TrueVal, ARMcc2, CCR, Cmp2);
3322   }
3323   return Result;
3324 }
3325
3326 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3327 /// to morph to an integer compare sequence.
3328 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3329                            const ARMSubtarget *Subtarget) {
3330   SDNode *N = Op.getNode();
3331   if (!N->hasOneUse())
3332     // Otherwise it requires moving the value from fp to integer registers.
3333     return false;
3334   if (!N->getNumValues())
3335     return false;
3336   EVT VT = Op.getValueType();
3337   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3338     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3339     // vmrs are very slow, e.g. cortex-a8.
3340     return false;
3341
3342   if (isFloatingPointZero(Op)) {
3343     SeenZero = true;
3344     return true;
3345   }
3346   return ISD::isNormalLoad(N);
3347 }
3348
3349 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3350   if (isFloatingPointZero(Op))
3351     return DAG.getConstant(0, MVT::i32);
3352
3353   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3354     return DAG.getLoad(MVT::i32, SDLoc(Op),
3355                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3356                        Ld->isVolatile(), Ld->isNonTemporal(),
3357                        Ld->isInvariant(), Ld->getAlignment());
3358
3359   llvm_unreachable("Unknown VFP cmp argument!");
3360 }
3361
3362 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3363                            SDValue &RetVal1, SDValue &RetVal2) {
3364   if (isFloatingPointZero(Op)) {
3365     RetVal1 = DAG.getConstant(0, MVT::i32);
3366     RetVal2 = DAG.getConstant(0, MVT::i32);
3367     return;
3368   }
3369
3370   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3371     SDValue Ptr = Ld->getBasePtr();
3372     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3373                           Ld->getChain(), Ptr,
3374                           Ld->getPointerInfo(),
3375                           Ld->isVolatile(), Ld->isNonTemporal(),
3376                           Ld->isInvariant(), Ld->getAlignment());
3377
3378     EVT PtrType = Ptr.getValueType();
3379     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3380     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3381                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3382     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3383                           Ld->getChain(), NewPtr,
3384                           Ld->getPointerInfo().getWithOffset(4),
3385                           Ld->isVolatile(), Ld->isNonTemporal(),
3386                           Ld->isInvariant(), NewAlign);
3387     return;
3388   }
3389
3390   llvm_unreachable("Unknown VFP cmp argument!");
3391 }
3392
3393 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3394 /// f32 and even f64 comparisons to integer ones.
3395 SDValue
3396 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3397   SDValue Chain = Op.getOperand(0);
3398   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3399   SDValue LHS = Op.getOperand(2);
3400   SDValue RHS = Op.getOperand(3);
3401   SDValue Dest = Op.getOperand(4);
3402   SDLoc dl(Op);
3403
3404   bool LHSSeenZero = false;
3405   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3406   bool RHSSeenZero = false;
3407   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3408   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3409     // If unsafe fp math optimization is enabled and there are no other uses of
3410     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3411     // to an integer comparison.
3412     if (CC == ISD::SETOEQ)
3413       CC = ISD::SETEQ;
3414     else if (CC == ISD::SETUNE)
3415       CC = ISD::SETNE;
3416
3417     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3418     SDValue ARMcc;
3419     if (LHS.getValueType() == MVT::f32) {
3420       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3421                         bitcastf32Toi32(LHS, DAG), Mask);
3422       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3423                         bitcastf32Toi32(RHS, DAG), Mask);
3424       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3425       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3426       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3427                          Chain, Dest, ARMcc, CCR, Cmp);
3428     }
3429
3430     SDValue LHS1, LHS2;
3431     SDValue RHS1, RHS2;
3432     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3433     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3434     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3435     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3436     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3437     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3438     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3439     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3440     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3441   }
3442
3443   return SDValue();
3444 }
3445
3446 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3447   SDValue Chain = Op.getOperand(0);
3448   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3449   SDValue LHS = Op.getOperand(2);
3450   SDValue RHS = Op.getOperand(3);
3451   SDValue Dest = Op.getOperand(4);
3452   SDLoc dl(Op);
3453
3454   if (LHS.getValueType() == MVT::i32) {
3455     SDValue ARMcc;
3456     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3457     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3458     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3459                        Chain, Dest, ARMcc, CCR, Cmp);
3460   }
3461
3462   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3463
3464   if (getTargetMachine().Options.UnsafeFPMath &&
3465       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3466        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3467     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3468     if (Result.getNode())
3469       return Result;
3470   }
3471
3472   ARMCC::CondCodes CondCode, CondCode2;
3473   FPCCToARMCC(CC, CondCode, CondCode2);
3474
3475   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3476   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3477   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3478   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3479   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3480   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3481   if (CondCode2 != ARMCC::AL) {
3482     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3483     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3484     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3485   }
3486   return Res;
3487 }
3488
3489 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3490   SDValue Chain = Op.getOperand(0);
3491   SDValue Table = Op.getOperand(1);
3492   SDValue Index = Op.getOperand(2);
3493   SDLoc dl(Op);
3494
3495   EVT PTy = getPointerTy();
3496   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3497   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3498   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3499   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3500   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3501   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3502   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3503   if (Subtarget->isThumb2()) {
3504     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3505     // which does another jump to the destination. This also makes it easier
3506     // to translate it to TBB / TBH later.
3507     // FIXME: This might not work if the function is extremely large.
3508     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3509                        Addr, Op.getOperand(2), JTI, UId);
3510   }
3511   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3512     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3513                        MachinePointerInfo::getJumpTable(),
3514                        false, false, false, 0);
3515     Chain = Addr.getValue(1);
3516     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3517     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3518   } else {
3519     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3520                        MachinePointerInfo::getJumpTable(),
3521                        false, false, false, 0);
3522     Chain = Addr.getValue(1);
3523     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3524   }
3525 }
3526
3527 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3528   EVT VT = Op.getValueType();
3529   SDLoc dl(Op);
3530
3531   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3532     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3533       return Op;
3534     return DAG.UnrollVectorOp(Op.getNode());
3535   }
3536
3537   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3538          "Invalid type for custom lowering!");
3539   if (VT != MVT::v4i16)
3540     return DAG.UnrollVectorOp(Op.getNode());
3541
3542   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3543   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3544 }
3545
3546 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3547   EVT VT = Op.getValueType();
3548   if (VT.isVector())
3549     return LowerVectorFP_TO_INT(Op, DAG);
3550
3551   SDLoc dl(Op);
3552   unsigned Opc;
3553
3554   switch (Op.getOpcode()) {
3555   default: llvm_unreachable("Invalid opcode!");
3556   case ISD::FP_TO_SINT:
3557     Opc = ARMISD::FTOSI;
3558     break;
3559   case ISD::FP_TO_UINT:
3560     Opc = ARMISD::FTOUI;
3561     break;
3562   }
3563   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3564   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3565 }
3566
3567 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3568   EVT VT = Op.getValueType();
3569   SDLoc dl(Op);
3570
3571   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3572     if (VT.getVectorElementType() == MVT::f32)
3573       return Op;
3574     return DAG.UnrollVectorOp(Op.getNode());
3575   }
3576
3577   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3578          "Invalid type for custom lowering!");
3579   if (VT != MVT::v4f32)
3580     return DAG.UnrollVectorOp(Op.getNode());
3581
3582   unsigned CastOpc;
3583   unsigned Opc;
3584   switch (Op.getOpcode()) {
3585   default: llvm_unreachable("Invalid opcode!");
3586   case ISD::SINT_TO_FP:
3587     CastOpc = ISD::SIGN_EXTEND;
3588     Opc = ISD::SINT_TO_FP;
3589     break;
3590   case ISD::UINT_TO_FP:
3591     CastOpc = ISD::ZERO_EXTEND;
3592     Opc = ISD::UINT_TO_FP;
3593     break;
3594   }
3595
3596   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3597   return DAG.getNode(Opc, dl, VT, Op);
3598 }
3599
3600 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3601   EVT VT = Op.getValueType();
3602   if (VT.isVector())
3603     return LowerVectorINT_TO_FP(Op, DAG);
3604
3605   SDLoc dl(Op);
3606   unsigned Opc;
3607
3608   switch (Op.getOpcode()) {
3609   default: llvm_unreachable("Invalid opcode!");
3610   case ISD::SINT_TO_FP:
3611     Opc = ARMISD::SITOF;
3612     break;
3613   case ISD::UINT_TO_FP:
3614     Opc = ARMISD::UITOF;
3615     break;
3616   }
3617
3618   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3619   return DAG.getNode(Opc, dl, VT, Op);
3620 }
3621
3622 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3623   // Implement fcopysign with a fabs and a conditional fneg.
3624   SDValue Tmp0 = Op.getOperand(0);
3625   SDValue Tmp1 = Op.getOperand(1);
3626   SDLoc dl(Op);
3627   EVT VT = Op.getValueType();
3628   EVT SrcVT = Tmp1.getValueType();
3629   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3630     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3631   bool UseNEON = !InGPR && Subtarget->hasNEON();
3632
3633   if (UseNEON) {
3634     // Use VBSL to copy the sign bit.
3635     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3636     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3637                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3638     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3639     if (VT == MVT::f64)
3640       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3641                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3642                          DAG.getConstant(32, MVT::i32));
3643     else /*if (VT == MVT::f32)*/
3644       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3645     if (SrcVT == MVT::f32) {
3646       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3647       if (VT == MVT::f64)
3648         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3649                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3650                            DAG.getConstant(32, MVT::i32));
3651     } else if (VT == MVT::f32)
3652       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3653                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3654                          DAG.getConstant(32, MVT::i32));
3655     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3656     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3657
3658     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3659                                             MVT::i32);
3660     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3661     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3662                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3663
3664     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3665                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3666                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3667     if (VT == MVT::f32) {
3668       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3669       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3670                         DAG.getConstant(0, MVT::i32));
3671     } else {
3672       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3673     }
3674
3675     return Res;
3676   }
3677
3678   // Bitcast operand 1 to i32.
3679   if (SrcVT == MVT::f64)
3680     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3681                        &Tmp1, 1).getValue(1);
3682   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3683
3684   // Or in the signbit with integer operations.
3685   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3686   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3687   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3688   if (VT == MVT::f32) {
3689     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3690                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3691     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3692                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3693   }
3694
3695   // f64: Or the high part with signbit and then combine two parts.
3696   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3697                      &Tmp0, 1);
3698   SDValue Lo = Tmp0.getValue(0);
3699   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3700   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3701   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3702 }
3703
3704 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3705   MachineFunction &MF = DAG.getMachineFunction();
3706   MachineFrameInfo *MFI = MF.getFrameInfo();
3707   MFI->setReturnAddressIsTaken(true);
3708
3709   EVT VT = Op.getValueType();
3710   SDLoc dl(Op);
3711   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3712   if (Depth) {
3713     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3714     SDValue Offset = DAG.getConstant(4, MVT::i32);
3715     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3716                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3717                        MachinePointerInfo(), false, false, false, 0);
3718   }
3719
3720   // Return LR, which contains the return address. Mark it an implicit live-in.
3721   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3722   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3723 }
3724
3725 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3726   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3727   MFI->setFrameAddressIsTaken(true);
3728
3729   EVT VT = Op.getValueType();
3730   SDLoc dl(Op);  // FIXME probably not meaningful
3731   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3732   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3733     ? ARM::R7 : ARM::R11;
3734   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3735   while (Depth--)
3736     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3737                             MachinePointerInfo(),
3738                             false, false, false, 0);
3739   return FrameAddr;
3740 }
3741
3742 /// Custom Expand long vector extensions, where size(DestVec) > 2*size(SrcVec),
3743 /// and size(DestVec) > 128-bits.
3744 /// This is achieved by doing the one extension from the SrcVec, splitting the
3745 /// result, extending these parts, and then concatenating these into the
3746 /// destination.
3747 static SDValue ExpandVectorExtension(SDNode *N, SelectionDAG &DAG) {
3748   SDValue Op = N->getOperand(0);
3749   EVT SrcVT = Op.getValueType();
3750   EVT DestVT = N->getValueType(0);
3751
3752   assert(DestVT.getSizeInBits() > 128 &&
3753          "Custom sext/zext expansion needs >128-bit vector.");
3754   // If this is a normal length extension, use the default expansion.
3755   if (SrcVT.getSizeInBits()*4 != DestVT.getSizeInBits() &&
3756       SrcVT.getSizeInBits()*8 != DestVT.getSizeInBits())
3757     return SDValue();
3758
3759   SDLoc dl(N);
3760   unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
3761   unsigned DestEltSize = DestVT.getVectorElementType().getSizeInBits();
3762   unsigned NumElts = SrcVT.getVectorNumElements();
3763   LLVMContext &Ctx = *DAG.getContext();
3764   SDValue Mid, SplitLo, SplitHi, ExtLo, ExtHi;
3765
3766   EVT MidVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3767                                NumElts);
3768   EVT SplitVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3769                                  NumElts/2);
3770   EVT ExtVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, DestEltSize),
3771                                NumElts/2);
3772
3773   Mid = DAG.getNode(N->getOpcode(), dl, MidVT, Op);
3774   SplitLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3775                         DAG.getIntPtrConstant(0));
3776   SplitHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3777                         DAG.getIntPtrConstant(NumElts/2));
3778   ExtLo = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitLo);
3779   ExtHi = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitHi);
3780   return DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, ExtLo, ExtHi);
3781 }
3782
3783 /// ExpandBITCAST - If the target supports VFP, this function is called to
3784 /// expand a bit convert where either the source or destination type is i64 to
3785 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3786 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3787 /// vectors), since the legalizer won't know what to do with that.
3788 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3789   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3790   SDLoc dl(N);
3791   SDValue Op = N->getOperand(0);
3792
3793   // This function is only supposed to be called for i64 types, either as the
3794   // source or destination of the bit convert.
3795   EVT SrcVT = Op.getValueType();
3796   EVT DstVT = N->getValueType(0);
3797   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3798          "ExpandBITCAST called for non-i64 type");
3799
3800   // Turn i64->f64 into VMOVDRR.
3801   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3802     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3803                              DAG.getConstant(0, MVT::i32));
3804     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3805                              DAG.getConstant(1, MVT::i32));
3806     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3807                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3808   }
3809
3810   // Turn f64->i64 into VMOVRRD.
3811   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3812     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3813                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3814     // Merge the pieces into a single i64 value.
3815     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3816   }
3817
3818   return SDValue();
3819 }
3820
3821 /// getZeroVector - Returns a vector of specified type with all zero elements.
3822 /// Zero vectors are used to represent vector negation and in those cases
3823 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3824 /// not support i64 elements, so sometimes the zero vectors will need to be
3825 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3826 /// zero vector.
3827 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3828   assert(VT.isVector() && "Expected a vector type");
3829   // The canonical modified immediate encoding of a zero vector is....0!
3830   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3831   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3832   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3833   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3834 }
3835
3836 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3837 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3838 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3839                                                 SelectionDAG &DAG) const {
3840   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3841   EVT VT = Op.getValueType();
3842   unsigned VTBits = VT.getSizeInBits();
3843   SDLoc dl(Op);
3844   SDValue ShOpLo = Op.getOperand(0);
3845   SDValue ShOpHi = Op.getOperand(1);
3846   SDValue ShAmt  = Op.getOperand(2);
3847   SDValue ARMcc;
3848   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3849
3850   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3851
3852   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3853                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3854   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3855   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3856                                    DAG.getConstant(VTBits, MVT::i32));
3857   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3858   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3859   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3860
3861   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3862   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3863                           ARMcc, DAG, dl);
3864   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3865   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3866                            CCR, Cmp);
3867
3868   SDValue Ops[2] = { Lo, Hi };
3869   return DAG.getMergeValues(Ops, 2, dl);
3870 }
3871
3872 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3873 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3874 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3875                                                SelectionDAG &DAG) const {
3876   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3877   EVT VT = Op.getValueType();
3878   unsigned VTBits = VT.getSizeInBits();
3879   SDLoc dl(Op);
3880   SDValue ShOpLo = Op.getOperand(0);
3881   SDValue ShOpHi = Op.getOperand(1);
3882   SDValue ShAmt  = Op.getOperand(2);
3883   SDValue ARMcc;
3884
3885   assert(Op.getOpcode() == ISD::SHL_PARTS);
3886   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3887                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3888   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3889   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3890                                    DAG.getConstant(VTBits, MVT::i32));
3891   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3892   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3893
3894   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3895   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3896   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3897                           ARMcc, DAG, dl);
3898   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3899   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3900                            CCR, Cmp);
3901
3902   SDValue Ops[2] = { Lo, Hi };
3903   return DAG.getMergeValues(Ops, 2, dl);
3904 }
3905
3906 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3907                                             SelectionDAG &DAG) const {
3908   // The rounding mode is in bits 23:22 of the FPSCR.
3909   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3910   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3911   // so that the shift + and get folded into a bitfield extract.
3912   SDLoc dl(Op);
3913   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3914                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3915                                               MVT::i32));
3916   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3917                                   DAG.getConstant(1U << 22, MVT::i32));
3918   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3919                               DAG.getConstant(22, MVT::i32));
3920   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3921                      DAG.getConstant(3, MVT::i32));
3922 }
3923
3924 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3925                          const ARMSubtarget *ST) {
3926   EVT VT = N->getValueType(0);
3927   SDLoc dl(N);
3928
3929   if (!ST->hasV6T2Ops())
3930     return SDValue();
3931
3932   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3933   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3934 }
3935
3936 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3937 /// for each 16-bit element from operand, repeated.  The basic idea is to
3938 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3939 ///
3940 /// Trace for v4i16:
3941 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
3942 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3943 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3944 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3945 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
3946 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
3947 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3948 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
3949 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3950   EVT VT = N->getValueType(0);
3951   SDLoc DL(N);
3952
3953   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
3954   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
3955   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
3956   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
3957   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
3958   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
3959 }
3960
3961 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
3962 /// bit-count for each 16-bit element from the operand.  We need slightly
3963 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
3964 /// 64/128-bit registers.
3965 ///
3966 /// Trace for v4i16:
3967 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
3968 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
3969 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
3970 /// v4i16:Extracted = [k0    k1    k2    k3    ]
3971 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
3972   EVT VT = N->getValueType(0);
3973   SDLoc DL(N);
3974
3975   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
3976   if (VT.is64BitVector()) {
3977     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
3978     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
3979                        DAG.getIntPtrConstant(0));
3980   } else {
3981     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
3982                                     BitCounts, DAG.getIntPtrConstant(0));
3983     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
3984   }
3985 }
3986
3987 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
3988 /// bit-count for each 32-bit element from the operand.  The idea here is
3989 /// to split the vector into 16-bit elements, leverage the 16-bit count
3990 /// routine, and then combine the results.
3991 ///
3992 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
3993 /// input    = [v0    v1    ] (vi: 32-bit elements)
3994 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
3995 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
3996 /// vrev: N0 = [k1 k0 k3 k2 ]
3997 ///            [k0 k1 k2 k3 ]
3998 ///       N1 =+[k1 k0 k3 k2 ]
3999 ///            [k0 k2 k1 k3 ]
4000 ///       N2 =+[k1 k3 k0 k2 ]
4001 ///            [k0    k2    k1    k3    ]
4002 /// Extended =+[k1    k3    k0    k2    ]
4003 ///            [k0    k2    ]
4004 /// Extracted=+[k1    k3    ]
4005 ///
4006 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4007   EVT VT = N->getValueType(0);
4008   SDLoc DL(N);
4009
4010   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4011
4012   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4013   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4014   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4015   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4016   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4017
4018   if (VT.is64BitVector()) {
4019     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4020     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4021                        DAG.getIntPtrConstant(0));
4022   } else {
4023     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4024                                     DAG.getIntPtrConstant(0));
4025     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4026   }
4027 }
4028
4029 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4030                           const ARMSubtarget *ST) {
4031   EVT VT = N->getValueType(0);
4032
4033   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4034   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4035           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4036          "Unexpected type for custom ctpop lowering");
4037
4038   if (VT.getVectorElementType() == MVT::i32)
4039     return lowerCTPOP32BitElements(N, DAG);
4040   else
4041     return lowerCTPOP16BitElements(N, DAG);
4042 }
4043
4044 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4045                           const ARMSubtarget *ST) {
4046   EVT VT = N->getValueType(0);
4047   SDLoc dl(N);
4048
4049   if (!VT.isVector())
4050     return SDValue();
4051
4052   // Lower vector shifts on NEON to use VSHL.
4053   assert(ST->hasNEON() && "unexpected vector shift");
4054
4055   // Left shifts translate directly to the vshiftu intrinsic.
4056   if (N->getOpcode() == ISD::SHL)
4057     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4058                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4059                        N->getOperand(0), N->getOperand(1));
4060
4061   assert((N->getOpcode() == ISD::SRA ||
4062           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4063
4064   // NEON uses the same intrinsics for both left and right shifts.  For
4065   // right shifts, the shift amounts are negative, so negate the vector of
4066   // shift amounts.
4067   EVT ShiftVT = N->getOperand(1).getValueType();
4068   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4069                                      getZeroVector(ShiftVT, DAG, dl),
4070                                      N->getOperand(1));
4071   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4072                              Intrinsic::arm_neon_vshifts :
4073                              Intrinsic::arm_neon_vshiftu);
4074   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4075                      DAG.getConstant(vshiftInt, MVT::i32),
4076                      N->getOperand(0), NegatedCount);
4077 }
4078
4079 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4080                                 const ARMSubtarget *ST) {
4081   EVT VT = N->getValueType(0);
4082   SDLoc dl(N);
4083
4084   // We can get here for a node like i32 = ISD::SHL i32, i64
4085   if (VT != MVT::i64)
4086     return SDValue();
4087
4088   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4089          "Unknown shift to lower!");
4090
4091   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4092   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4093       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4094     return SDValue();
4095
4096   // If we are in thumb mode, we don't have RRX.
4097   if (ST->isThumb1Only()) return SDValue();
4098
4099   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4100   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4101                            DAG.getConstant(0, MVT::i32));
4102   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4103                            DAG.getConstant(1, MVT::i32));
4104
4105   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4106   // captures the result into a carry flag.
4107   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4108   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
4109
4110   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4111   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4112
4113   // Merge the pieces into a single i64 value.
4114  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4115 }
4116
4117 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4118   SDValue TmpOp0, TmpOp1;
4119   bool Invert = false;
4120   bool Swap = false;
4121   unsigned Opc = 0;
4122
4123   SDValue Op0 = Op.getOperand(0);
4124   SDValue Op1 = Op.getOperand(1);
4125   SDValue CC = Op.getOperand(2);
4126   EVT VT = Op.getValueType();
4127   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4128   SDLoc dl(Op);
4129
4130   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4131     switch (SetCCOpcode) {
4132     default: llvm_unreachable("Illegal FP comparison");
4133     case ISD::SETUNE:
4134     case ISD::SETNE:  Invert = true; // Fallthrough
4135     case ISD::SETOEQ:
4136     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4137     case ISD::SETOLT:
4138     case ISD::SETLT: Swap = true; // Fallthrough
4139     case ISD::SETOGT:
4140     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4141     case ISD::SETOLE:
4142     case ISD::SETLE:  Swap = true; // Fallthrough
4143     case ISD::SETOGE:
4144     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4145     case ISD::SETUGE: Swap = true; // Fallthrough
4146     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4147     case ISD::SETUGT: Swap = true; // Fallthrough
4148     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4149     case ISD::SETUEQ: Invert = true; // Fallthrough
4150     case ISD::SETONE:
4151       // Expand this to (OLT | OGT).
4152       TmpOp0 = Op0;
4153       TmpOp1 = Op1;
4154       Opc = ISD::OR;
4155       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4156       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4157       break;
4158     case ISD::SETUO: Invert = true; // Fallthrough
4159     case ISD::SETO:
4160       // Expand this to (OLT | OGE).
4161       TmpOp0 = Op0;
4162       TmpOp1 = Op1;
4163       Opc = ISD::OR;
4164       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4165       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4166       break;
4167     }
4168   } else {
4169     // Integer comparisons.
4170     switch (SetCCOpcode) {
4171     default: llvm_unreachable("Illegal integer comparison");
4172     case ISD::SETNE:  Invert = true;
4173     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4174     case ISD::SETLT:  Swap = true;
4175     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4176     case ISD::SETLE:  Swap = true;
4177     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4178     case ISD::SETULT: Swap = true;
4179     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4180     case ISD::SETULE: Swap = true;
4181     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4182     }
4183
4184     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4185     if (Opc == ARMISD::VCEQ) {
4186
4187       SDValue AndOp;
4188       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4189         AndOp = Op0;
4190       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4191         AndOp = Op1;
4192
4193       // Ignore bitconvert.
4194       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4195         AndOp = AndOp.getOperand(0);
4196
4197       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4198         Opc = ARMISD::VTST;
4199         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4200         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4201         Invert = !Invert;
4202       }
4203     }
4204   }
4205
4206   if (Swap)
4207     std::swap(Op0, Op1);
4208
4209   // If one of the operands is a constant vector zero, attempt to fold the
4210   // comparison to a specialized compare-against-zero form.
4211   SDValue SingleOp;
4212   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4213     SingleOp = Op0;
4214   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4215     if (Opc == ARMISD::VCGE)
4216       Opc = ARMISD::VCLEZ;
4217     else if (Opc == ARMISD::VCGT)
4218       Opc = ARMISD::VCLTZ;
4219     SingleOp = Op1;
4220   }
4221
4222   SDValue Result;
4223   if (SingleOp.getNode()) {
4224     switch (Opc) {
4225     case ARMISD::VCEQ:
4226       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4227     case ARMISD::VCGE:
4228       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4229     case ARMISD::VCLEZ:
4230       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4231     case ARMISD::VCGT:
4232       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4233     case ARMISD::VCLTZ:
4234       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4235     default:
4236       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4237     }
4238   } else {
4239      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4240   }
4241
4242   if (Invert)
4243     Result = DAG.getNOT(dl, Result, VT);
4244
4245   return Result;
4246 }
4247
4248 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4249 /// valid vector constant for a NEON instruction with a "modified immediate"
4250 /// operand (e.g., VMOV).  If so, return the encoded value.
4251 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4252                                  unsigned SplatBitSize, SelectionDAG &DAG,
4253                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4254   unsigned OpCmode, Imm;
4255
4256   // SplatBitSize is set to the smallest size that splats the vector, so a
4257   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4258   // immediate instructions others than VMOV do not support the 8-bit encoding
4259   // of a zero vector, and the default encoding of zero is supposed to be the
4260   // 32-bit version.
4261   if (SplatBits == 0)
4262     SplatBitSize = 32;
4263
4264   switch (SplatBitSize) {
4265   case 8:
4266     if (type != VMOVModImm)
4267       return SDValue();
4268     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4269     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4270     OpCmode = 0xe;
4271     Imm = SplatBits;
4272     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4273     break;
4274
4275   case 16:
4276     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4277     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4278     if ((SplatBits & ~0xff) == 0) {
4279       // Value = 0x00nn: Op=x, Cmode=100x.
4280       OpCmode = 0x8;
4281       Imm = SplatBits;
4282       break;
4283     }
4284     if ((SplatBits & ~0xff00) == 0) {
4285       // Value = 0xnn00: Op=x, Cmode=101x.
4286       OpCmode = 0xa;
4287       Imm = SplatBits >> 8;
4288       break;
4289     }
4290     return SDValue();
4291
4292   case 32:
4293     // NEON's 32-bit VMOV supports splat values where:
4294     // * only one byte is nonzero, or
4295     // * the least significant byte is 0xff and the second byte is nonzero, or
4296     // * the least significant 2 bytes are 0xff and the third is nonzero.
4297     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4298     if ((SplatBits & ~0xff) == 0) {
4299       // Value = 0x000000nn: Op=x, Cmode=000x.
4300       OpCmode = 0;
4301       Imm = SplatBits;
4302       break;
4303     }
4304     if ((SplatBits & ~0xff00) == 0) {
4305       // Value = 0x0000nn00: Op=x, Cmode=001x.
4306       OpCmode = 0x2;
4307       Imm = SplatBits >> 8;
4308       break;
4309     }
4310     if ((SplatBits & ~0xff0000) == 0) {
4311       // Value = 0x00nn0000: Op=x, Cmode=010x.
4312       OpCmode = 0x4;
4313       Imm = SplatBits >> 16;
4314       break;
4315     }
4316     if ((SplatBits & ~0xff000000) == 0) {
4317       // Value = 0xnn000000: Op=x, Cmode=011x.
4318       OpCmode = 0x6;
4319       Imm = SplatBits >> 24;
4320       break;
4321     }
4322
4323     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4324     if (type == OtherModImm) return SDValue();
4325
4326     if ((SplatBits & ~0xffff) == 0 &&
4327         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4328       // Value = 0x0000nnff: Op=x, Cmode=1100.
4329       OpCmode = 0xc;
4330       Imm = SplatBits >> 8;
4331       SplatBits |= 0xff;
4332       break;
4333     }
4334
4335     if ((SplatBits & ~0xffffff) == 0 &&
4336         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4337       // Value = 0x00nnffff: Op=x, Cmode=1101.
4338       OpCmode = 0xd;
4339       Imm = SplatBits >> 16;
4340       SplatBits |= 0xffff;
4341       break;
4342     }
4343
4344     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4345     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4346     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4347     // and fall through here to test for a valid 64-bit splat.  But, then the
4348     // caller would also need to check and handle the change in size.
4349     return SDValue();
4350
4351   case 64: {
4352     if (type != VMOVModImm)
4353       return SDValue();
4354     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4355     uint64_t BitMask = 0xff;
4356     uint64_t Val = 0;
4357     unsigned ImmMask = 1;
4358     Imm = 0;
4359     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4360       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4361         Val |= BitMask;
4362         Imm |= ImmMask;
4363       } else if ((SplatBits & BitMask) != 0) {
4364         return SDValue();
4365       }
4366       BitMask <<= 8;
4367       ImmMask <<= 1;
4368     }
4369     // Op=1, Cmode=1110.
4370     OpCmode = 0x1e;
4371     SplatBits = Val;
4372     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4373     break;
4374   }
4375
4376   default:
4377     llvm_unreachable("unexpected size for isNEONModifiedImm");
4378   }
4379
4380   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4381   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4382 }
4383
4384 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4385                                            const ARMSubtarget *ST) const {
4386   if (!ST->hasVFP3())
4387     return SDValue();
4388
4389   bool IsDouble = Op.getValueType() == MVT::f64;
4390   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4391
4392   // Try splatting with a VMOV.f32...
4393   APFloat FPVal = CFP->getValueAPF();
4394   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4395
4396   if (ImmVal != -1) {
4397     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4398       // We have code in place to select a valid ConstantFP already, no need to
4399       // do any mangling.
4400       return Op;
4401     }
4402
4403     // It's a float and we are trying to use NEON operations where
4404     // possible. Lower it to a splat followed by an extract.
4405     SDLoc DL(Op);
4406     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4407     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4408                                       NewVal);
4409     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4410                        DAG.getConstant(0, MVT::i32));
4411   }
4412
4413   // The rest of our options are NEON only, make sure that's allowed before
4414   // proceeding..
4415   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4416     return SDValue();
4417
4418   EVT VMovVT;
4419   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4420
4421   // It wouldn't really be worth bothering for doubles except for one very
4422   // important value, which does happen to match: 0.0. So make sure we don't do
4423   // anything stupid.
4424   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4425     return SDValue();
4426
4427   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4428   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4429                                      false, VMOVModImm);
4430   if (NewVal != SDValue()) {
4431     SDLoc DL(Op);
4432     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4433                                       NewVal);
4434     if (IsDouble)
4435       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4436
4437     // It's a float: cast and extract a vector element.
4438     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4439                                        VecConstant);
4440     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4441                        DAG.getConstant(0, MVT::i32));
4442   }
4443
4444   // Finally, try a VMVN.i32
4445   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4446                              false, VMVNModImm);
4447   if (NewVal != SDValue()) {
4448     SDLoc DL(Op);
4449     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4450
4451     if (IsDouble)
4452       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4453
4454     // It's a float: cast and extract a vector element.
4455     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4456                                        VecConstant);
4457     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4458                        DAG.getConstant(0, MVT::i32));
4459   }
4460
4461   return SDValue();
4462 }
4463
4464 // check if an VEXT instruction can handle the shuffle mask when the
4465 // vector sources of the shuffle are the same.
4466 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4467   unsigned NumElts = VT.getVectorNumElements();
4468
4469   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4470   if (M[0] < 0)
4471     return false;
4472
4473   Imm = M[0];
4474
4475   // If this is a VEXT shuffle, the immediate value is the index of the first
4476   // element.  The other shuffle indices must be the successive elements after
4477   // the first one.
4478   unsigned ExpectedElt = Imm;
4479   for (unsigned i = 1; i < NumElts; ++i) {
4480     // Increment the expected index.  If it wraps around, just follow it
4481     // back to index zero and keep going.
4482     ++ExpectedElt;
4483     if (ExpectedElt == NumElts)
4484       ExpectedElt = 0;
4485
4486     if (M[i] < 0) continue; // ignore UNDEF indices
4487     if (ExpectedElt != static_cast<unsigned>(M[i]))
4488       return false;
4489   }
4490
4491   return true;
4492 }
4493
4494
4495 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4496                        bool &ReverseVEXT, unsigned &Imm) {
4497   unsigned NumElts = VT.getVectorNumElements();
4498   ReverseVEXT = false;
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, it may still be
4512     // a VEXT but the source vectors must be swapped.
4513     ExpectedElt += 1;
4514     if (ExpectedElt == NumElts * 2) {
4515       ExpectedElt = 0;
4516       ReverseVEXT = true;
4517     }
4518
4519     if (M[i] < 0) continue; // ignore UNDEF indices
4520     if (ExpectedElt != static_cast<unsigned>(M[i]))
4521       return false;
4522   }
4523
4524   // Adjust the index value if the source operands will be swapped.
4525   if (ReverseVEXT)
4526     Imm -= NumElts;
4527
4528   return true;
4529 }
4530
4531 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4532 /// instruction with the specified blocksize.  (The order of the elements
4533 /// within each block of the vector is reversed.)
4534 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4535   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4536          "Only possible block sizes for VREV are: 16, 32, 64");
4537
4538   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4539   if (EltSz == 64)
4540     return false;
4541
4542   unsigned NumElts = VT.getVectorNumElements();
4543   unsigned BlockElts = M[0] + 1;
4544   // If the first shuffle index is UNDEF, be optimistic.
4545   if (M[0] < 0)
4546     BlockElts = BlockSize / EltSz;
4547
4548   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4549     return false;
4550
4551   for (unsigned i = 0; i < NumElts; ++i) {
4552     if (M[i] < 0) continue; // ignore UNDEF indices
4553     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4554       return false;
4555   }
4556
4557   return true;
4558 }
4559
4560 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4561   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4562   // range, then 0 is placed into the resulting vector. So pretty much any mask
4563   // of 8 elements can work here.
4564   return VT == MVT::v8i8 && M.size() == 8;
4565 }
4566
4567 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4568   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4569   if (EltSz == 64)
4570     return false;
4571
4572   unsigned NumElts = VT.getVectorNumElements();
4573   WhichResult = (M[0] == 0 ? 0 : 1);
4574   for (unsigned i = 0; i < NumElts; i += 2) {
4575     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4576         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4577       return false;
4578   }
4579   return true;
4580 }
4581
4582 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4583 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4584 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4585 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4586   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4587   if (EltSz == 64)
4588     return false;
4589
4590   unsigned NumElts = VT.getVectorNumElements();
4591   WhichResult = (M[0] == 0 ? 0 : 1);
4592   for (unsigned i = 0; i < NumElts; i += 2) {
4593     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4594         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4595       return false;
4596   }
4597   return true;
4598 }
4599
4600 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4601   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4602   if (EltSz == 64)
4603     return false;
4604
4605   unsigned NumElts = VT.getVectorNumElements();
4606   WhichResult = (M[0] == 0 ? 0 : 1);
4607   for (unsigned i = 0; i != NumElts; ++i) {
4608     if (M[i] < 0) continue; // ignore UNDEF indices
4609     if ((unsigned) M[i] != 2 * i + WhichResult)
4610       return false;
4611   }
4612
4613   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4614   if (VT.is64BitVector() && EltSz == 32)
4615     return false;
4616
4617   return true;
4618 }
4619
4620 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4621 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4622 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4623 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4624   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4625   if (EltSz == 64)
4626     return false;
4627
4628   unsigned Half = VT.getVectorNumElements() / 2;
4629   WhichResult = (M[0] == 0 ? 0 : 1);
4630   for (unsigned j = 0; j != 2; ++j) {
4631     unsigned Idx = WhichResult;
4632     for (unsigned i = 0; i != Half; ++i) {
4633       int MIdx = M[i + j * Half];
4634       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4635         return false;
4636       Idx += 2;
4637     }
4638   }
4639
4640   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4641   if (VT.is64BitVector() && EltSz == 32)
4642     return false;
4643
4644   return true;
4645 }
4646
4647 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4648   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4649   if (EltSz == 64)
4650     return false;
4651
4652   unsigned NumElts = VT.getVectorNumElements();
4653   WhichResult = (M[0] == 0 ? 0 : 1);
4654   unsigned Idx = WhichResult * NumElts / 2;
4655   for (unsigned i = 0; i != NumElts; i += 2) {
4656     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4657         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4658       return false;
4659     Idx += 1;
4660   }
4661
4662   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4663   if (VT.is64BitVector() && EltSz == 32)
4664     return false;
4665
4666   return true;
4667 }
4668
4669 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4670 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4671 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4672 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4673   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4674   if (EltSz == 64)
4675     return false;
4676
4677   unsigned NumElts = VT.getVectorNumElements();
4678   WhichResult = (M[0] == 0 ? 0 : 1);
4679   unsigned Idx = WhichResult * NumElts / 2;
4680   for (unsigned i = 0; i != NumElts; i += 2) {
4681     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4682         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4683       return false;
4684     Idx += 1;
4685   }
4686
4687   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4688   if (VT.is64BitVector() && EltSz == 32)
4689     return false;
4690
4691   return true;
4692 }
4693
4694 /// \return true if this is a reverse operation on an vector.
4695 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4696   unsigned NumElts = VT.getVectorNumElements();
4697   // Make sure the mask has the right size.
4698   if (NumElts != M.size())
4699       return false;
4700
4701   // Look for <15, ..., 3, -1, 1, 0>.
4702   for (unsigned i = 0; i != NumElts; ++i)
4703     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4704       return false;
4705
4706   return true;
4707 }
4708
4709 // If N is an integer constant that can be moved into a register in one
4710 // instruction, return an SDValue of such a constant (will become a MOV
4711 // instruction).  Otherwise return null.
4712 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4713                                      const ARMSubtarget *ST, SDLoc dl) {
4714   uint64_t Val;
4715   if (!isa<ConstantSDNode>(N))
4716     return SDValue();
4717   Val = cast<ConstantSDNode>(N)->getZExtValue();
4718
4719   if (ST->isThumb1Only()) {
4720     if (Val <= 255 || ~Val <= 255)
4721       return DAG.getConstant(Val, MVT::i32);
4722   } else {
4723     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4724       return DAG.getConstant(Val, MVT::i32);
4725   }
4726   return SDValue();
4727 }
4728
4729 // If this is a case we can't handle, return null and let the default
4730 // expansion code take care of it.
4731 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4732                                              const ARMSubtarget *ST) const {
4733   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4734   SDLoc dl(Op);
4735   EVT VT = Op.getValueType();
4736
4737   APInt SplatBits, SplatUndef;
4738   unsigned SplatBitSize;
4739   bool HasAnyUndefs;
4740   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4741     if (SplatBitSize <= 64) {
4742       // Check if an immediate VMOV works.
4743       EVT VmovVT;
4744       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4745                                       SplatUndef.getZExtValue(), SplatBitSize,
4746                                       DAG, VmovVT, VT.is128BitVector(),
4747                                       VMOVModImm);
4748       if (Val.getNode()) {
4749         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4750         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4751       }
4752
4753       // Try an immediate VMVN.
4754       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4755       Val = isNEONModifiedImm(NegatedImm,
4756                                       SplatUndef.getZExtValue(), SplatBitSize,
4757                                       DAG, VmovVT, VT.is128BitVector(),
4758                                       VMVNModImm);
4759       if (Val.getNode()) {
4760         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4761         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4762       }
4763
4764       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4765       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4766         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4767         if (ImmVal != -1) {
4768           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4769           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4770         }
4771       }
4772     }
4773   }
4774
4775   // Scan through the operands to see if only one value is used.
4776   //
4777   // As an optimisation, even if more than one value is used it may be more
4778   // profitable to splat with one value then change some lanes.
4779   //
4780   // Heuristically we decide to do this if the vector has a "dominant" value,
4781   // defined as splatted to more than half of the lanes.
4782   unsigned NumElts = VT.getVectorNumElements();
4783   bool isOnlyLowElement = true;
4784   bool usesOnlyOneValue = true;
4785   bool hasDominantValue = false;
4786   bool isConstant = true;
4787
4788   // Map of the number of times a particular SDValue appears in the
4789   // element list.
4790   DenseMap<SDValue, unsigned> ValueCounts;
4791   SDValue Value;
4792   for (unsigned i = 0; i < NumElts; ++i) {
4793     SDValue V = Op.getOperand(i);
4794     if (V.getOpcode() == ISD::UNDEF)
4795       continue;
4796     if (i > 0)
4797       isOnlyLowElement = false;
4798     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4799       isConstant = false;
4800
4801     ValueCounts.insert(std::make_pair(V, 0));
4802     unsigned &Count = ValueCounts[V];
4803
4804     // Is this value dominant? (takes up more than half of the lanes)
4805     if (++Count > (NumElts / 2)) {
4806       hasDominantValue = true;
4807       Value = V;
4808     }
4809   }
4810   if (ValueCounts.size() != 1)
4811     usesOnlyOneValue = false;
4812   if (!Value.getNode() && ValueCounts.size() > 0)
4813     Value = ValueCounts.begin()->first;
4814
4815   if (ValueCounts.size() == 0)
4816     return DAG.getUNDEF(VT);
4817
4818   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
4819   // Keep going if we are hitting this case.
4820   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
4821     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4822
4823   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4824
4825   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4826   // i32 and try again.
4827   if (hasDominantValue && EltSize <= 32) {
4828     if (!isConstant) {
4829       SDValue N;
4830
4831       // If we are VDUPing a value that comes directly from a vector, that will
4832       // cause an unnecessary move to and from a GPR, where instead we could
4833       // just use VDUPLANE. We can only do this if the lane being extracted
4834       // is at a constant index, as the VDUP from lane instructions only have
4835       // constant-index forms.
4836       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4837           isa<ConstantSDNode>(Value->getOperand(1))) {
4838         // We need to create a new undef vector to use for the VDUPLANE if the
4839         // size of the vector from which we get the value is different than the
4840         // size of the vector that we need to create. We will insert the element
4841         // such that the register coalescer will remove unnecessary copies.
4842         if (VT != Value->getOperand(0).getValueType()) {
4843           ConstantSDNode *constIndex;
4844           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4845           assert(constIndex && "The index is not a constant!");
4846           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4847                              VT.getVectorNumElements();
4848           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4849                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4850                         Value, DAG.getConstant(index, MVT::i32)),
4851                            DAG.getConstant(index, MVT::i32));
4852         } else
4853           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4854                         Value->getOperand(0), Value->getOperand(1));
4855       } else
4856         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4857
4858       if (!usesOnlyOneValue) {
4859         // The dominant value was splatted as 'N', but we now have to insert
4860         // all differing elements.
4861         for (unsigned I = 0; I < NumElts; ++I) {
4862           if (Op.getOperand(I) == Value)
4863             continue;
4864           SmallVector<SDValue, 3> Ops;
4865           Ops.push_back(N);
4866           Ops.push_back(Op.getOperand(I));
4867           Ops.push_back(DAG.getConstant(I, MVT::i32));
4868           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4869         }
4870       }
4871       return N;
4872     }
4873     if (VT.getVectorElementType().isFloatingPoint()) {
4874       SmallVector<SDValue, 8> Ops;
4875       for (unsigned i = 0; i < NumElts; ++i)
4876         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4877                                   Op.getOperand(i)));
4878       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4879       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4880       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4881       if (Val.getNode())
4882         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4883     }
4884     if (usesOnlyOneValue) {
4885       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4886       if (isConstant && Val.getNode())
4887         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4888     }
4889   }
4890
4891   // If all elements are constants and the case above didn't get hit, fall back
4892   // to the default expansion, which will generate a load from the constant
4893   // pool.
4894   if (isConstant)
4895     return SDValue();
4896
4897   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4898   if (NumElts >= 4) {
4899     SDValue shuffle = ReconstructShuffle(Op, DAG);
4900     if (shuffle != SDValue())
4901       return shuffle;
4902   }
4903
4904   // Vectors with 32- or 64-bit elements can be built by directly assigning
4905   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4906   // will be legalized.
4907   if (EltSize >= 32) {
4908     // Do the expansion with floating-point types, since that is what the VFP
4909     // registers are defined to use, and since i64 is not legal.
4910     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4911     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4912     SmallVector<SDValue, 8> Ops;
4913     for (unsigned i = 0; i < NumElts; ++i)
4914       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4915     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4916     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4917   }
4918
4919   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
4920   // know the default expansion would otherwise fall back on something even
4921   // worse. For a vector with one or two non-undef values, that's
4922   // scalar_to_vector for the elements followed by a shuffle (provided the
4923   // shuffle is valid for the target) and materialization element by element
4924   // on the stack followed by a load for everything else.
4925   if (!isConstant && !usesOnlyOneValue) {
4926     SDValue Vec = DAG.getUNDEF(VT);
4927     for (unsigned i = 0 ; i < NumElts; ++i) {
4928       SDValue V = Op.getOperand(i);
4929       if (V.getOpcode() == ISD::UNDEF)
4930         continue;
4931       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
4932       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
4933     }
4934     return Vec;
4935   }
4936
4937   return SDValue();
4938 }
4939
4940 // Gather data to see if the operation can be modelled as a
4941 // shuffle in combination with VEXTs.
4942 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4943                                               SelectionDAG &DAG) const {
4944   SDLoc dl(Op);
4945   EVT VT = Op.getValueType();
4946   unsigned NumElts = VT.getVectorNumElements();
4947
4948   SmallVector<SDValue, 2> SourceVecs;
4949   SmallVector<unsigned, 2> MinElts;
4950   SmallVector<unsigned, 2> MaxElts;
4951
4952   for (unsigned i = 0; i < NumElts; ++i) {
4953     SDValue V = Op.getOperand(i);
4954     if (V.getOpcode() == ISD::UNDEF)
4955       continue;
4956     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4957       // A shuffle can only come from building a vector from various
4958       // elements of other vectors.
4959       return SDValue();
4960     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4961                VT.getVectorElementType()) {
4962       // This code doesn't know how to handle shuffles where the vector
4963       // element types do not match (this happens because type legalization
4964       // promotes the return type of EXTRACT_VECTOR_ELT).
4965       // FIXME: It might be appropriate to extend this code to handle
4966       // mismatched types.
4967       return SDValue();
4968     }
4969
4970     // Record this extraction against the appropriate vector if possible...
4971     SDValue SourceVec = V.getOperand(0);
4972     // If the element number isn't a constant, we can't effectively
4973     // analyze what's going on.
4974     if (!isa<ConstantSDNode>(V.getOperand(1)))
4975       return SDValue();
4976     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4977     bool FoundSource = false;
4978     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4979       if (SourceVecs[j] == SourceVec) {
4980         if (MinElts[j] > EltNo)
4981           MinElts[j] = EltNo;
4982         if (MaxElts[j] < EltNo)
4983           MaxElts[j] = EltNo;
4984         FoundSource = true;
4985         break;
4986       }
4987     }
4988
4989     // Or record a new source if not...
4990     if (!FoundSource) {
4991       SourceVecs.push_back(SourceVec);
4992       MinElts.push_back(EltNo);
4993       MaxElts.push_back(EltNo);
4994     }
4995   }
4996
4997   // Currently only do something sane when at most two source vectors
4998   // involved.
4999   if (SourceVecs.size() > 2)
5000     return SDValue();
5001
5002   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5003   int VEXTOffsets[2] = {0, 0};
5004
5005   // This loop extracts the usage patterns of the source vectors
5006   // and prepares appropriate SDValues for a shuffle if possible.
5007   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5008     if (SourceVecs[i].getValueType() == VT) {
5009       // No VEXT necessary
5010       ShuffleSrcs[i] = SourceVecs[i];
5011       VEXTOffsets[i] = 0;
5012       continue;
5013     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5014       // It probably isn't worth padding out a smaller vector just to
5015       // break it down again in a shuffle.
5016       return SDValue();
5017     }
5018
5019     // Since only 64-bit and 128-bit vectors are legal on ARM and
5020     // we've eliminated the other cases...
5021     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5022            "unexpected vector sizes in ReconstructShuffle");
5023
5024     if (MaxElts[i] - MinElts[i] >= NumElts) {
5025       // Span too large for a VEXT to cope
5026       return SDValue();
5027     }
5028
5029     if (MinElts[i] >= NumElts) {
5030       // The extraction can just take the second half
5031       VEXTOffsets[i] = NumElts;
5032       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5033                                    SourceVecs[i],
5034                                    DAG.getIntPtrConstant(NumElts));
5035     } else if (MaxElts[i] < NumElts) {
5036       // The extraction can just take the first half
5037       VEXTOffsets[i] = 0;
5038       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5039                                    SourceVecs[i],
5040                                    DAG.getIntPtrConstant(0));
5041     } else {
5042       // An actual VEXT is needed
5043       VEXTOffsets[i] = MinElts[i];
5044       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5045                                      SourceVecs[i],
5046                                      DAG.getIntPtrConstant(0));
5047       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5048                                      SourceVecs[i],
5049                                      DAG.getIntPtrConstant(NumElts));
5050       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5051                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5052     }
5053   }
5054
5055   SmallVector<int, 8> Mask;
5056
5057   for (unsigned i = 0; i < NumElts; ++i) {
5058     SDValue Entry = Op.getOperand(i);
5059     if (Entry.getOpcode() == ISD::UNDEF) {
5060       Mask.push_back(-1);
5061       continue;
5062     }
5063
5064     SDValue ExtractVec = Entry.getOperand(0);
5065     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5066                                           .getOperand(1))->getSExtValue();
5067     if (ExtractVec == SourceVecs[0]) {
5068       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5069     } else {
5070       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5071     }
5072   }
5073
5074   // Final check before we try to produce nonsense...
5075   if (isShuffleMaskLegal(Mask, VT))
5076     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5077                                 &Mask[0]);
5078
5079   return SDValue();
5080 }
5081
5082 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5083 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5084 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5085 /// are assumed to be legal.
5086 bool
5087 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5088                                       EVT VT) const {
5089   if (VT.getVectorNumElements() == 4 &&
5090       (VT.is128BitVector() || VT.is64BitVector())) {
5091     unsigned PFIndexes[4];
5092     for (unsigned i = 0; i != 4; ++i) {
5093       if (M[i] < 0)
5094         PFIndexes[i] = 8;
5095       else
5096         PFIndexes[i] = M[i];
5097     }
5098
5099     // Compute the index in the perfect shuffle table.
5100     unsigned PFTableIndex =
5101       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5102     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5103     unsigned Cost = (PFEntry >> 30);
5104
5105     if (Cost <= 4)
5106       return true;
5107   }
5108
5109   bool ReverseVEXT;
5110   unsigned Imm, WhichResult;
5111
5112   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5113   return (EltSize >= 32 ||
5114           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5115           isVREVMask(M, VT, 64) ||
5116           isVREVMask(M, VT, 32) ||
5117           isVREVMask(M, VT, 16) ||
5118           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5119           isVTBLMask(M, VT) ||
5120           isVTRNMask(M, VT, WhichResult) ||
5121           isVUZPMask(M, VT, WhichResult) ||
5122           isVZIPMask(M, VT, WhichResult) ||
5123           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5124           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5125           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5126           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5127 }
5128
5129 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5130 /// the specified operations to build the shuffle.
5131 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5132                                       SDValue RHS, SelectionDAG &DAG,
5133                                       SDLoc dl) {
5134   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5135   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5136   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5137
5138   enum {
5139     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5140     OP_VREV,
5141     OP_VDUP0,
5142     OP_VDUP1,
5143     OP_VDUP2,
5144     OP_VDUP3,
5145     OP_VEXT1,
5146     OP_VEXT2,
5147     OP_VEXT3,
5148     OP_VUZPL, // VUZP, left result
5149     OP_VUZPR, // VUZP, right result
5150     OP_VZIPL, // VZIP, left result
5151     OP_VZIPR, // VZIP, right result
5152     OP_VTRNL, // VTRN, left result
5153     OP_VTRNR  // VTRN, right result
5154   };
5155
5156   if (OpNum == OP_COPY) {
5157     if (LHSID == (1*9+2)*9+3) return LHS;
5158     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5159     return RHS;
5160   }
5161
5162   SDValue OpLHS, OpRHS;
5163   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5164   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5165   EVT VT = OpLHS.getValueType();
5166
5167   switch (OpNum) {
5168   default: llvm_unreachable("Unknown shuffle opcode!");
5169   case OP_VREV:
5170     // VREV divides the vector in half and swaps within the half.
5171     if (VT.getVectorElementType() == MVT::i32 ||
5172         VT.getVectorElementType() == MVT::f32)
5173       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5174     // vrev <4 x i16> -> VREV32
5175     if (VT.getVectorElementType() == MVT::i16)
5176       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5177     // vrev <4 x i8> -> VREV16
5178     assert(VT.getVectorElementType() == MVT::i8);
5179     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5180   case OP_VDUP0:
5181   case OP_VDUP1:
5182   case OP_VDUP2:
5183   case OP_VDUP3:
5184     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5185                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5186   case OP_VEXT1:
5187   case OP_VEXT2:
5188   case OP_VEXT3:
5189     return DAG.getNode(ARMISD::VEXT, dl, VT,
5190                        OpLHS, OpRHS,
5191                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5192   case OP_VUZPL:
5193   case OP_VUZPR:
5194     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5195                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5196   case OP_VZIPL:
5197   case OP_VZIPR:
5198     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5199                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5200   case OP_VTRNL:
5201   case OP_VTRNR:
5202     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5203                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5204   }
5205 }
5206
5207 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5208                                        ArrayRef<int> ShuffleMask,
5209                                        SelectionDAG &DAG) {
5210   // Check to see if we can use the VTBL instruction.
5211   SDValue V1 = Op.getOperand(0);
5212   SDValue V2 = Op.getOperand(1);
5213   SDLoc DL(Op);
5214
5215   SmallVector<SDValue, 8> VTBLMask;
5216   for (ArrayRef<int>::iterator
5217          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5218     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5219
5220   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5221     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5222                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5223                                    &VTBLMask[0], 8));
5224
5225   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5226                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5227                                  &VTBLMask[0], 8));
5228 }
5229
5230 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5231                                                       SelectionDAG &DAG) {
5232   SDLoc DL(Op);
5233   SDValue OpLHS = Op.getOperand(0);
5234   EVT VT = OpLHS.getValueType();
5235
5236   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5237          "Expect an v8i16/v16i8 type");
5238   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5239   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5240   // extract the first 8 bytes into the top double word and the last 8 bytes
5241   // into the bottom double word. The v8i16 case is similar.
5242   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5243   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5244                      DAG.getConstant(ExtractNum, MVT::i32));
5245 }
5246
5247 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5248   SDValue V1 = Op.getOperand(0);
5249   SDValue V2 = Op.getOperand(1);
5250   SDLoc dl(Op);
5251   EVT VT = Op.getValueType();
5252   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5253
5254   // Convert shuffles that are directly supported on NEON to target-specific
5255   // DAG nodes, instead of keeping them as shuffles and matching them again
5256   // during code selection.  This is more efficient and avoids the possibility
5257   // of inconsistencies between legalization and selection.
5258   // FIXME: floating-point vectors should be canonicalized to integer vectors
5259   // of the same time so that they get CSEd properly.
5260   ArrayRef<int> ShuffleMask = SVN->getMask();
5261
5262   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5263   if (EltSize <= 32) {
5264     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5265       int Lane = SVN->getSplatIndex();
5266       // If this is undef splat, generate it via "just" vdup, if possible.
5267       if (Lane == -1) Lane = 0;
5268
5269       // Test if V1 is a SCALAR_TO_VECTOR.
5270       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5271         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5272       }
5273       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5274       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5275       // reaches it).
5276       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5277           !isa<ConstantSDNode>(V1.getOperand(0))) {
5278         bool IsScalarToVector = true;
5279         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5280           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5281             IsScalarToVector = false;
5282             break;
5283           }
5284         if (IsScalarToVector)
5285           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5286       }
5287       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5288                          DAG.getConstant(Lane, MVT::i32));
5289     }
5290
5291     bool ReverseVEXT;
5292     unsigned Imm;
5293     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5294       if (ReverseVEXT)
5295         std::swap(V1, V2);
5296       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5297                          DAG.getConstant(Imm, MVT::i32));
5298     }
5299
5300     if (isVREVMask(ShuffleMask, VT, 64))
5301       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5302     if (isVREVMask(ShuffleMask, VT, 32))
5303       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5304     if (isVREVMask(ShuffleMask, VT, 16))
5305       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5306
5307     if (V2->getOpcode() == ISD::UNDEF &&
5308         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5309       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5310                          DAG.getConstant(Imm, MVT::i32));
5311     }
5312
5313     // Check for Neon shuffles that modify both input vectors in place.
5314     // If both results are used, i.e., if there are two shuffles with the same
5315     // source operands and with masks corresponding to both results of one of
5316     // these operations, DAG memoization will ensure that a single node is
5317     // used for both shuffles.
5318     unsigned WhichResult;
5319     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5320       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5321                          V1, V2).getValue(WhichResult);
5322     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5323       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5324                          V1, V2).getValue(WhichResult);
5325     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5326       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5327                          V1, V2).getValue(WhichResult);
5328
5329     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5330       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5331                          V1, V1).getValue(WhichResult);
5332     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5333       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5334                          V1, V1).getValue(WhichResult);
5335     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5336       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5337                          V1, V1).getValue(WhichResult);
5338   }
5339
5340   // If the shuffle is not directly supported and it has 4 elements, use
5341   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5342   unsigned NumElts = VT.getVectorNumElements();
5343   if (NumElts == 4) {
5344     unsigned PFIndexes[4];
5345     for (unsigned i = 0; i != 4; ++i) {
5346       if (ShuffleMask[i] < 0)
5347         PFIndexes[i] = 8;
5348       else
5349         PFIndexes[i] = ShuffleMask[i];
5350     }
5351
5352     // Compute the index in the perfect shuffle table.
5353     unsigned PFTableIndex =
5354       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5355     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5356     unsigned Cost = (PFEntry >> 30);
5357
5358     if (Cost <= 4)
5359       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5360   }
5361
5362   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5363   if (EltSize >= 32) {
5364     // Do the expansion with floating-point types, since that is what the VFP
5365     // registers are defined to use, and since i64 is not legal.
5366     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5367     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5368     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5369     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5370     SmallVector<SDValue, 8> Ops;
5371     for (unsigned i = 0; i < NumElts; ++i) {
5372       if (ShuffleMask[i] < 0)
5373         Ops.push_back(DAG.getUNDEF(EltVT));
5374       else
5375         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5376                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5377                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5378                                                   MVT::i32)));
5379     }
5380     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5381     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5382   }
5383
5384   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5385     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5386
5387   if (VT == MVT::v8i8) {
5388     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5389     if (NewOp.getNode())
5390       return NewOp;
5391   }
5392
5393   return SDValue();
5394 }
5395
5396 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5397   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5398   SDValue Lane = Op.getOperand(2);
5399   if (!isa<ConstantSDNode>(Lane))
5400     return SDValue();
5401
5402   return Op;
5403 }
5404
5405 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5406   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5407   SDValue Lane = Op.getOperand(1);
5408   if (!isa<ConstantSDNode>(Lane))
5409     return SDValue();
5410
5411   SDValue Vec = Op.getOperand(0);
5412   if (Op.getValueType() == MVT::i32 &&
5413       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5414     SDLoc dl(Op);
5415     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5416   }
5417
5418   return Op;
5419 }
5420
5421 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5422   // The only time a CONCAT_VECTORS operation can have legal types is when
5423   // two 64-bit vectors are concatenated to a 128-bit vector.
5424   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5425          "unexpected CONCAT_VECTORS");
5426   SDLoc dl(Op);
5427   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5428   SDValue Op0 = Op.getOperand(0);
5429   SDValue Op1 = Op.getOperand(1);
5430   if (Op0.getOpcode() != ISD::UNDEF)
5431     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5432                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5433                       DAG.getIntPtrConstant(0));
5434   if (Op1.getOpcode() != ISD::UNDEF)
5435     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5436                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5437                       DAG.getIntPtrConstant(1));
5438   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5439 }
5440
5441 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5442 /// element has been zero/sign-extended, depending on the isSigned parameter,
5443 /// from an integer type half its size.
5444 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5445                                    bool isSigned) {
5446   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5447   EVT VT = N->getValueType(0);
5448   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5449     SDNode *BVN = N->getOperand(0).getNode();
5450     if (BVN->getValueType(0) != MVT::v4i32 ||
5451         BVN->getOpcode() != ISD::BUILD_VECTOR)
5452       return false;
5453     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5454     unsigned HiElt = 1 - LoElt;
5455     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5456     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5457     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5458     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5459     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5460       return false;
5461     if (isSigned) {
5462       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5463           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5464         return true;
5465     } else {
5466       if (Hi0->isNullValue() && Hi1->isNullValue())
5467         return true;
5468     }
5469     return false;
5470   }
5471
5472   if (N->getOpcode() != ISD::BUILD_VECTOR)
5473     return false;
5474
5475   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5476     SDNode *Elt = N->getOperand(i).getNode();
5477     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5478       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5479       unsigned HalfSize = EltSize / 2;
5480       if (isSigned) {
5481         if (!isIntN(HalfSize, C->getSExtValue()))
5482           return false;
5483       } else {
5484         if (!isUIntN(HalfSize, C->getZExtValue()))
5485           return false;
5486       }
5487       continue;
5488     }
5489     return false;
5490   }
5491
5492   return true;
5493 }
5494
5495 /// isSignExtended - Check if a node is a vector value that is sign-extended
5496 /// or a constant BUILD_VECTOR with sign-extended elements.
5497 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5498   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5499     return true;
5500   if (isExtendedBUILD_VECTOR(N, DAG, true))
5501     return true;
5502   return false;
5503 }
5504
5505 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5506 /// or a constant BUILD_VECTOR with zero-extended elements.
5507 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5508   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5509     return true;
5510   if (isExtendedBUILD_VECTOR(N, DAG, false))
5511     return true;
5512   return false;
5513 }
5514
5515 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5516   if (OrigVT.getSizeInBits() >= 64)
5517     return OrigVT;
5518
5519   assert(OrigVT.isSimple() && "Expecting a simple value type");
5520
5521   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5522   switch (OrigSimpleTy) {
5523   default: llvm_unreachable("Unexpected Vector Type");
5524   case MVT::v2i8:
5525   case MVT::v2i16:
5526      return MVT::v2i32;
5527   case MVT::v4i8:
5528     return  MVT::v4i16;
5529   }
5530 }
5531
5532 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5533 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5534 /// We insert the required extension here to get the vector to fill a D register.
5535 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5536                                             const EVT &OrigTy,
5537                                             const EVT &ExtTy,
5538                                             unsigned ExtOpcode) {
5539   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5540   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5541   // 64-bits we need to insert a new extension so that it will be 64-bits.
5542   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5543   if (OrigTy.getSizeInBits() >= 64)
5544     return N;
5545
5546   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5547   EVT NewVT = getExtensionTo64Bits(OrigTy);
5548
5549   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5550 }
5551
5552 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5553 /// does not do any sign/zero extension. If the original vector is less
5554 /// than 64 bits, an appropriate extension will be added after the load to
5555 /// reach a total size of 64 bits. We have to add the extension separately
5556 /// because ARM does not have a sign/zero extending load for vectors.
5557 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5558   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5559
5560   // The load already has the right type.
5561   if (ExtendedTy == LD->getMemoryVT())
5562     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5563                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5564                 LD->isNonTemporal(), LD->isInvariant(),
5565                 LD->getAlignment());
5566
5567   // We need to create a zextload/sextload. We cannot just create a load
5568   // followed by a zext/zext node because LowerMUL is also run during normal
5569   // operation legalization where we can't create illegal types.
5570   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5571                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5572                         LD->getMemoryVT(), LD->isVolatile(),
5573                         LD->isNonTemporal(), LD->getAlignment());
5574 }
5575
5576 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5577 /// extending load, or BUILD_VECTOR with extended elements, return the
5578 /// unextended value. The unextended vector should be 64 bits so that it can
5579 /// be used as an operand to a VMULL instruction. If the original vector size
5580 /// before extension is less than 64 bits we add a an extension to resize
5581 /// the vector to 64 bits.
5582 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5583   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5584     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5585                                         N->getOperand(0)->getValueType(0),
5586                                         N->getValueType(0),
5587                                         N->getOpcode());
5588
5589   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5590     return SkipLoadExtensionForVMULL(LD, DAG);
5591
5592   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5593   // have been legalized as a BITCAST from v4i32.
5594   if (N->getOpcode() == ISD::BITCAST) {
5595     SDNode *BVN = N->getOperand(0).getNode();
5596     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5597            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5598     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5599     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5600                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5601   }
5602   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5603   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5604   EVT VT = N->getValueType(0);
5605   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5606   unsigned NumElts = VT.getVectorNumElements();
5607   MVT TruncVT = MVT::getIntegerVT(EltSize);
5608   SmallVector<SDValue, 8> Ops;
5609   for (unsigned i = 0; i != NumElts; ++i) {
5610     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5611     const APInt &CInt = C->getAPIntValue();
5612     // Element types smaller than 32 bits are not legal, so use i32 elements.
5613     // The values are implicitly truncated so sext vs. zext doesn't matter.
5614     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5615   }
5616   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5617                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5618 }
5619
5620 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5621   unsigned Opcode = N->getOpcode();
5622   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5623     SDNode *N0 = N->getOperand(0).getNode();
5624     SDNode *N1 = N->getOperand(1).getNode();
5625     return N0->hasOneUse() && N1->hasOneUse() &&
5626       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5627   }
5628   return false;
5629 }
5630
5631 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5632   unsigned Opcode = N->getOpcode();
5633   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5634     SDNode *N0 = N->getOperand(0).getNode();
5635     SDNode *N1 = N->getOperand(1).getNode();
5636     return N0->hasOneUse() && N1->hasOneUse() &&
5637       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5638   }
5639   return false;
5640 }
5641
5642 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5643   // Multiplications are only custom-lowered for 128-bit vectors so that
5644   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5645   EVT VT = Op.getValueType();
5646   assert(VT.is128BitVector() && VT.isInteger() &&
5647          "unexpected type for custom-lowering ISD::MUL");
5648   SDNode *N0 = Op.getOperand(0).getNode();
5649   SDNode *N1 = Op.getOperand(1).getNode();
5650   unsigned NewOpc = 0;
5651   bool isMLA = false;
5652   bool isN0SExt = isSignExtended(N0, DAG);
5653   bool isN1SExt = isSignExtended(N1, DAG);
5654   if (isN0SExt && isN1SExt)
5655     NewOpc = ARMISD::VMULLs;
5656   else {
5657     bool isN0ZExt = isZeroExtended(N0, DAG);
5658     bool isN1ZExt = isZeroExtended(N1, DAG);
5659     if (isN0ZExt && isN1ZExt)
5660       NewOpc = ARMISD::VMULLu;
5661     else if (isN1SExt || isN1ZExt) {
5662       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5663       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5664       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5665         NewOpc = ARMISD::VMULLs;
5666         isMLA = true;
5667       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5668         NewOpc = ARMISD::VMULLu;
5669         isMLA = true;
5670       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5671         std::swap(N0, N1);
5672         NewOpc = ARMISD::VMULLu;
5673         isMLA = true;
5674       }
5675     }
5676
5677     if (!NewOpc) {
5678       if (VT == MVT::v2i64)
5679         // Fall through to expand this.  It is not legal.
5680         return SDValue();
5681       else
5682         // Other vector multiplications are legal.
5683         return Op;
5684     }
5685   }
5686
5687   // Legalize to a VMULL instruction.
5688   SDLoc DL(Op);
5689   SDValue Op0;
5690   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5691   if (!isMLA) {
5692     Op0 = SkipExtensionForVMULL(N0, DAG);
5693     assert(Op0.getValueType().is64BitVector() &&
5694            Op1.getValueType().is64BitVector() &&
5695            "unexpected types for extended operands to VMULL");
5696     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5697   }
5698
5699   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5700   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5701   //   vmull q0, d4, d6
5702   //   vmlal q0, d5, d6
5703   // is faster than
5704   //   vaddl q0, d4, d5
5705   //   vmovl q1, d6
5706   //   vmul  q0, q0, q1
5707   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5708   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5709   EVT Op1VT = Op1.getValueType();
5710   return DAG.getNode(N0->getOpcode(), DL, VT,
5711                      DAG.getNode(NewOpc, DL, VT,
5712                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5713                      DAG.getNode(NewOpc, DL, VT,
5714                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5715 }
5716
5717 static SDValue
5718 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5719   // Convert to float
5720   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5721   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5722   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5723   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5724   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5725   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5726   // Get reciprocal estimate.
5727   // float4 recip = vrecpeq_f32(yf);
5728   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5729                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5730   // Because char has a smaller range than uchar, we can actually get away
5731   // without any newton steps.  This requires that we use a weird bias
5732   // of 0xb000, however (again, this has been exhaustively tested).
5733   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5734   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5735   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5736   Y = DAG.getConstant(0xb000, MVT::i32);
5737   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5738   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5739   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5740   // Convert back to short.
5741   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5742   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5743   return X;
5744 }
5745
5746 static SDValue
5747 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5748   SDValue N2;
5749   // Convert to float.
5750   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5751   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5752   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5753   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5754   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5755   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5756
5757   // Use reciprocal estimate and one refinement step.
5758   // float4 recip = vrecpeq_f32(yf);
5759   // recip *= vrecpsq_f32(yf, recip);
5760   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5761                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5762   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5763                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5764                    N1, N2);
5765   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5766   // Because short has a smaller range than ushort, we can actually get away
5767   // with only a single newton step.  This requires that we use a weird bias
5768   // of 89, however (again, this has been exhaustively tested).
5769   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5770   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5771   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5772   N1 = DAG.getConstant(0x89, MVT::i32);
5773   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5774   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5775   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5776   // Convert back to integer and return.
5777   // return vmovn_s32(vcvt_s32_f32(result));
5778   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5779   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5780   return N0;
5781 }
5782
5783 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5784   EVT VT = Op.getValueType();
5785   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5786          "unexpected type for custom-lowering ISD::SDIV");
5787
5788   SDLoc dl(Op);
5789   SDValue N0 = Op.getOperand(0);
5790   SDValue N1 = Op.getOperand(1);
5791   SDValue N2, N3;
5792
5793   if (VT == MVT::v8i8) {
5794     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5795     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5796
5797     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5798                      DAG.getIntPtrConstant(4));
5799     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5800                      DAG.getIntPtrConstant(4));
5801     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5802                      DAG.getIntPtrConstant(0));
5803     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5804                      DAG.getIntPtrConstant(0));
5805
5806     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5807     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5808
5809     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5810     N0 = LowerCONCAT_VECTORS(N0, DAG);
5811
5812     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5813     return N0;
5814   }
5815   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5816 }
5817
5818 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5819   EVT VT = Op.getValueType();
5820   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5821          "unexpected type for custom-lowering ISD::UDIV");
5822
5823   SDLoc dl(Op);
5824   SDValue N0 = Op.getOperand(0);
5825   SDValue N1 = Op.getOperand(1);
5826   SDValue N2, N3;
5827
5828   if (VT == MVT::v8i8) {
5829     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5830     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5831
5832     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5833                      DAG.getIntPtrConstant(4));
5834     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5835                      DAG.getIntPtrConstant(4));
5836     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5837                      DAG.getIntPtrConstant(0));
5838     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5839                      DAG.getIntPtrConstant(0));
5840
5841     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5842     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5843
5844     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5845     N0 = LowerCONCAT_VECTORS(N0, DAG);
5846
5847     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5848                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5849                      N0);
5850     return N0;
5851   }
5852
5853   // v4i16 sdiv ... Convert to float.
5854   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5855   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5856   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5857   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5858   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5859   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5860
5861   // Use reciprocal estimate and two refinement steps.
5862   // float4 recip = vrecpeq_f32(yf);
5863   // recip *= vrecpsq_f32(yf, recip);
5864   // recip *= vrecpsq_f32(yf, recip);
5865   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5866                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5867   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5868                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5869                    BN1, N2);
5870   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5871   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5872                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5873                    BN1, N2);
5874   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5875   // Simply multiplying by the reciprocal estimate can leave us a few ulps
5876   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5877   // and that it will never cause us to return an answer too large).
5878   // float4 result = as_float4(as_int4(xf*recip) + 2);
5879   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5880   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5881   N1 = DAG.getConstant(2, MVT::i32);
5882   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5883   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5884   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5885   // Convert back to integer and return.
5886   // return vmovn_u32(vcvt_s32_f32(result));
5887   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5888   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5889   return N0;
5890 }
5891
5892 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5893   EVT VT = Op.getNode()->getValueType(0);
5894   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5895
5896   unsigned Opc;
5897   bool ExtraOp = false;
5898   switch (Op.getOpcode()) {
5899   default: llvm_unreachable("Invalid code");
5900   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5901   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5902   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5903   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5904   }
5905
5906   if (!ExtraOp)
5907     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5908                        Op.getOperand(1));
5909   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5910                      Op.getOperand(1), Op.getOperand(2));
5911 }
5912
5913 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5914   // Monotonic load/store is legal for all targets
5915   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5916     return Op;
5917
5918   // Aquire/Release load/store is not legal for targets without a
5919   // dmb or equivalent available.
5920   return SDValue();
5921 }
5922
5923 static void
5924 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5925                     SelectionDAG &DAG, unsigned NewOp) {
5926   SDLoc dl(Node);
5927   assert (Node->getValueType(0) == MVT::i64 &&
5928           "Only know how to expand i64 atomics");
5929
5930   SmallVector<SDValue, 6> Ops;
5931   Ops.push_back(Node->getOperand(0)); // Chain
5932   Ops.push_back(Node->getOperand(1)); // Ptr
5933   // Low part of Val1
5934   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5935                             Node->getOperand(2), DAG.getIntPtrConstant(0)));
5936   // High part of Val1
5937   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5938                             Node->getOperand(2), DAG.getIntPtrConstant(1)));
5939   if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5940     // High part of Val1
5941     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5942                               Node->getOperand(3), DAG.getIntPtrConstant(0)));
5943     // High part of Val2
5944     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5945                               Node->getOperand(3), DAG.getIntPtrConstant(1)));
5946   }
5947   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5948   SDValue Result =
5949     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5950                             cast<MemSDNode>(Node)->getMemOperand());
5951   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5952   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5953   Results.push_back(Result.getValue(2));
5954 }
5955
5956 static void ReplaceREADCYCLECOUNTER(SDNode *N,
5957                                     SmallVectorImpl<SDValue> &Results,
5958                                     SelectionDAG &DAG,
5959                                     const ARMSubtarget *Subtarget) {
5960   SDLoc DL(N);
5961   SDValue Cycles32, OutChain;
5962
5963   if (Subtarget->hasPerfMon()) {
5964     // Under Power Management extensions, the cycle-count is:
5965     //    mrc p15, #0, <Rt>, c9, c13, #0
5966     SDValue Ops[] = { N->getOperand(0), // Chain
5967                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
5968                       DAG.getConstant(15, MVT::i32),
5969                       DAG.getConstant(0, MVT::i32),
5970                       DAG.getConstant(9, MVT::i32),
5971                       DAG.getConstant(13, MVT::i32),
5972                       DAG.getConstant(0, MVT::i32)
5973     };
5974
5975     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
5976                            DAG.getVTList(MVT::i32, MVT::Other), &Ops[0],
5977                            array_lengthof(Ops));
5978     OutChain = Cycles32.getValue(1);
5979   } else {
5980     // Intrinsic is defined to return 0 on unsupported platforms. Technically
5981     // there are older ARM CPUs that have implementation-specific ways of
5982     // obtaining this information (FIXME!).
5983     Cycles32 = DAG.getConstant(0, MVT::i32);
5984     OutChain = DAG.getEntryNode();
5985   }
5986
5987
5988   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
5989                                  Cycles32, DAG.getConstant(0, MVT::i32));
5990   Results.push_back(Cycles64);
5991   Results.push_back(OutChain);
5992 }
5993
5994 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5995   switch (Op.getOpcode()) {
5996   default: llvm_unreachable("Don't know how to custom lower this!");
5997   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
5998   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
5999   case ISD::GlobalAddress:
6000     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
6001       LowerGlobalAddressELF(Op, DAG);
6002   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6003   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6004   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6005   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6006   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6007   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6008   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6009   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6010   case ISD::SINT_TO_FP:
6011   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6012   case ISD::FP_TO_SINT:
6013   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6014   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6015   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6016   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6017   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6018   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6019   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6020   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6021                                                                Subtarget);
6022   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6023   case ISD::SHL:
6024   case ISD::SRL:
6025   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6026   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6027   case ISD::SRL_PARTS:
6028   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6029   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6030   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6031   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6032   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6033   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6034   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6035   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6036   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6037   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6038   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6039   case ISD::MUL:           return LowerMUL(Op, DAG);
6040   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6041   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6042   case ISD::ADDC:
6043   case ISD::ADDE:
6044   case ISD::SUBC:
6045   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6046   case ISD::ATOMIC_LOAD:
6047   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6048   case ISD::SDIVREM:
6049   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6050   }
6051 }
6052
6053 /// ReplaceNodeResults - Replace the results of node with an illegal result
6054 /// type with new values built out of custom code.
6055 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6056                                            SmallVectorImpl<SDValue>&Results,
6057                                            SelectionDAG &DAG) const {
6058   SDValue Res;
6059   switch (N->getOpcode()) {
6060   default:
6061     llvm_unreachable("Don't know how to custom expand this!");
6062   case ISD::BITCAST:
6063     Res = ExpandBITCAST(N, DAG);
6064     break;
6065   case ISD::SIGN_EXTEND:
6066   case ISD::ZERO_EXTEND:
6067     Res = ExpandVectorExtension(N, DAG);
6068     break;
6069   case ISD::SRL:
6070   case ISD::SRA:
6071     Res = Expand64BitShift(N, DAG, Subtarget);
6072     break;
6073   case ISD::READCYCLECOUNTER:
6074     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6075     return;
6076   case ISD::ATOMIC_LOAD_ADD:
6077     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
6078     return;
6079   case ISD::ATOMIC_LOAD_AND:
6080     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
6081     return;
6082   case ISD::ATOMIC_LOAD_NAND:
6083     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
6084     return;
6085   case ISD::ATOMIC_LOAD_OR:
6086     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
6087     return;
6088   case ISD::ATOMIC_LOAD_SUB:
6089     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
6090     return;
6091   case ISD::ATOMIC_LOAD_XOR:
6092     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
6093     return;
6094   case ISD::ATOMIC_SWAP:
6095     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
6096     return;
6097   case ISD::ATOMIC_CMP_SWAP:
6098     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
6099     return;
6100   case ISD::ATOMIC_LOAD_MIN:
6101     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMIN64_DAG);
6102     return;
6103   case ISD::ATOMIC_LOAD_UMIN:
6104     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMIN64_DAG);
6105     return;
6106   case ISD::ATOMIC_LOAD_MAX:
6107     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMAX64_DAG);
6108     return;
6109   case ISD::ATOMIC_LOAD_UMAX:
6110     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMAX64_DAG);
6111     return;
6112   }
6113   if (Res.getNode())
6114     Results.push_back(Res);
6115 }
6116
6117 //===----------------------------------------------------------------------===//
6118 //                           ARM Scheduler Hooks
6119 //===----------------------------------------------------------------------===//
6120
6121 MachineBasicBlock *
6122 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
6123                                      MachineBasicBlock *BB,
6124                                      unsigned Size) const {
6125   unsigned dest    = MI->getOperand(0).getReg();
6126   unsigned ptr     = MI->getOperand(1).getReg();
6127   unsigned oldval  = MI->getOperand(2).getReg();
6128   unsigned newval  = MI->getOperand(3).getReg();
6129   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6130   DebugLoc dl = MI->getDebugLoc();
6131   bool isThumb2 = Subtarget->isThumb2();
6132
6133   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6134   unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
6135     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6136     (const TargetRegisterClass*)&ARM::GPRRegClass);
6137
6138   if (isThumb2) {
6139     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6140     MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
6141     MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
6142   }
6143
6144   unsigned ldrOpc, strOpc;
6145   switch (Size) {
6146   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
6147   case 1:
6148     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
6149     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
6150     break;
6151   case 2:
6152     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
6153     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
6154     break;
6155   case 4:
6156     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
6157     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
6158     break;
6159   }
6160
6161   MachineFunction *MF = BB->getParent();
6162   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6163   MachineFunction::iterator It = BB;
6164   ++It; // insert the new blocks after the current block
6165
6166   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6167   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6168   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6169   MF->insert(It, loop1MBB);
6170   MF->insert(It, loop2MBB);
6171   MF->insert(It, exitMBB);
6172
6173   // Transfer the remainder of BB and its successor edges to exitMBB.
6174   exitMBB->splice(exitMBB->begin(), BB,
6175                   llvm::next(MachineBasicBlock::iterator(MI)),
6176                   BB->end());
6177   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6178
6179   //  thisMBB:
6180   //   ...
6181   //   fallthrough --> loop1MBB
6182   BB->addSuccessor(loop1MBB);
6183
6184   // loop1MBB:
6185   //   ldrex dest, [ptr]
6186   //   cmp dest, oldval
6187   //   bne exitMBB
6188   BB = loop1MBB;
6189   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6190   if (ldrOpc == ARM::t2LDREX)
6191     MIB.addImm(0);
6192   AddDefaultPred(MIB);
6193   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6194                  .addReg(dest).addReg(oldval));
6195   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6196     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6197   BB->addSuccessor(loop2MBB);
6198   BB->addSuccessor(exitMBB);
6199
6200   // loop2MBB:
6201   //   strex scratch, newval, [ptr]
6202   //   cmp scratch, #0
6203   //   bne loop1MBB
6204   BB = loop2MBB;
6205   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
6206   if (strOpc == ARM::t2STREX)
6207     MIB.addImm(0);
6208   AddDefaultPred(MIB);
6209   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6210                  .addReg(scratch).addImm(0));
6211   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6212     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6213   BB->addSuccessor(loop1MBB);
6214   BB->addSuccessor(exitMBB);
6215
6216   //  exitMBB:
6217   //   ...
6218   BB = exitMBB;
6219
6220   MI->eraseFromParent();   // The instruction is gone now.
6221
6222   return BB;
6223 }
6224
6225 MachineBasicBlock *
6226 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6227                                     unsigned Size, unsigned BinOpcode) const {
6228   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6229   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6230
6231   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6232   MachineFunction *MF = BB->getParent();
6233   MachineFunction::iterator It = BB;
6234   ++It;
6235
6236   unsigned dest = MI->getOperand(0).getReg();
6237   unsigned ptr = MI->getOperand(1).getReg();
6238   unsigned incr = MI->getOperand(2).getReg();
6239   DebugLoc dl = MI->getDebugLoc();
6240   bool isThumb2 = Subtarget->isThumb2();
6241
6242   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6243   if (isThumb2) {
6244     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6245     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6246   }
6247
6248   unsigned ldrOpc, strOpc;
6249   switch (Size) {
6250   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
6251   case 1:
6252     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
6253     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
6254     break;
6255   case 2:
6256     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
6257     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
6258     break;
6259   case 4:
6260     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
6261     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
6262     break;
6263   }
6264
6265   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6266   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6267   MF->insert(It, loopMBB);
6268   MF->insert(It, exitMBB);
6269
6270   // Transfer the remainder of BB and its successor edges to exitMBB.
6271   exitMBB->splice(exitMBB->begin(), BB,
6272                   llvm::next(MachineBasicBlock::iterator(MI)),
6273                   BB->end());
6274   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6275
6276   const TargetRegisterClass *TRC = isThumb2 ?
6277     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6278     (const TargetRegisterClass*)&ARM::GPRRegClass;
6279   unsigned scratch = MRI.createVirtualRegister(TRC);
6280   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
6281
6282   //  thisMBB:
6283   //   ...
6284   //   fallthrough --> loopMBB
6285   BB->addSuccessor(loopMBB);
6286
6287   //  loopMBB:
6288   //   ldrex dest, ptr
6289   //   <binop> scratch2, dest, incr
6290   //   strex scratch, scratch2, ptr
6291   //   cmp scratch, #0
6292   //   bne- loopMBB
6293   //   fallthrough --> exitMBB
6294   BB = loopMBB;
6295   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6296   if (ldrOpc == ARM::t2LDREX)
6297     MIB.addImm(0);
6298   AddDefaultPred(MIB);
6299   if (BinOpcode) {
6300     // operand order needs to go the other way for NAND
6301     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
6302       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6303                      addReg(incr).addReg(dest)).addReg(0);
6304     else
6305       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6306                      addReg(dest).addReg(incr)).addReg(0);
6307   }
6308
6309   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6310   if (strOpc == ARM::t2STREX)
6311     MIB.addImm(0);
6312   AddDefaultPred(MIB);
6313   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6314                  .addReg(scratch).addImm(0));
6315   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6316     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6317
6318   BB->addSuccessor(loopMBB);
6319   BB->addSuccessor(exitMBB);
6320
6321   //  exitMBB:
6322   //   ...
6323   BB = exitMBB;
6324
6325   MI->eraseFromParent();   // The instruction is gone now.
6326
6327   return BB;
6328 }
6329
6330 MachineBasicBlock *
6331 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
6332                                           MachineBasicBlock *BB,
6333                                           unsigned Size,
6334                                           bool signExtend,
6335                                           ARMCC::CondCodes Cond) const {
6336   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6337
6338   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6339   MachineFunction *MF = BB->getParent();
6340   MachineFunction::iterator It = BB;
6341   ++It;
6342
6343   unsigned dest = MI->getOperand(0).getReg();
6344   unsigned ptr = MI->getOperand(1).getReg();
6345   unsigned incr = MI->getOperand(2).getReg();
6346   unsigned oldval = dest;
6347   DebugLoc dl = MI->getDebugLoc();
6348   bool isThumb2 = Subtarget->isThumb2();
6349
6350   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6351   if (isThumb2) {
6352     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6353     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6354   }
6355
6356   unsigned ldrOpc, strOpc, extendOpc;
6357   switch (Size) {
6358   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
6359   case 1:
6360     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
6361     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
6362     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
6363     break;
6364   case 2:
6365     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
6366     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
6367     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
6368     break;
6369   case 4:
6370     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
6371     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
6372     extendOpc = 0;
6373     break;
6374   }
6375
6376   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6377   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6378   MF->insert(It, loopMBB);
6379   MF->insert(It, exitMBB);
6380
6381   // Transfer the remainder of BB and its successor edges to exitMBB.
6382   exitMBB->splice(exitMBB->begin(), BB,
6383                   llvm::next(MachineBasicBlock::iterator(MI)),
6384                   BB->end());
6385   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6386
6387   const TargetRegisterClass *TRC = isThumb2 ?
6388     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6389     (const TargetRegisterClass*)&ARM::GPRRegClass;
6390   unsigned scratch = MRI.createVirtualRegister(TRC);
6391   unsigned scratch2 = MRI.createVirtualRegister(TRC);
6392
6393   //  thisMBB:
6394   //   ...
6395   //   fallthrough --> loopMBB
6396   BB->addSuccessor(loopMBB);
6397
6398   //  loopMBB:
6399   //   ldrex dest, ptr
6400   //   (sign extend dest, if required)
6401   //   cmp dest, incr
6402   //   cmov.cond scratch2, incr, dest
6403   //   strex scratch, scratch2, ptr
6404   //   cmp scratch, #0
6405   //   bne- loopMBB
6406   //   fallthrough --> exitMBB
6407   BB = loopMBB;
6408   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6409   if (ldrOpc == ARM::t2LDREX)
6410     MIB.addImm(0);
6411   AddDefaultPred(MIB);
6412
6413   // Sign extend the value, if necessary.
6414   if (signExtend && extendOpc) {
6415     oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
6416     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
6417                      .addReg(dest)
6418                      .addImm(0));
6419   }
6420
6421   // Build compare and cmov instructions.
6422   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6423                  .addReg(oldval).addReg(incr));
6424   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
6425          .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
6426
6427   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6428   if (strOpc == ARM::t2STREX)
6429     MIB.addImm(0);
6430   AddDefaultPred(MIB);
6431   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6432                  .addReg(scratch).addImm(0));
6433   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6434     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6435
6436   BB->addSuccessor(loopMBB);
6437   BB->addSuccessor(exitMBB);
6438
6439   //  exitMBB:
6440   //   ...
6441   BB = exitMBB;
6442
6443   MI->eraseFromParent();   // The instruction is gone now.
6444
6445   return BB;
6446 }
6447
6448 MachineBasicBlock *
6449 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
6450                                       unsigned Op1, unsigned Op2,
6451                                       bool NeedsCarry, bool IsCmpxchg,
6452                                       bool IsMinMax, ARMCC::CondCodes CC) const {
6453   // This also handles ATOMIC_SWAP, indicated by Op1==0.
6454   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6455
6456   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6457   MachineFunction *MF = BB->getParent();
6458   MachineFunction::iterator It = BB;
6459   ++It;
6460
6461   unsigned destlo = MI->getOperand(0).getReg();
6462   unsigned desthi = MI->getOperand(1).getReg();
6463   unsigned ptr = MI->getOperand(2).getReg();
6464   unsigned vallo = MI->getOperand(3).getReg();
6465   unsigned valhi = MI->getOperand(4).getReg();
6466   DebugLoc dl = MI->getDebugLoc();
6467   bool isThumb2 = Subtarget->isThumb2();
6468
6469   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6470   if (isThumb2) {
6471     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6472     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6473     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6474     MRI.constrainRegClass(vallo, &ARM::rGPRRegClass);
6475     MRI.constrainRegClass(valhi, &ARM::rGPRRegClass);
6476   }
6477
6478   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6479   MachineBasicBlock *contBB = 0, *cont2BB = 0;
6480   if (IsCmpxchg || IsMinMax)
6481     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
6482   if (IsCmpxchg)
6483     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
6484   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6485
6486   MF->insert(It, loopMBB);
6487   if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6488   if (IsCmpxchg) MF->insert(It, cont2BB);
6489   MF->insert(It, exitMBB);
6490
6491   // Transfer the remainder of BB and its successor edges to exitMBB.
6492   exitMBB->splice(exitMBB->begin(), BB,
6493                   llvm::next(MachineBasicBlock::iterator(MI)),
6494                   BB->end());
6495   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6496
6497   const TargetRegisterClass *TRC = isThumb2 ?
6498     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6499     (const TargetRegisterClass*)&ARM::GPRRegClass;
6500   unsigned storesuccess = MRI.createVirtualRegister(TRC);
6501
6502   //  thisMBB:
6503   //   ...
6504   //   fallthrough --> loopMBB
6505   BB->addSuccessor(loopMBB);
6506
6507   //  loopMBB:
6508   //   ldrexd r2, r3, ptr
6509   //   <binopa> r0, r2, incr
6510   //   <binopb> r1, r3, incr
6511   //   strexd storesuccess, r0, r1, ptr
6512   //   cmp storesuccess, #0
6513   //   bne- loopMBB
6514   //   fallthrough --> exitMBB
6515   BB = loopMBB;
6516
6517   // Load
6518   if (isThumb2) {
6519     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2LDREXD))
6520                    .addReg(destlo, RegState::Define)
6521                    .addReg(desthi, RegState::Define)
6522                    .addReg(ptr));
6523   } else {
6524     unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6525     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDREXD))
6526                    .addReg(GPRPair0, RegState::Define).addReg(ptr));
6527     // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
6528     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6529       .addReg(GPRPair0, 0, ARM::gsub_0);
6530     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6531       .addReg(GPRPair0, 0, ARM::gsub_1);
6532   }
6533
6534   unsigned StoreLo, StoreHi;
6535   if (IsCmpxchg) {
6536     // Add early exit
6537     for (unsigned i = 0; i < 2; i++) {
6538       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6539                                                          ARM::CMPrr))
6540                      .addReg(i == 0 ? destlo : desthi)
6541                      .addReg(i == 0 ? vallo : valhi));
6542       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6543         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6544       BB->addSuccessor(exitMBB);
6545       BB->addSuccessor(i == 0 ? contBB : cont2BB);
6546       BB = (i == 0 ? contBB : cont2BB);
6547     }
6548
6549     // Copy to physregs for strexd
6550     StoreLo = MI->getOperand(5).getReg();
6551     StoreHi = MI->getOperand(6).getReg();
6552   } else if (Op1) {
6553     // Perform binary operation
6554     unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6555     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6556                    .addReg(destlo).addReg(vallo))
6557         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6558     unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6559     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6560                    .addReg(desthi).addReg(valhi))
6561         .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6562
6563     StoreLo = tmpRegLo;
6564     StoreHi = tmpRegHi;
6565   } else {
6566     // Copy to physregs for strexd
6567     StoreLo = vallo;
6568     StoreHi = valhi;
6569   }
6570   if (IsMinMax) {
6571     // Compare and branch to exit block.
6572     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6573       .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6574     BB->addSuccessor(exitMBB);
6575     BB->addSuccessor(contBB);
6576     BB = contBB;
6577     StoreLo = vallo;
6578     StoreHi = valhi;
6579   }
6580
6581   // Store
6582   if (isThumb2) {
6583     MRI.constrainRegClass(StoreLo, &ARM::rGPRRegClass);
6584     MRI.constrainRegClass(StoreHi, &ARM::rGPRRegClass);
6585     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2STREXD), storesuccess)
6586                    .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6587   } else {
6588     // Marshal a pair...
6589     unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6590     unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6591     unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6592     BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6593     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6594       .addReg(UndefPair)
6595       .addReg(StoreLo)
6596       .addImm(ARM::gsub_0);
6597     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6598       .addReg(r1)
6599       .addReg(StoreHi)
6600       .addImm(ARM::gsub_1);
6601
6602     // ...and store it
6603     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::STREXD), storesuccess)
6604                    .addReg(StorePair).addReg(ptr));
6605   }
6606   // Cmp+jump
6607   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6608                  .addReg(storesuccess).addImm(0));
6609   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6610     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6611
6612   BB->addSuccessor(loopMBB);
6613   BB->addSuccessor(exitMBB);
6614
6615   //  exitMBB:
6616   //   ...
6617   BB = exitMBB;
6618
6619   MI->eraseFromParent();   // The instruction is gone now.
6620
6621   return BB;
6622 }
6623
6624 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6625 /// registers the function context.
6626 void ARMTargetLowering::
6627 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6628                        MachineBasicBlock *DispatchBB, int FI) const {
6629   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6630   DebugLoc dl = MI->getDebugLoc();
6631   MachineFunction *MF = MBB->getParent();
6632   MachineRegisterInfo *MRI = &MF->getRegInfo();
6633   MachineConstantPool *MCP = MF->getConstantPool();
6634   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6635   const Function *F = MF->getFunction();
6636
6637   bool isThumb = Subtarget->isThumb();
6638   bool isThumb2 = Subtarget->isThumb2();
6639
6640   unsigned PCLabelId = AFI->createPICLabelUId();
6641   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6642   ARMConstantPoolValue *CPV =
6643     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6644   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6645
6646   const TargetRegisterClass *TRC = isThumb ?
6647     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6648     (const TargetRegisterClass*)&ARM::GPRRegClass;
6649
6650   // Grab constant pool and fixed stack memory operands.
6651   MachineMemOperand *CPMMO =
6652     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6653                              MachineMemOperand::MOLoad, 4, 4);
6654
6655   MachineMemOperand *FIMMOSt =
6656     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6657                              MachineMemOperand::MOStore, 4, 4);
6658
6659   // Load the address of the dispatch MBB into the jump buffer.
6660   if (isThumb2) {
6661     // Incoming value: jbuf
6662     //   ldr.n  r5, LCPI1_1
6663     //   orr    r5, r5, #1
6664     //   add    r5, pc
6665     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6666     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6667     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6668                    .addConstantPoolIndex(CPI)
6669                    .addMemOperand(CPMMO));
6670     // Set the low bit because of thumb mode.
6671     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6672     AddDefaultCC(
6673       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6674                      .addReg(NewVReg1, RegState::Kill)
6675                      .addImm(0x01)));
6676     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6677     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6678       .addReg(NewVReg2, RegState::Kill)
6679       .addImm(PCLabelId);
6680     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6681                    .addReg(NewVReg3, RegState::Kill)
6682                    .addFrameIndex(FI)
6683                    .addImm(36)  // &jbuf[1] :: pc
6684                    .addMemOperand(FIMMOSt));
6685   } else if (isThumb) {
6686     // Incoming value: jbuf
6687     //   ldr.n  r1, LCPI1_4
6688     //   add    r1, pc
6689     //   mov    r2, #1
6690     //   orrs   r1, r2
6691     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6692     //   str    r1, [r2]
6693     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6694     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6695                    .addConstantPoolIndex(CPI)
6696                    .addMemOperand(CPMMO));
6697     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6698     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6699       .addReg(NewVReg1, RegState::Kill)
6700       .addImm(PCLabelId);
6701     // Set the low bit because of thumb mode.
6702     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6703     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6704                    .addReg(ARM::CPSR, RegState::Define)
6705                    .addImm(1));
6706     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6707     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6708                    .addReg(ARM::CPSR, RegState::Define)
6709                    .addReg(NewVReg2, RegState::Kill)
6710                    .addReg(NewVReg3, RegState::Kill));
6711     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6712     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6713                    .addFrameIndex(FI)
6714                    .addImm(36)); // &jbuf[1] :: pc
6715     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6716                    .addReg(NewVReg4, RegState::Kill)
6717                    .addReg(NewVReg5, RegState::Kill)
6718                    .addImm(0)
6719                    .addMemOperand(FIMMOSt));
6720   } else {
6721     // Incoming value: jbuf
6722     //   ldr  r1, LCPI1_1
6723     //   add  r1, pc, r1
6724     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6725     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6726     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6727                    .addConstantPoolIndex(CPI)
6728                    .addImm(0)
6729                    .addMemOperand(CPMMO));
6730     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6731     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6732                    .addReg(NewVReg1, RegState::Kill)
6733                    .addImm(PCLabelId));
6734     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6735                    .addReg(NewVReg2, RegState::Kill)
6736                    .addFrameIndex(FI)
6737                    .addImm(36)  // &jbuf[1] :: pc
6738                    .addMemOperand(FIMMOSt));
6739   }
6740 }
6741
6742 MachineBasicBlock *ARMTargetLowering::
6743 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6744   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6745   DebugLoc dl = MI->getDebugLoc();
6746   MachineFunction *MF = MBB->getParent();
6747   MachineRegisterInfo *MRI = &MF->getRegInfo();
6748   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6749   MachineFrameInfo *MFI = MF->getFrameInfo();
6750   int FI = MFI->getFunctionContextIndex();
6751
6752   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6753     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6754     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6755
6756   // Get a mapping of the call site numbers to all of the landing pads they're
6757   // associated with.
6758   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6759   unsigned MaxCSNum = 0;
6760   MachineModuleInfo &MMI = MF->getMMI();
6761   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6762        ++BB) {
6763     if (!BB->isLandingPad()) continue;
6764
6765     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6766     // pad.
6767     for (MachineBasicBlock::iterator
6768            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6769       if (!II->isEHLabel()) continue;
6770
6771       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6772       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6773
6774       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6775       for (SmallVectorImpl<unsigned>::iterator
6776              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6777            CSI != CSE; ++CSI) {
6778         CallSiteNumToLPad[*CSI].push_back(BB);
6779         MaxCSNum = std::max(MaxCSNum, *CSI);
6780       }
6781       break;
6782     }
6783   }
6784
6785   // Get an ordered list of the machine basic blocks for the jump table.
6786   std::vector<MachineBasicBlock*> LPadList;
6787   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6788   LPadList.reserve(CallSiteNumToLPad.size());
6789   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6790     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6791     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6792            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6793       LPadList.push_back(*II);
6794       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6795     }
6796   }
6797
6798   assert(!LPadList.empty() &&
6799          "No landing pad destinations for the dispatch jump table!");
6800
6801   // Create the jump table and associated information.
6802   MachineJumpTableInfo *JTI =
6803     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6804   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6805   unsigned UId = AFI->createJumpTableUId();
6806   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6807
6808   // Create the MBBs for the dispatch code.
6809
6810   // Shove the dispatch's address into the return slot in the function context.
6811   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6812   DispatchBB->setIsLandingPad();
6813
6814   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6815   unsigned trap_opcode;
6816   if (Subtarget->isThumb())
6817     trap_opcode = ARM::tTRAP;
6818   else
6819     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6820
6821   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6822   DispatchBB->addSuccessor(TrapBB);
6823
6824   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6825   DispatchBB->addSuccessor(DispContBB);
6826
6827   // Insert and MBBs.
6828   MF->insert(MF->end(), DispatchBB);
6829   MF->insert(MF->end(), DispContBB);
6830   MF->insert(MF->end(), TrapBB);
6831
6832   // Insert code into the entry block that creates and registers the function
6833   // context.
6834   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6835
6836   MachineMemOperand *FIMMOLd =
6837     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6838                              MachineMemOperand::MOLoad |
6839                              MachineMemOperand::MOVolatile, 4, 4);
6840
6841   MachineInstrBuilder MIB;
6842   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6843
6844   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6845   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6846
6847   // Add a register mask with no preserved registers.  This results in all
6848   // registers being marked as clobbered.
6849   MIB.addRegMask(RI.getNoPreservedMask());
6850
6851   unsigned NumLPads = LPadList.size();
6852   if (Subtarget->isThumb2()) {
6853     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6854     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6855                    .addFrameIndex(FI)
6856                    .addImm(4)
6857                    .addMemOperand(FIMMOLd));
6858
6859     if (NumLPads < 256) {
6860       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6861                      .addReg(NewVReg1)
6862                      .addImm(LPadList.size()));
6863     } else {
6864       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6865       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6866                      .addImm(NumLPads & 0xFFFF));
6867
6868       unsigned VReg2 = VReg1;
6869       if ((NumLPads & 0xFFFF0000) != 0) {
6870         VReg2 = MRI->createVirtualRegister(TRC);
6871         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6872                        .addReg(VReg1)
6873                        .addImm(NumLPads >> 16));
6874       }
6875
6876       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6877                      .addReg(NewVReg1)
6878                      .addReg(VReg2));
6879     }
6880
6881     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6882       .addMBB(TrapBB)
6883       .addImm(ARMCC::HI)
6884       .addReg(ARM::CPSR);
6885
6886     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6887     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6888                    .addJumpTableIndex(MJTI)
6889                    .addImm(UId));
6890
6891     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6892     AddDefaultCC(
6893       AddDefaultPred(
6894         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6895         .addReg(NewVReg3, RegState::Kill)
6896         .addReg(NewVReg1)
6897         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6898
6899     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6900       .addReg(NewVReg4, RegState::Kill)
6901       .addReg(NewVReg1)
6902       .addJumpTableIndex(MJTI)
6903       .addImm(UId);
6904   } else if (Subtarget->isThumb()) {
6905     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6906     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6907                    .addFrameIndex(FI)
6908                    .addImm(1)
6909                    .addMemOperand(FIMMOLd));
6910
6911     if (NumLPads < 256) {
6912       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6913                      .addReg(NewVReg1)
6914                      .addImm(NumLPads));
6915     } else {
6916       MachineConstantPool *ConstantPool = MF->getConstantPool();
6917       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6918       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6919
6920       // MachineConstantPool wants an explicit alignment.
6921       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6922       if (Align == 0)
6923         Align = getDataLayout()->getTypeAllocSize(C->getType());
6924       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6925
6926       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6927       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6928                      .addReg(VReg1, RegState::Define)
6929                      .addConstantPoolIndex(Idx));
6930       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6931                      .addReg(NewVReg1)
6932                      .addReg(VReg1));
6933     }
6934
6935     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6936       .addMBB(TrapBB)
6937       .addImm(ARMCC::HI)
6938       .addReg(ARM::CPSR);
6939
6940     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6941     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6942                    .addReg(ARM::CPSR, RegState::Define)
6943                    .addReg(NewVReg1)
6944                    .addImm(2));
6945
6946     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6947     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6948                    .addJumpTableIndex(MJTI)
6949                    .addImm(UId));
6950
6951     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6952     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6953                    .addReg(ARM::CPSR, RegState::Define)
6954                    .addReg(NewVReg2, RegState::Kill)
6955                    .addReg(NewVReg3));
6956
6957     MachineMemOperand *JTMMOLd =
6958       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6959                                MachineMemOperand::MOLoad, 4, 4);
6960
6961     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6962     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6963                    .addReg(NewVReg4, RegState::Kill)
6964                    .addImm(0)
6965                    .addMemOperand(JTMMOLd));
6966
6967     unsigned NewVReg6 = NewVReg5;
6968     if (RelocM == Reloc::PIC_) {
6969       NewVReg6 = MRI->createVirtualRegister(TRC);
6970       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6971                      .addReg(ARM::CPSR, RegState::Define)
6972                      .addReg(NewVReg5, RegState::Kill)
6973                      .addReg(NewVReg3));
6974     }
6975
6976     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6977       .addReg(NewVReg6, RegState::Kill)
6978       .addJumpTableIndex(MJTI)
6979       .addImm(UId);
6980   } else {
6981     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6982     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6983                    .addFrameIndex(FI)
6984                    .addImm(4)
6985                    .addMemOperand(FIMMOLd));
6986
6987     if (NumLPads < 256) {
6988       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6989                      .addReg(NewVReg1)
6990                      .addImm(NumLPads));
6991     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6992       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6993       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6994                      .addImm(NumLPads & 0xFFFF));
6995
6996       unsigned VReg2 = VReg1;
6997       if ((NumLPads & 0xFFFF0000) != 0) {
6998         VReg2 = MRI->createVirtualRegister(TRC);
6999         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7000                        .addReg(VReg1)
7001                        .addImm(NumLPads >> 16));
7002       }
7003
7004       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7005                      .addReg(NewVReg1)
7006                      .addReg(VReg2));
7007     } else {
7008       MachineConstantPool *ConstantPool = MF->getConstantPool();
7009       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7010       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7011
7012       // MachineConstantPool wants an explicit alignment.
7013       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7014       if (Align == 0)
7015         Align = getDataLayout()->getTypeAllocSize(C->getType());
7016       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7017
7018       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7019       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7020                      .addReg(VReg1, RegState::Define)
7021                      .addConstantPoolIndex(Idx)
7022                      .addImm(0));
7023       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7024                      .addReg(NewVReg1)
7025                      .addReg(VReg1, RegState::Kill));
7026     }
7027
7028     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7029       .addMBB(TrapBB)
7030       .addImm(ARMCC::HI)
7031       .addReg(ARM::CPSR);
7032
7033     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7034     AddDefaultCC(
7035       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7036                      .addReg(NewVReg1)
7037                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7038     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7039     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7040                    .addJumpTableIndex(MJTI)
7041                    .addImm(UId));
7042
7043     MachineMemOperand *JTMMOLd =
7044       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7045                                MachineMemOperand::MOLoad, 4, 4);
7046     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7047     AddDefaultPred(
7048       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7049       .addReg(NewVReg3, RegState::Kill)
7050       .addReg(NewVReg4)
7051       .addImm(0)
7052       .addMemOperand(JTMMOLd));
7053
7054     if (RelocM == Reloc::PIC_) {
7055       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7056         .addReg(NewVReg5, RegState::Kill)
7057         .addReg(NewVReg4)
7058         .addJumpTableIndex(MJTI)
7059         .addImm(UId);
7060     } else {
7061       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7062         .addReg(NewVReg5, RegState::Kill)
7063         .addJumpTableIndex(MJTI)
7064         .addImm(UId);
7065     }
7066   }
7067
7068   // Add the jump table entries as successors to the MBB.
7069   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7070   for (std::vector<MachineBasicBlock*>::iterator
7071          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7072     MachineBasicBlock *CurMBB = *I;
7073     if (SeenMBBs.insert(CurMBB))
7074       DispContBB->addSuccessor(CurMBB);
7075   }
7076
7077   // N.B. the order the invoke BBs are processed in doesn't matter here.
7078   const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
7079   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7080   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
7081          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
7082     MachineBasicBlock *BB = *I;
7083
7084     // Remove the landing pad successor from the invoke block and replace it
7085     // with the new dispatch block.
7086     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7087                                                   BB->succ_end());
7088     while (!Successors.empty()) {
7089       MachineBasicBlock *SMBB = Successors.pop_back_val();
7090       if (SMBB->isLandingPad()) {
7091         BB->removeSuccessor(SMBB);
7092         MBBLPads.push_back(SMBB);
7093       }
7094     }
7095
7096     BB->addSuccessor(DispatchBB);
7097
7098     // Find the invoke call and mark all of the callee-saved registers as
7099     // 'implicit defined' so that they're spilled. This prevents code from
7100     // moving instructions to before the EH block, where they will never be
7101     // executed.
7102     for (MachineBasicBlock::reverse_iterator
7103            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7104       if (!II->isCall()) continue;
7105
7106       DenseMap<unsigned, bool> DefRegs;
7107       for (MachineInstr::mop_iterator
7108              OI = II->operands_begin(), OE = II->operands_end();
7109            OI != OE; ++OI) {
7110         if (!OI->isReg()) continue;
7111         DefRegs[OI->getReg()] = true;
7112       }
7113
7114       MachineInstrBuilder MIB(*MF, &*II);
7115
7116       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7117         unsigned Reg = SavedRegs[i];
7118         if (Subtarget->isThumb2() &&
7119             !ARM::tGPRRegClass.contains(Reg) &&
7120             !ARM::hGPRRegClass.contains(Reg))
7121           continue;
7122         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7123           continue;
7124         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7125           continue;
7126         if (!DefRegs[Reg])
7127           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7128       }
7129
7130       break;
7131     }
7132   }
7133
7134   // Mark all former landing pads as non-landing pads. The dispatch is the only
7135   // landing pad now.
7136   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7137          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7138     (*I)->setIsLandingPad(false);
7139
7140   // The instruction is gone now.
7141   MI->eraseFromParent();
7142
7143   return MBB;
7144 }
7145
7146 static
7147 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7148   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7149        E = MBB->succ_end(); I != E; ++I)
7150     if (*I != Succ)
7151       return *I;
7152   llvm_unreachable("Expecting a BB with two successors!");
7153 }
7154
7155 MachineBasicBlock *ARMTargetLowering::
7156 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
7157   // This pseudo instruction has 3 operands: dst, src, size
7158   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7159   // Otherwise, we will generate unrolled scalar copies.
7160   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7161   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7162   MachineFunction::iterator It = BB;
7163   ++It;
7164
7165   unsigned dest = MI->getOperand(0).getReg();
7166   unsigned src = MI->getOperand(1).getReg();
7167   unsigned SizeVal = MI->getOperand(2).getImm();
7168   unsigned Align = MI->getOperand(3).getImm();
7169   DebugLoc dl = MI->getDebugLoc();
7170
7171   bool isThumb2 = Subtarget->isThumb2();
7172   MachineFunction *MF = BB->getParent();
7173   MachineRegisterInfo &MRI = MF->getRegInfo();
7174   unsigned ldrOpc, strOpc, UnitSize = 0;
7175
7176   const TargetRegisterClass *TRC = isThumb2 ?
7177     (const TargetRegisterClass*)&ARM::tGPRRegClass :
7178     (const TargetRegisterClass*)&ARM::GPRRegClass;
7179   const TargetRegisterClass *TRC_Vec = 0;
7180
7181   if (Align & 1) {
7182     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
7183     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
7184     UnitSize = 1;
7185   } else if (Align & 2) {
7186     ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
7187     strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
7188     UnitSize = 2;
7189   } else {
7190     // Check whether we can use NEON instructions.
7191     if (!MF->getFunction()->getAttributes().
7192           hasAttribute(AttributeSet::FunctionIndex,
7193                        Attribute::NoImplicitFloat) &&
7194         Subtarget->hasNEON()) {
7195       if ((Align % 16 == 0) && SizeVal >= 16) {
7196         ldrOpc = ARM::VLD1q32wb_fixed;
7197         strOpc = ARM::VST1q32wb_fixed;
7198         UnitSize = 16;
7199         TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
7200       }
7201       else if ((Align % 8 == 0) && SizeVal >= 8) {
7202         ldrOpc = ARM::VLD1d32wb_fixed;
7203         strOpc = ARM::VST1d32wb_fixed;
7204         UnitSize = 8;
7205         TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
7206       }
7207     }
7208     // Can't use NEON instructions.
7209     if (UnitSize == 0) {
7210       ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
7211       strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
7212       UnitSize = 4;
7213     }
7214   }
7215
7216   unsigned BytesLeft = SizeVal % UnitSize;
7217   unsigned LoopSize = SizeVal - BytesLeft;
7218
7219   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7220     // Use LDR and STR to copy.
7221     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7222     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7223     unsigned srcIn = src;
7224     unsigned destIn = dest;
7225     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7226       unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
7227       unsigned srcOut = MRI.createVirtualRegister(TRC);
7228       unsigned destOut = MRI.createVirtualRegister(TRC);
7229       if (UnitSize >= 8) {
7230         AddDefaultPred(BuildMI(*BB, MI, dl,
7231           TII->get(ldrOpc), scratch)
7232           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
7233
7234         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7235           .addReg(destIn).addImm(0).addReg(scratch));
7236       } else if (isThumb2) {
7237         AddDefaultPred(BuildMI(*BB, MI, dl,
7238           TII->get(ldrOpc), scratch)
7239           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
7240
7241         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7242           .addReg(scratch).addReg(destIn)
7243           .addImm(UnitSize));
7244       } else {
7245         AddDefaultPred(BuildMI(*BB, MI, dl,
7246           TII->get(ldrOpc), scratch)
7247           .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
7248           .addImm(UnitSize));
7249
7250         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7251           .addReg(scratch).addReg(destIn)
7252           .addReg(0).addImm(UnitSize));
7253       }
7254       srcIn = srcOut;
7255       destIn = destOut;
7256     }
7257
7258     // Handle the leftover bytes with LDRB and STRB.
7259     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7260     // [destOut] = STRB_POST(scratch, destIn, 1)
7261     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
7262     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
7263     for (unsigned i = 0; i < BytesLeft; i++) {
7264       unsigned scratch = MRI.createVirtualRegister(TRC);
7265       unsigned srcOut = MRI.createVirtualRegister(TRC);
7266       unsigned destOut = MRI.createVirtualRegister(TRC);
7267       if (isThumb2) {
7268         AddDefaultPred(BuildMI(*BB, MI, dl,
7269           TII->get(ldrOpc),scratch)
7270           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
7271
7272         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7273           .addReg(scratch).addReg(destIn)
7274           .addReg(0).addImm(1));
7275       } else {
7276         AddDefaultPred(BuildMI(*BB, MI, dl,
7277           TII->get(ldrOpc),scratch)
7278           .addReg(srcOut, RegState::Define).addReg(srcIn)
7279           .addReg(0).addImm(1));
7280
7281         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7282           .addReg(scratch).addReg(destIn)
7283           .addReg(0).addImm(1));
7284       }
7285       srcIn = srcOut;
7286       destIn = destOut;
7287     }
7288     MI->eraseFromParent();   // The instruction is gone now.
7289     return BB;
7290   }
7291
7292   // Expand the pseudo op to a loop.
7293   // thisMBB:
7294   //   ...
7295   //   movw varEnd, # --> with thumb2
7296   //   movt varEnd, #
7297   //   ldrcp varEnd, idx --> without thumb2
7298   //   fallthrough --> loopMBB
7299   // loopMBB:
7300   //   PHI varPhi, varEnd, varLoop
7301   //   PHI srcPhi, src, srcLoop
7302   //   PHI destPhi, dst, destLoop
7303   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7304   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7305   //   subs varLoop, varPhi, #UnitSize
7306   //   bne loopMBB
7307   //   fallthrough --> exitMBB
7308   // exitMBB:
7309   //   epilogue to handle left-over bytes
7310   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7311   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7312   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7313   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7314   MF->insert(It, loopMBB);
7315   MF->insert(It, exitMBB);
7316
7317   // Transfer the remainder of BB and its successor edges to exitMBB.
7318   exitMBB->splice(exitMBB->begin(), BB,
7319                   llvm::next(MachineBasicBlock::iterator(MI)),
7320                   BB->end());
7321   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7322
7323   // Load an immediate to varEnd.
7324   unsigned varEnd = MRI.createVirtualRegister(TRC);
7325   if (isThumb2) {
7326     unsigned VReg1 = varEnd;
7327     if ((LoopSize & 0xFFFF0000) != 0)
7328       VReg1 = MRI.createVirtualRegister(TRC);
7329     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
7330                    .addImm(LoopSize & 0xFFFF));
7331
7332     if ((LoopSize & 0xFFFF0000) != 0)
7333       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7334                      .addReg(VReg1)
7335                      .addImm(LoopSize >> 16));
7336   } else {
7337     MachineConstantPool *ConstantPool = MF->getConstantPool();
7338     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7339     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7340
7341     // MachineConstantPool wants an explicit alignment.
7342     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7343     if (Align == 0)
7344       Align = getDataLayout()->getTypeAllocSize(C->getType());
7345     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7346
7347     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
7348                    .addReg(varEnd, RegState::Define)
7349                    .addConstantPoolIndex(Idx)
7350                    .addImm(0));
7351   }
7352   BB->addSuccessor(loopMBB);
7353
7354   // Generate the loop body:
7355   //   varPhi = PHI(varLoop, varEnd)
7356   //   srcPhi = PHI(srcLoop, src)
7357   //   destPhi = PHI(destLoop, dst)
7358   MachineBasicBlock *entryBB = BB;
7359   BB = loopMBB;
7360   unsigned varLoop = MRI.createVirtualRegister(TRC);
7361   unsigned varPhi = MRI.createVirtualRegister(TRC);
7362   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7363   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7364   unsigned destLoop = MRI.createVirtualRegister(TRC);
7365   unsigned destPhi = MRI.createVirtualRegister(TRC);
7366
7367   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7368     .addReg(varLoop).addMBB(loopMBB)
7369     .addReg(varEnd).addMBB(entryBB);
7370   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7371     .addReg(srcLoop).addMBB(loopMBB)
7372     .addReg(src).addMBB(entryBB);
7373   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7374     .addReg(destLoop).addMBB(loopMBB)
7375     .addReg(dest).addMBB(entryBB);
7376
7377   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7378   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7379   unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
7380   if (UnitSize >= 8) {
7381     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7382       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
7383
7384     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7385       .addReg(destPhi).addImm(0).addReg(scratch));
7386   } else if (isThumb2) {
7387     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7388       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
7389
7390     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7391       .addReg(scratch).addReg(destPhi)
7392       .addImm(UnitSize));
7393   } else {
7394     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7395       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
7396       .addImm(UnitSize));
7397
7398     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7399       .addReg(scratch).addReg(destPhi)
7400       .addReg(0).addImm(UnitSize));
7401   }
7402
7403   // Decrement loop variable by UnitSize.
7404   MachineInstrBuilder MIB = BuildMI(BB, dl,
7405     TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7406   AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7407   MIB->getOperand(5).setReg(ARM::CPSR);
7408   MIB->getOperand(5).setIsDef(true);
7409
7410   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7411     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7412
7413   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7414   BB->addSuccessor(loopMBB);
7415   BB->addSuccessor(exitMBB);
7416
7417   // Add epilogue to handle BytesLeft.
7418   BB = exitMBB;
7419   MachineInstr *StartOfExit = exitMBB->begin();
7420   ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
7421   strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
7422
7423   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7424   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7425   unsigned srcIn = srcLoop;
7426   unsigned destIn = destLoop;
7427   for (unsigned i = 0; i < BytesLeft; i++) {
7428     unsigned scratch = MRI.createVirtualRegister(TRC);
7429     unsigned srcOut = MRI.createVirtualRegister(TRC);
7430     unsigned destOut = MRI.createVirtualRegister(TRC);
7431     if (isThumb2) {
7432       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
7433         TII->get(ldrOpc),scratch)
7434         .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
7435
7436       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
7437         .addReg(scratch).addReg(destIn)
7438         .addImm(1));
7439     } else {
7440       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
7441         TII->get(ldrOpc),scratch)
7442         .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
7443
7444       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
7445         .addReg(scratch).addReg(destIn)
7446         .addReg(0).addImm(1));
7447     }
7448     srcIn = srcOut;
7449     destIn = destOut;
7450   }
7451
7452   MI->eraseFromParent();   // The instruction is gone now.
7453   return BB;
7454 }
7455
7456 MachineBasicBlock *
7457 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7458                                                MachineBasicBlock *BB) const {
7459   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7460   DebugLoc dl = MI->getDebugLoc();
7461   bool isThumb2 = Subtarget->isThumb2();
7462   switch (MI->getOpcode()) {
7463   default: {
7464     MI->dump();
7465     llvm_unreachable("Unexpected instr type to insert");
7466   }
7467   // The Thumb2 pre-indexed stores have the same MI operands, they just
7468   // define them differently in the .td files from the isel patterns, so
7469   // they need pseudos.
7470   case ARM::t2STR_preidx:
7471     MI->setDesc(TII->get(ARM::t2STR_PRE));
7472     return BB;
7473   case ARM::t2STRB_preidx:
7474     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7475     return BB;
7476   case ARM::t2STRH_preidx:
7477     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7478     return BB;
7479
7480   case ARM::STRi_preidx:
7481   case ARM::STRBi_preidx: {
7482     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7483       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7484     // Decode the offset.
7485     unsigned Offset = MI->getOperand(4).getImm();
7486     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7487     Offset = ARM_AM::getAM2Offset(Offset);
7488     if (isSub)
7489       Offset = -Offset;
7490
7491     MachineMemOperand *MMO = *MI->memoperands_begin();
7492     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7493       .addOperand(MI->getOperand(0))  // Rn_wb
7494       .addOperand(MI->getOperand(1))  // Rt
7495       .addOperand(MI->getOperand(2))  // Rn
7496       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7497       .addOperand(MI->getOperand(5))  // pred
7498       .addOperand(MI->getOperand(6))
7499       .addMemOperand(MMO);
7500     MI->eraseFromParent();
7501     return BB;
7502   }
7503   case ARM::STRr_preidx:
7504   case ARM::STRBr_preidx:
7505   case ARM::STRH_preidx: {
7506     unsigned NewOpc;
7507     switch (MI->getOpcode()) {
7508     default: llvm_unreachable("unexpected opcode!");
7509     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7510     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7511     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7512     }
7513     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7514     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7515       MIB.addOperand(MI->getOperand(i));
7516     MI->eraseFromParent();
7517     return BB;
7518   }
7519   case ARM::ATOMIC_LOAD_ADD_I8:
7520      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7521   case ARM::ATOMIC_LOAD_ADD_I16:
7522      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7523   case ARM::ATOMIC_LOAD_ADD_I32:
7524      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7525
7526   case ARM::ATOMIC_LOAD_AND_I8:
7527      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7528   case ARM::ATOMIC_LOAD_AND_I16:
7529      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7530   case ARM::ATOMIC_LOAD_AND_I32:
7531      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7532
7533   case ARM::ATOMIC_LOAD_OR_I8:
7534      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7535   case ARM::ATOMIC_LOAD_OR_I16:
7536      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7537   case ARM::ATOMIC_LOAD_OR_I32:
7538      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7539
7540   case ARM::ATOMIC_LOAD_XOR_I8:
7541      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7542   case ARM::ATOMIC_LOAD_XOR_I16:
7543      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7544   case ARM::ATOMIC_LOAD_XOR_I32:
7545      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7546
7547   case ARM::ATOMIC_LOAD_NAND_I8:
7548      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7549   case ARM::ATOMIC_LOAD_NAND_I16:
7550      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7551   case ARM::ATOMIC_LOAD_NAND_I32:
7552      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7553
7554   case ARM::ATOMIC_LOAD_SUB_I8:
7555      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7556   case ARM::ATOMIC_LOAD_SUB_I16:
7557      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7558   case ARM::ATOMIC_LOAD_SUB_I32:
7559      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7560
7561   case ARM::ATOMIC_LOAD_MIN_I8:
7562      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7563   case ARM::ATOMIC_LOAD_MIN_I16:
7564      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7565   case ARM::ATOMIC_LOAD_MIN_I32:
7566      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7567
7568   case ARM::ATOMIC_LOAD_MAX_I8:
7569      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7570   case ARM::ATOMIC_LOAD_MAX_I16:
7571      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7572   case ARM::ATOMIC_LOAD_MAX_I32:
7573      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7574
7575   case ARM::ATOMIC_LOAD_UMIN_I8:
7576      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7577   case ARM::ATOMIC_LOAD_UMIN_I16:
7578      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7579   case ARM::ATOMIC_LOAD_UMIN_I32:
7580      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7581
7582   case ARM::ATOMIC_LOAD_UMAX_I8:
7583      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7584   case ARM::ATOMIC_LOAD_UMAX_I16:
7585      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7586   case ARM::ATOMIC_LOAD_UMAX_I32:
7587      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7588
7589   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
7590   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7591   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7592
7593   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
7594   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7595   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7596
7597
7598   case ARM::ATOMADD6432:
7599     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7600                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7601                               /*NeedsCarry*/ true);
7602   case ARM::ATOMSUB6432:
7603     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7604                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7605                               /*NeedsCarry*/ true);
7606   case ARM::ATOMOR6432:
7607     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7608                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7609   case ARM::ATOMXOR6432:
7610     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7611                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7612   case ARM::ATOMAND6432:
7613     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7614                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7615   case ARM::ATOMSWAP6432:
7616     return EmitAtomicBinary64(MI, BB, 0, 0, false);
7617   case ARM::ATOMCMPXCHG6432:
7618     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7619                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7620                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7621   case ARM::ATOMMIN6432:
7622     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7623                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7624                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7625                               /*IsMinMax*/ true, ARMCC::LT);
7626   case ARM::ATOMMAX6432:
7627     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7628                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7629                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7630                               /*IsMinMax*/ true, ARMCC::GE);
7631   case ARM::ATOMUMIN6432:
7632     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7633                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7634                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7635                               /*IsMinMax*/ true, ARMCC::LO);
7636   case ARM::ATOMUMAX6432:
7637     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7638                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7639                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7640                               /*IsMinMax*/ true, ARMCC::HS);
7641
7642   case ARM::tMOVCCr_pseudo: {
7643     // To "insert" a SELECT_CC instruction, we actually have to insert the
7644     // diamond control-flow pattern.  The incoming instruction knows the
7645     // destination vreg to set, the condition code register to branch on, the
7646     // true/false values to select between, and a branch opcode to use.
7647     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7648     MachineFunction::iterator It = BB;
7649     ++It;
7650
7651     //  thisMBB:
7652     //  ...
7653     //   TrueVal = ...
7654     //   cmpTY ccX, r1, r2
7655     //   bCC copy1MBB
7656     //   fallthrough --> copy0MBB
7657     MachineBasicBlock *thisMBB  = BB;
7658     MachineFunction *F = BB->getParent();
7659     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7660     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7661     F->insert(It, copy0MBB);
7662     F->insert(It, sinkMBB);
7663
7664     // Transfer the remainder of BB and its successor edges to sinkMBB.
7665     sinkMBB->splice(sinkMBB->begin(), BB,
7666                     llvm::next(MachineBasicBlock::iterator(MI)),
7667                     BB->end());
7668     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7669
7670     BB->addSuccessor(copy0MBB);
7671     BB->addSuccessor(sinkMBB);
7672
7673     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7674       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7675
7676     //  copy0MBB:
7677     //   %FalseValue = ...
7678     //   # fallthrough to sinkMBB
7679     BB = copy0MBB;
7680
7681     // Update machine-CFG edges
7682     BB->addSuccessor(sinkMBB);
7683
7684     //  sinkMBB:
7685     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7686     //  ...
7687     BB = sinkMBB;
7688     BuildMI(*BB, BB->begin(), dl,
7689             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7690       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7691       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7692
7693     MI->eraseFromParent();   // The pseudo instruction is gone now.
7694     return BB;
7695   }
7696
7697   case ARM::BCCi64:
7698   case ARM::BCCZi64: {
7699     // If there is an unconditional branch to the other successor, remove it.
7700     BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
7701
7702     // Compare both parts that make up the double comparison separately for
7703     // equality.
7704     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7705
7706     unsigned LHS1 = MI->getOperand(1).getReg();
7707     unsigned LHS2 = MI->getOperand(2).getReg();
7708     if (RHSisZero) {
7709       AddDefaultPred(BuildMI(BB, dl,
7710                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7711                      .addReg(LHS1).addImm(0));
7712       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7713         .addReg(LHS2).addImm(0)
7714         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7715     } else {
7716       unsigned RHS1 = MI->getOperand(3).getReg();
7717       unsigned RHS2 = MI->getOperand(4).getReg();
7718       AddDefaultPred(BuildMI(BB, dl,
7719                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7720                      .addReg(LHS1).addReg(RHS1));
7721       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7722         .addReg(LHS2).addReg(RHS2)
7723         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7724     }
7725
7726     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7727     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7728     if (MI->getOperand(0).getImm() == ARMCC::NE)
7729       std::swap(destMBB, exitMBB);
7730
7731     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7732       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7733     if (isThumb2)
7734       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7735     else
7736       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7737
7738     MI->eraseFromParent();   // The pseudo instruction is gone now.
7739     return BB;
7740   }
7741
7742   case ARM::Int_eh_sjlj_setjmp:
7743   case ARM::Int_eh_sjlj_setjmp_nofp:
7744   case ARM::tInt_eh_sjlj_setjmp:
7745   case ARM::t2Int_eh_sjlj_setjmp:
7746   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7747     EmitSjLjDispatchBlock(MI, BB);
7748     return BB;
7749
7750   case ARM::ABS:
7751   case ARM::t2ABS: {
7752     // To insert an ABS instruction, we have to insert the
7753     // diamond control-flow pattern.  The incoming instruction knows the
7754     // source vreg to test against 0, the destination vreg to set,
7755     // the condition code register to branch on, the
7756     // true/false values to select between, and a branch opcode to use.
7757     // It transforms
7758     //     V1 = ABS V0
7759     // into
7760     //     V2 = MOVS V0
7761     //     BCC                      (branch to SinkBB if V0 >= 0)
7762     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7763     //     SinkBB: V1 = PHI(V2, V3)
7764     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7765     MachineFunction::iterator BBI = BB;
7766     ++BBI;
7767     MachineFunction *Fn = BB->getParent();
7768     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7769     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7770     Fn->insert(BBI, RSBBB);
7771     Fn->insert(BBI, SinkBB);
7772
7773     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7774     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7775     bool isThumb2 = Subtarget->isThumb2();
7776     MachineRegisterInfo &MRI = Fn->getRegInfo();
7777     // In Thumb mode S must not be specified if source register is the SP or
7778     // PC and if destination register is the SP, so restrict register class
7779     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7780       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7781       (const TargetRegisterClass*)&ARM::GPRRegClass);
7782
7783     // Transfer the remainder of BB and its successor edges to sinkMBB.
7784     SinkBB->splice(SinkBB->begin(), BB,
7785       llvm::next(MachineBasicBlock::iterator(MI)),
7786       BB->end());
7787     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7788
7789     BB->addSuccessor(RSBBB);
7790     BB->addSuccessor(SinkBB);
7791
7792     // fall through to SinkMBB
7793     RSBBB->addSuccessor(SinkBB);
7794
7795     // insert a cmp at the end of BB
7796     AddDefaultPred(BuildMI(BB, dl,
7797                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7798                    .addReg(ABSSrcReg).addImm(0));
7799
7800     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7801     BuildMI(BB, dl,
7802       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7803       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7804
7805     // insert rsbri in RSBBB
7806     // Note: BCC and rsbri will be converted into predicated rsbmi
7807     // by if-conversion pass
7808     BuildMI(*RSBBB, RSBBB->begin(), dl,
7809       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7810       .addReg(ABSSrcReg, RegState::Kill)
7811       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7812
7813     // insert PHI in SinkBB,
7814     // reuse ABSDstReg to not change uses of ABS instruction
7815     BuildMI(*SinkBB, SinkBB->begin(), dl,
7816       TII->get(ARM::PHI), ABSDstReg)
7817       .addReg(NewRsbDstReg).addMBB(RSBBB)
7818       .addReg(ABSSrcReg).addMBB(BB);
7819
7820     // remove ABS instruction
7821     MI->eraseFromParent();
7822
7823     // return last added BB
7824     return SinkBB;
7825   }
7826   case ARM::COPY_STRUCT_BYVAL_I32:
7827     ++NumLoopByVals;
7828     return EmitStructByval(MI, BB);
7829   }
7830 }
7831
7832 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7833                                                       SDNode *Node) const {
7834   if (!MI->hasPostISelHook()) {
7835     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7836            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7837     return;
7838   }
7839
7840   const MCInstrDesc *MCID = &MI->getDesc();
7841   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7842   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7843   // operand is still set to noreg. If needed, set the optional operand's
7844   // register to CPSR, and remove the redundant implicit def.
7845   //
7846   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7847
7848   // Rename pseudo opcodes.
7849   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7850   if (NewOpc) {
7851     const ARMBaseInstrInfo *TII =
7852       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7853     MCID = &TII->get(NewOpc);
7854
7855     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7856            "converted opcode should be the same except for cc_out");
7857
7858     MI->setDesc(*MCID);
7859
7860     // Add the optional cc_out operand
7861     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7862   }
7863   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7864
7865   // Any ARM instruction that sets the 's' bit should specify an optional
7866   // "cc_out" operand in the last operand position.
7867   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7868     assert(!NewOpc && "Optional cc_out operand required");
7869     return;
7870   }
7871   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7872   // since we already have an optional CPSR def.
7873   bool definesCPSR = false;
7874   bool deadCPSR = false;
7875   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7876        i != e; ++i) {
7877     const MachineOperand &MO = MI->getOperand(i);
7878     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7879       definesCPSR = true;
7880       if (MO.isDead())
7881         deadCPSR = true;
7882       MI->RemoveOperand(i);
7883       break;
7884     }
7885   }
7886   if (!definesCPSR) {
7887     assert(!NewOpc && "Optional cc_out operand required");
7888     return;
7889   }
7890   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7891   if (deadCPSR) {
7892     assert(!MI->getOperand(ccOutIdx).getReg() &&
7893            "expect uninitialized optional cc_out operand");
7894     return;
7895   }
7896
7897   // If this instruction was defined with an optional CPSR def and its dag node
7898   // had a live implicit CPSR def, then activate the optional CPSR def.
7899   MachineOperand &MO = MI->getOperand(ccOutIdx);
7900   MO.setReg(ARM::CPSR);
7901   MO.setIsDef(true);
7902 }
7903
7904 //===----------------------------------------------------------------------===//
7905 //                           ARM Optimization Hooks
7906 //===----------------------------------------------------------------------===//
7907
7908 // Helper function that checks if N is a null or all ones constant.
7909 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7910   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7911   if (!C)
7912     return false;
7913   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7914 }
7915
7916 // Return true if N is conditionally 0 or all ones.
7917 // Detects these expressions where cc is an i1 value:
7918 //
7919 //   (select cc 0, y)   [AllOnes=0]
7920 //   (select cc y, 0)   [AllOnes=0]
7921 //   (zext cc)          [AllOnes=0]
7922 //   (sext cc)          [AllOnes=0/1]
7923 //   (select cc -1, y)  [AllOnes=1]
7924 //   (select cc y, -1)  [AllOnes=1]
7925 //
7926 // Invert is set when N is the null/all ones constant when CC is false.
7927 // OtherOp is set to the alternative value of N.
7928 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7929                                        SDValue &CC, bool &Invert,
7930                                        SDValue &OtherOp,
7931                                        SelectionDAG &DAG) {
7932   switch (N->getOpcode()) {
7933   default: return false;
7934   case ISD::SELECT: {
7935     CC = N->getOperand(0);
7936     SDValue N1 = N->getOperand(1);
7937     SDValue N2 = N->getOperand(2);
7938     if (isZeroOrAllOnes(N1, AllOnes)) {
7939       Invert = false;
7940       OtherOp = N2;
7941       return true;
7942     }
7943     if (isZeroOrAllOnes(N2, AllOnes)) {
7944       Invert = true;
7945       OtherOp = N1;
7946       return true;
7947     }
7948     return false;
7949   }
7950   case ISD::ZERO_EXTEND:
7951     // (zext cc) can never be the all ones value.
7952     if (AllOnes)
7953       return false;
7954     // Fall through.
7955   case ISD::SIGN_EXTEND: {
7956     EVT VT = N->getValueType(0);
7957     CC = N->getOperand(0);
7958     if (CC.getValueType() != MVT::i1)
7959       return false;
7960     Invert = !AllOnes;
7961     if (AllOnes)
7962       // When looking for an AllOnes constant, N is an sext, and the 'other'
7963       // value is 0.
7964       OtherOp = DAG.getConstant(0, VT);
7965     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7966       // When looking for a 0 constant, N can be zext or sext.
7967       OtherOp = DAG.getConstant(1, VT);
7968     else
7969       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7970     return true;
7971   }
7972   }
7973 }
7974
7975 // Combine a constant select operand into its use:
7976 //
7977 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7978 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7979 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7980 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7981 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7982 //
7983 // The transform is rejected if the select doesn't have a constant operand that
7984 // is null, or all ones when AllOnes is set.
7985 //
7986 // Also recognize sext/zext from i1:
7987 //
7988 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7989 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7990 //
7991 // These transformations eventually create predicated instructions.
7992 //
7993 // @param N       The node to transform.
7994 // @param Slct    The N operand that is a select.
7995 // @param OtherOp The other N operand (x above).
7996 // @param DCI     Context.
7997 // @param AllOnes Require the select constant to be all ones instead of null.
7998 // @returns The new node, or SDValue() on failure.
7999 static
8000 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8001                             TargetLowering::DAGCombinerInfo &DCI,
8002                             bool AllOnes = false) {
8003   SelectionDAG &DAG = DCI.DAG;
8004   EVT VT = N->getValueType(0);
8005   SDValue NonConstantVal;
8006   SDValue CCOp;
8007   bool SwapSelectOps;
8008   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8009                                   NonConstantVal, DAG))
8010     return SDValue();
8011
8012   // Slct is now know to be the desired identity constant when CC is true.
8013   SDValue TrueVal = OtherOp;
8014   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8015                                  OtherOp, NonConstantVal);
8016   // Unless SwapSelectOps says CC should be false.
8017   if (SwapSelectOps)
8018     std::swap(TrueVal, FalseVal);
8019
8020   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8021                      CCOp, TrueVal, FalseVal);
8022 }
8023
8024 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8025 static
8026 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8027                                        TargetLowering::DAGCombinerInfo &DCI) {
8028   SDValue N0 = N->getOperand(0);
8029   SDValue N1 = N->getOperand(1);
8030   if (N0.getNode()->hasOneUse()) {
8031     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8032     if (Result.getNode())
8033       return Result;
8034   }
8035   if (N1.getNode()->hasOneUse()) {
8036     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8037     if (Result.getNode())
8038       return Result;
8039   }
8040   return SDValue();
8041 }
8042
8043 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8044 // (only after legalization).
8045 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8046                                  TargetLowering::DAGCombinerInfo &DCI,
8047                                  const ARMSubtarget *Subtarget) {
8048
8049   // Only perform optimization if after legalize, and if NEON is available. We
8050   // also expected both operands to be BUILD_VECTORs.
8051   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8052       || N0.getOpcode() != ISD::BUILD_VECTOR
8053       || N1.getOpcode() != ISD::BUILD_VECTOR)
8054     return SDValue();
8055
8056   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8057   EVT VT = N->getValueType(0);
8058   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8059     return SDValue();
8060
8061   // Check that the vector operands are of the right form.
8062   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8063   // operands, where N is the size of the formed vector.
8064   // Each EXTRACT_VECTOR should have the same input vector and odd or even
8065   // index such that we have a pair wise add pattern.
8066
8067   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8068   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8069     return SDValue();
8070   SDValue Vec = N0->getOperand(0)->getOperand(0);
8071   SDNode *V = Vec.getNode();
8072   unsigned nextIndex = 0;
8073
8074   // For each operands to the ADD which are BUILD_VECTORs,
8075   // check to see if each of their operands are an EXTRACT_VECTOR with
8076   // the same vector and appropriate index.
8077   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8078     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8079         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8080
8081       SDValue ExtVec0 = N0->getOperand(i);
8082       SDValue ExtVec1 = N1->getOperand(i);
8083
8084       // First operand is the vector, verify its the same.
8085       if (V != ExtVec0->getOperand(0).getNode() ||
8086           V != ExtVec1->getOperand(0).getNode())
8087         return SDValue();
8088
8089       // Second is the constant, verify its correct.
8090       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8091       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8092
8093       // For the constant, we want to see all the even or all the odd.
8094       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8095           || C1->getZExtValue() != nextIndex+1)
8096         return SDValue();
8097
8098       // Increment index.
8099       nextIndex+=2;
8100     } else
8101       return SDValue();
8102   }
8103
8104   // Create VPADDL node.
8105   SelectionDAG &DAG = DCI.DAG;
8106   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8107
8108   // Build operand list.
8109   SmallVector<SDValue, 8> Ops;
8110   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
8111                                 TLI.getPointerTy()));
8112
8113   // Input is the vector.
8114   Ops.push_back(Vec);
8115
8116   // Get widened type and narrowed type.
8117   MVT widenType;
8118   unsigned numElem = VT.getVectorNumElements();
8119   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8120     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8121     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8122     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8123     default:
8124       llvm_unreachable("Invalid vector element type for padd optimization.");
8125   }
8126
8127   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
8128                             widenType, &Ops[0], Ops.size());
8129   return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, tmp);
8130 }
8131
8132 static SDValue findMUL_LOHI(SDValue V) {
8133   if (V->getOpcode() == ISD::UMUL_LOHI ||
8134       V->getOpcode() == ISD::SMUL_LOHI)
8135     return V;
8136   return SDValue();
8137 }
8138
8139 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8140                                      TargetLowering::DAGCombinerInfo &DCI,
8141                                      const ARMSubtarget *Subtarget) {
8142
8143   if (Subtarget->isThumb1Only()) return SDValue();
8144
8145   // Only perform the checks after legalize when the pattern is available.
8146   if (DCI.isBeforeLegalize()) return SDValue();
8147
8148   // Look for multiply add opportunities.
8149   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8150   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8151   // a glue link from the first add to the second add.
8152   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8153   // a S/UMLAL instruction.
8154   //          loAdd   UMUL_LOHI
8155   //            \    / :lo    \ :hi
8156   //             \  /          \          [no multiline comment]
8157   //              ADDC         |  hiAdd
8158   //                 \ :glue  /  /
8159   //                  \      /  /
8160   //                    ADDE
8161   //
8162   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8163   SDValue AddcOp0 = AddcNode->getOperand(0);
8164   SDValue AddcOp1 = AddcNode->getOperand(1);
8165
8166   // Check if the two operands are from the same mul_lohi node.
8167   if (AddcOp0.getNode() == AddcOp1.getNode())
8168     return SDValue();
8169
8170   assert(AddcNode->getNumValues() == 2 &&
8171          AddcNode->getValueType(0) == MVT::i32 &&
8172          "Expect ADDC with two result values. First: i32");
8173
8174   // Check that we have a glued ADDC node.
8175   if (AddcNode->getValueType(1) != MVT::Glue)
8176     return SDValue();
8177
8178   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8179   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8180       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8181       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8182       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8183     return SDValue();
8184
8185   // Look for the glued ADDE.
8186   SDNode* AddeNode = AddcNode->getGluedUser();
8187   if (AddeNode == NULL)
8188     return SDValue();
8189
8190   // Make sure it is really an ADDE.
8191   if (AddeNode->getOpcode() != ISD::ADDE)
8192     return SDValue();
8193
8194   assert(AddeNode->getNumOperands() == 3 &&
8195          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8196          "ADDE node has the wrong inputs");
8197
8198   // Check for the triangle shape.
8199   SDValue AddeOp0 = AddeNode->getOperand(0);
8200   SDValue AddeOp1 = AddeNode->getOperand(1);
8201
8202   // Make sure that the ADDE operands are not coming from the same node.
8203   if (AddeOp0.getNode() == AddeOp1.getNode())
8204     return SDValue();
8205
8206   // Find the MUL_LOHI node walking up ADDE's operands.
8207   bool IsLeftOperandMUL = false;
8208   SDValue MULOp = findMUL_LOHI(AddeOp0);
8209   if (MULOp == SDValue())
8210    MULOp = findMUL_LOHI(AddeOp1);
8211   else
8212     IsLeftOperandMUL = true;
8213   if (MULOp == SDValue())
8214      return SDValue();
8215
8216   // Figure out the right opcode.
8217   unsigned Opc = MULOp->getOpcode();
8218   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8219
8220   // Figure out the high and low input values to the MLAL node.
8221   SDValue* HiMul = &MULOp;
8222   SDValue* HiAdd = NULL;
8223   SDValue* LoMul = NULL;
8224   SDValue* LowAdd = NULL;
8225
8226   if (IsLeftOperandMUL)
8227     HiAdd = &AddeOp1;
8228   else
8229     HiAdd = &AddeOp0;
8230
8231
8232   if (AddcOp0->getOpcode() == Opc) {
8233     LoMul = &AddcOp0;
8234     LowAdd = &AddcOp1;
8235   }
8236   if (AddcOp1->getOpcode() == Opc) {
8237     LoMul = &AddcOp1;
8238     LowAdd = &AddcOp0;
8239   }
8240
8241   if (LoMul == NULL)
8242     return SDValue();
8243
8244   if (LoMul->getNode() != HiMul->getNode())
8245     return SDValue();
8246
8247   // Create the merged node.
8248   SelectionDAG &DAG = DCI.DAG;
8249
8250   // Build operand list.
8251   SmallVector<SDValue, 8> Ops;
8252   Ops.push_back(LoMul->getOperand(0));
8253   Ops.push_back(LoMul->getOperand(1));
8254   Ops.push_back(*LowAdd);
8255   Ops.push_back(*HiAdd);
8256
8257   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8258                                  DAG.getVTList(MVT::i32, MVT::i32),
8259                                  &Ops[0], Ops.size());
8260
8261   // Replace the ADDs' nodes uses by the MLA node's values.
8262   SDValue HiMLALResult(MLALNode.getNode(), 1);
8263   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8264
8265   SDValue LoMLALResult(MLALNode.getNode(), 0);
8266   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8267
8268   // Return original node to notify the driver to stop replacing.
8269   SDValue resNode(AddcNode, 0);
8270   return resNode;
8271 }
8272
8273 /// PerformADDCCombine - Target-specific dag combine transform from
8274 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8275 static SDValue PerformADDCCombine(SDNode *N,
8276                                  TargetLowering::DAGCombinerInfo &DCI,
8277                                  const ARMSubtarget *Subtarget) {
8278
8279   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8280
8281 }
8282
8283 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8284 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8285 /// called with the default operands, and if that fails, with commuted
8286 /// operands.
8287 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8288                                           TargetLowering::DAGCombinerInfo &DCI,
8289                                           const ARMSubtarget *Subtarget){
8290
8291   // Attempt to create vpaddl for this add.
8292   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8293   if (Result.getNode())
8294     return Result;
8295
8296   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8297   if (N0.getNode()->hasOneUse()) {
8298     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8299     if (Result.getNode()) return Result;
8300   }
8301   return SDValue();
8302 }
8303
8304 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8305 ///
8306 static SDValue PerformADDCombine(SDNode *N,
8307                                  TargetLowering::DAGCombinerInfo &DCI,
8308                                  const ARMSubtarget *Subtarget) {
8309   SDValue N0 = N->getOperand(0);
8310   SDValue N1 = N->getOperand(1);
8311
8312   // First try with the default operand order.
8313   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8314   if (Result.getNode())
8315     return Result;
8316
8317   // If that didn't work, try again with the operands commuted.
8318   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8319 }
8320
8321 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8322 ///
8323 static SDValue PerformSUBCombine(SDNode *N,
8324                                  TargetLowering::DAGCombinerInfo &DCI) {
8325   SDValue N0 = N->getOperand(0);
8326   SDValue N1 = N->getOperand(1);
8327
8328   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8329   if (N1.getNode()->hasOneUse()) {
8330     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8331     if (Result.getNode()) return Result;
8332   }
8333
8334   return SDValue();
8335 }
8336
8337 /// PerformVMULCombine
8338 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8339 /// special multiplier accumulator forwarding.
8340 ///   vmul d3, d0, d2
8341 ///   vmla d3, d1, d2
8342 /// is faster than
8343 ///   vadd d3, d0, d1
8344 ///   vmul d3, d3, d2
8345 //  However, for (A + B) * (A + B),
8346 //    vadd d2, d0, d1
8347 //    vmul d3, d0, d2
8348 //    vmla d3, d1, d2
8349 //  is slower than
8350 //    vadd d2, d0, d1
8351 //    vmul d3, d2, d2
8352 static SDValue PerformVMULCombine(SDNode *N,
8353                                   TargetLowering::DAGCombinerInfo &DCI,
8354                                   const ARMSubtarget *Subtarget) {
8355   if (!Subtarget->hasVMLxForwarding())
8356     return SDValue();
8357
8358   SelectionDAG &DAG = DCI.DAG;
8359   SDValue N0 = N->getOperand(0);
8360   SDValue N1 = N->getOperand(1);
8361   unsigned Opcode = N0.getOpcode();
8362   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8363       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8364     Opcode = N1.getOpcode();
8365     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8366         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8367       return SDValue();
8368     std::swap(N0, N1);
8369   }
8370
8371   if (N0 == N1)
8372     return SDValue();
8373
8374   EVT VT = N->getValueType(0);
8375   SDLoc DL(N);
8376   SDValue N00 = N0->getOperand(0);
8377   SDValue N01 = N0->getOperand(1);
8378   return DAG.getNode(Opcode, DL, VT,
8379                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8380                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8381 }
8382
8383 static SDValue PerformMULCombine(SDNode *N,
8384                                  TargetLowering::DAGCombinerInfo &DCI,
8385                                  const ARMSubtarget *Subtarget) {
8386   SelectionDAG &DAG = DCI.DAG;
8387
8388   if (Subtarget->isThumb1Only())
8389     return SDValue();
8390
8391   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8392     return SDValue();
8393
8394   EVT VT = N->getValueType(0);
8395   if (VT.is64BitVector() || VT.is128BitVector())
8396     return PerformVMULCombine(N, DCI, Subtarget);
8397   if (VT != MVT::i32)
8398     return SDValue();
8399
8400   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8401   if (!C)
8402     return SDValue();
8403
8404   int64_t MulAmt = C->getSExtValue();
8405   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8406
8407   ShiftAmt = ShiftAmt & (32 - 1);
8408   SDValue V = N->getOperand(0);
8409   SDLoc DL(N);
8410
8411   SDValue Res;
8412   MulAmt >>= ShiftAmt;
8413
8414   if (MulAmt >= 0) {
8415     if (isPowerOf2_32(MulAmt - 1)) {
8416       // (mul x, 2^N + 1) => (add (shl x, N), x)
8417       Res = DAG.getNode(ISD::ADD, DL, VT,
8418                         V,
8419                         DAG.getNode(ISD::SHL, DL, VT,
8420                                     V,
8421                                     DAG.getConstant(Log2_32(MulAmt - 1),
8422                                                     MVT::i32)));
8423     } else if (isPowerOf2_32(MulAmt + 1)) {
8424       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8425       Res = DAG.getNode(ISD::SUB, DL, VT,
8426                         DAG.getNode(ISD::SHL, DL, VT,
8427                                     V,
8428                                     DAG.getConstant(Log2_32(MulAmt + 1),
8429                                                     MVT::i32)),
8430                         V);
8431     } else
8432       return SDValue();
8433   } else {
8434     uint64_t MulAmtAbs = -MulAmt;
8435     if (isPowerOf2_32(MulAmtAbs + 1)) {
8436       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8437       Res = DAG.getNode(ISD::SUB, DL, VT,
8438                         V,
8439                         DAG.getNode(ISD::SHL, DL, VT,
8440                                     V,
8441                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8442                                                     MVT::i32)));
8443     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8444       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8445       Res = DAG.getNode(ISD::ADD, DL, VT,
8446                         V,
8447                         DAG.getNode(ISD::SHL, DL, VT,
8448                                     V,
8449                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8450                                                     MVT::i32)));
8451       Res = DAG.getNode(ISD::SUB, DL, VT,
8452                         DAG.getConstant(0, MVT::i32),Res);
8453
8454     } else
8455       return SDValue();
8456   }
8457
8458   if (ShiftAmt != 0)
8459     Res = DAG.getNode(ISD::SHL, DL, VT,
8460                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8461
8462   // Do not add new nodes to DAG combiner worklist.
8463   DCI.CombineTo(N, Res, false);
8464   return SDValue();
8465 }
8466
8467 static SDValue PerformANDCombine(SDNode *N,
8468                                  TargetLowering::DAGCombinerInfo &DCI,
8469                                  const ARMSubtarget *Subtarget) {
8470
8471   // Attempt to use immediate-form VBIC
8472   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8473   SDLoc dl(N);
8474   EVT VT = N->getValueType(0);
8475   SelectionDAG &DAG = DCI.DAG;
8476
8477   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8478     return SDValue();
8479
8480   APInt SplatBits, SplatUndef;
8481   unsigned SplatBitSize;
8482   bool HasAnyUndefs;
8483   if (BVN &&
8484       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8485     if (SplatBitSize <= 64) {
8486       EVT VbicVT;
8487       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8488                                       SplatUndef.getZExtValue(), SplatBitSize,
8489                                       DAG, VbicVT, VT.is128BitVector(),
8490                                       OtherModImm);
8491       if (Val.getNode()) {
8492         SDValue Input =
8493           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8494         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8495         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8496       }
8497     }
8498   }
8499
8500   if (!Subtarget->isThumb1Only()) {
8501     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8502     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8503     if (Result.getNode())
8504       return Result;
8505   }
8506
8507   return SDValue();
8508 }
8509
8510 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8511 static SDValue PerformORCombine(SDNode *N,
8512                                 TargetLowering::DAGCombinerInfo &DCI,
8513                                 const ARMSubtarget *Subtarget) {
8514   // Attempt to use immediate-form VORR
8515   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8516   SDLoc dl(N);
8517   EVT VT = N->getValueType(0);
8518   SelectionDAG &DAG = DCI.DAG;
8519
8520   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8521     return SDValue();
8522
8523   APInt SplatBits, SplatUndef;
8524   unsigned SplatBitSize;
8525   bool HasAnyUndefs;
8526   if (BVN && Subtarget->hasNEON() &&
8527       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8528     if (SplatBitSize <= 64) {
8529       EVT VorrVT;
8530       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8531                                       SplatUndef.getZExtValue(), SplatBitSize,
8532                                       DAG, VorrVT, VT.is128BitVector(),
8533                                       OtherModImm);
8534       if (Val.getNode()) {
8535         SDValue Input =
8536           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8537         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8538         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8539       }
8540     }
8541   }
8542
8543   if (!Subtarget->isThumb1Only()) {
8544     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8545     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8546     if (Result.getNode())
8547       return Result;
8548   }
8549
8550   // The code below optimizes (or (and X, Y), Z).
8551   // The AND operand needs to have a single user to make these optimizations
8552   // profitable.
8553   SDValue N0 = N->getOperand(0);
8554   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8555     return SDValue();
8556   SDValue N1 = N->getOperand(1);
8557
8558   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8559   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8560       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8561     APInt SplatUndef;
8562     unsigned SplatBitSize;
8563     bool HasAnyUndefs;
8564
8565     APInt SplatBits0, SplatBits1;
8566     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8567     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8568     // Ensure that the second operand of both ands are constants
8569     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8570                                       HasAnyUndefs) && !HasAnyUndefs) {
8571         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8572                                           HasAnyUndefs) && !HasAnyUndefs) {
8573             // Ensure that the bit width of the constants are the same and that
8574             // the splat arguments are logical inverses as per the pattern we
8575             // are trying to simplify.
8576             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8577                 SplatBits0 == ~SplatBits1) {
8578                 // Canonicalize the vector type to make instruction selection
8579                 // simpler.
8580                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8581                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8582                                              N0->getOperand(1),
8583                                              N0->getOperand(0),
8584                                              N1->getOperand(0));
8585                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8586             }
8587         }
8588     }
8589   }
8590
8591   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8592   // reasonable.
8593
8594   // BFI is only available on V6T2+
8595   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8596     return SDValue();
8597
8598   SDLoc DL(N);
8599   // 1) or (and A, mask), val => ARMbfi A, val, mask
8600   //      iff (val & mask) == val
8601   //
8602   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8603   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8604   //          && mask == ~mask2
8605   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8606   //          && ~mask == mask2
8607   //  (i.e., copy a bitfield value into another bitfield of the same width)
8608
8609   if (VT != MVT::i32)
8610     return SDValue();
8611
8612   SDValue N00 = N0.getOperand(0);
8613
8614   // The value and the mask need to be constants so we can verify this is
8615   // actually a bitfield set. If the mask is 0xffff, we can do better
8616   // via a movt instruction, so don't use BFI in that case.
8617   SDValue MaskOp = N0.getOperand(1);
8618   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8619   if (!MaskC)
8620     return SDValue();
8621   unsigned Mask = MaskC->getZExtValue();
8622   if (Mask == 0xffff)
8623     return SDValue();
8624   SDValue Res;
8625   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8626   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8627   if (N1C) {
8628     unsigned Val = N1C->getZExtValue();
8629     if ((Val & ~Mask) != Val)
8630       return SDValue();
8631
8632     if (ARM::isBitFieldInvertedMask(Mask)) {
8633       Val >>= countTrailingZeros(~Mask);
8634
8635       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8636                         DAG.getConstant(Val, MVT::i32),
8637                         DAG.getConstant(Mask, MVT::i32));
8638
8639       // Do not add new nodes to DAG combiner worklist.
8640       DCI.CombineTo(N, Res, false);
8641       return SDValue();
8642     }
8643   } else if (N1.getOpcode() == ISD::AND) {
8644     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8645     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8646     if (!N11C)
8647       return SDValue();
8648     unsigned Mask2 = N11C->getZExtValue();
8649
8650     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8651     // as is to match.
8652     if (ARM::isBitFieldInvertedMask(Mask) &&
8653         (Mask == ~Mask2)) {
8654       // The pack halfword instruction works better for masks that fit it,
8655       // so use that when it's available.
8656       if (Subtarget->hasT2ExtractPack() &&
8657           (Mask == 0xffff || Mask == 0xffff0000))
8658         return SDValue();
8659       // 2a
8660       unsigned amt = countTrailingZeros(Mask2);
8661       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8662                         DAG.getConstant(amt, MVT::i32));
8663       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8664                         DAG.getConstant(Mask, MVT::i32));
8665       // Do not add new nodes to DAG combiner worklist.
8666       DCI.CombineTo(N, Res, false);
8667       return SDValue();
8668     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8669                (~Mask == Mask2)) {
8670       // The pack halfword instruction works better for masks that fit it,
8671       // so use that when it's available.
8672       if (Subtarget->hasT2ExtractPack() &&
8673           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8674         return SDValue();
8675       // 2b
8676       unsigned lsb = countTrailingZeros(Mask);
8677       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8678                         DAG.getConstant(lsb, MVT::i32));
8679       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8680                         DAG.getConstant(Mask2, MVT::i32));
8681       // Do not add new nodes to DAG combiner worklist.
8682       DCI.CombineTo(N, Res, false);
8683       return SDValue();
8684     }
8685   }
8686
8687   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8688       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8689       ARM::isBitFieldInvertedMask(~Mask)) {
8690     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8691     // where lsb(mask) == #shamt and masked bits of B are known zero.
8692     SDValue ShAmt = N00.getOperand(1);
8693     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8694     unsigned LSB = countTrailingZeros(Mask);
8695     if (ShAmtC != LSB)
8696       return SDValue();
8697
8698     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8699                       DAG.getConstant(~Mask, MVT::i32));
8700
8701     // Do not add new nodes to DAG combiner worklist.
8702     DCI.CombineTo(N, Res, false);
8703   }
8704
8705   return SDValue();
8706 }
8707
8708 static SDValue PerformXORCombine(SDNode *N,
8709                                  TargetLowering::DAGCombinerInfo &DCI,
8710                                  const ARMSubtarget *Subtarget) {
8711   EVT VT = N->getValueType(0);
8712   SelectionDAG &DAG = DCI.DAG;
8713
8714   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8715     return SDValue();
8716
8717   if (!Subtarget->isThumb1Only()) {
8718     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8719     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8720     if (Result.getNode())
8721       return Result;
8722   }
8723
8724   return SDValue();
8725 }
8726
8727 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8728 /// the bits being cleared by the AND are not demanded by the BFI.
8729 static SDValue PerformBFICombine(SDNode *N,
8730                                  TargetLowering::DAGCombinerInfo &DCI) {
8731   SDValue N1 = N->getOperand(1);
8732   if (N1.getOpcode() == ISD::AND) {
8733     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8734     if (!N11C)
8735       return SDValue();
8736     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8737     unsigned LSB = countTrailingZeros(~InvMask);
8738     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8739     unsigned Mask = (1 << Width)-1;
8740     unsigned Mask2 = N11C->getZExtValue();
8741     if ((Mask & (~Mask2)) == 0)
8742       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8743                              N->getOperand(0), N1.getOperand(0),
8744                              N->getOperand(2));
8745   }
8746   return SDValue();
8747 }
8748
8749 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8750 /// ARMISD::VMOVRRD.
8751 static SDValue PerformVMOVRRDCombine(SDNode *N,
8752                                      TargetLowering::DAGCombinerInfo &DCI) {
8753   // vmovrrd(vmovdrr x, y) -> x,y
8754   SDValue InDouble = N->getOperand(0);
8755   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8756     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8757
8758   // vmovrrd(load f64) -> (load i32), (load i32)
8759   SDNode *InNode = InDouble.getNode();
8760   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8761       InNode->getValueType(0) == MVT::f64 &&
8762       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8763       !cast<LoadSDNode>(InNode)->isVolatile()) {
8764     // TODO: Should this be done for non-FrameIndex operands?
8765     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8766
8767     SelectionDAG &DAG = DCI.DAG;
8768     SDLoc DL(LD);
8769     SDValue BasePtr = LD->getBasePtr();
8770     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8771                                  LD->getPointerInfo(), LD->isVolatile(),
8772                                  LD->isNonTemporal(), LD->isInvariant(),
8773                                  LD->getAlignment());
8774
8775     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8776                                     DAG.getConstant(4, MVT::i32));
8777     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8778                                  LD->getPointerInfo(), LD->isVolatile(),
8779                                  LD->isNonTemporal(), LD->isInvariant(),
8780                                  std::min(4U, LD->getAlignment() / 2));
8781
8782     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8783     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8784     DCI.RemoveFromWorklist(LD);
8785     DAG.DeleteNode(LD);
8786     return Result;
8787   }
8788
8789   return SDValue();
8790 }
8791
8792 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8793 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8794 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8795   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8796   SDValue Op0 = N->getOperand(0);
8797   SDValue Op1 = N->getOperand(1);
8798   if (Op0.getOpcode() == ISD::BITCAST)
8799     Op0 = Op0.getOperand(0);
8800   if (Op1.getOpcode() == ISD::BITCAST)
8801     Op1 = Op1.getOperand(0);
8802   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8803       Op0.getNode() == Op1.getNode() &&
8804       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8805     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8806                        N->getValueType(0), Op0.getOperand(0));
8807   return SDValue();
8808 }
8809
8810 /// PerformSTORECombine - Target-specific dag combine xforms for
8811 /// ISD::STORE.
8812 static SDValue PerformSTORECombine(SDNode *N,
8813                                    TargetLowering::DAGCombinerInfo &DCI) {
8814   StoreSDNode *St = cast<StoreSDNode>(N);
8815   if (St->isVolatile())
8816     return SDValue();
8817
8818   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8819   // pack all of the elements in one place.  Next, store to memory in fewer
8820   // chunks.
8821   SDValue StVal = St->getValue();
8822   EVT VT = StVal.getValueType();
8823   if (St->isTruncatingStore() && VT.isVector()) {
8824     SelectionDAG &DAG = DCI.DAG;
8825     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8826     EVT StVT = St->getMemoryVT();
8827     unsigned NumElems = VT.getVectorNumElements();
8828     assert(StVT != VT && "Cannot truncate to the same type");
8829     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8830     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8831
8832     // From, To sizes and ElemCount must be pow of two
8833     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8834
8835     // We are going to use the original vector elt for storing.
8836     // Accumulated smaller vector elements must be a multiple of the store size.
8837     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8838
8839     unsigned SizeRatio  = FromEltSz / ToEltSz;
8840     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8841
8842     // Create a type on which we perform the shuffle.
8843     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8844                                      NumElems*SizeRatio);
8845     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8846
8847     SDLoc DL(St);
8848     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8849     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8850     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8851
8852     // Can't shuffle using an illegal type.
8853     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8854
8855     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8856                                 DAG.getUNDEF(WideVec.getValueType()),
8857                                 ShuffleVec.data());
8858     // At this point all of the data is stored at the bottom of the
8859     // register. We now need to save it to mem.
8860
8861     // Find the largest store unit
8862     MVT StoreType = MVT::i8;
8863     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8864          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8865       MVT Tp = (MVT::SimpleValueType)tp;
8866       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8867         StoreType = Tp;
8868     }
8869     // Didn't find a legal store type.
8870     if (!TLI.isTypeLegal(StoreType))
8871       return SDValue();
8872
8873     // Bitcast the original vector into a vector of store-size units
8874     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8875             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8876     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8877     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8878     SmallVector<SDValue, 8> Chains;
8879     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8880                                         TLI.getPointerTy());
8881     SDValue BasePtr = St->getBasePtr();
8882
8883     // Perform one or more big stores into memory.
8884     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8885     for (unsigned I = 0; I < E; I++) {
8886       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8887                                    StoreType, ShuffWide,
8888                                    DAG.getIntPtrConstant(I));
8889       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8890                                 St->getPointerInfo(), St->isVolatile(),
8891                                 St->isNonTemporal(), St->getAlignment());
8892       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8893                             Increment);
8894       Chains.push_back(Ch);
8895     }
8896     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
8897                        Chains.size());
8898   }
8899
8900   if (!ISD::isNormalStore(St))
8901     return SDValue();
8902
8903   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8904   // ARM stores of arguments in the same cache line.
8905   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8906       StVal.getNode()->hasOneUse()) {
8907     SelectionDAG  &DAG = DCI.DAG;
8908     SDLoc DL(St);
8909     SDValue BasePtr = St->getBasePtr();
8910     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8911                                   StVal.getNode()->getOperand(0), BasePtr,
8912                                   St->getPointerInfo(), St->isVolatile(),
8913                                   St->isNonTemporal(), St->getAlignment());
8914
8915     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8916                                     DAG.getConstant(4, MVT::i32));
8917     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
8918                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8919                         St->isNonTemporal(),
8920                         std::min(4U, St->getAlignment() / 2));
8921   }
8922
8923   if (StVal.getValueType() != MVT::i64 ||
8924       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8925     return SDValue();
8926
8927   // Bitcast an i64 store extracted from a vector to f64.
8928   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8929   SelectionDAG &DAG = DCI.DAG;
8930   SDLoc dl(StVal);
8931   SDValue IntVec = StVal.getOperand(0);
8932   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8933                                  IntVec.getValueType().getVectorNumElements());
8934   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8935   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8936                                Vec, StVal.getOperand(1));
8937   dl = SDLoc(N);
8938   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8939   // Make the DAGCombiner fold the bitcasts.
8940   DCI.AddToWorklist(Vec.getNode());
8941   DCI.AddToWorklist(ExtElt.getNode());
8942   DCI.AddToWorklist(V.getNode());
8943   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8944                       St->getPointerInfo(), St->isVolatile(),
8945                       St->isNonTemporal(), St->getAlignment(),
8946                       St->getTBAAInfo());
8947 }
8948
8949 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8950 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8951 /// i64 vector to have f64 elements, since the value can then be loaded
8952 /// directly into a VFP register.
8953 static bool hasNormalLoadOperand(SDNode *N) {
8954   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8955   for (unsigned i = 0; i < NumElts; ++i) {
8956     SDNode *Elt = N->getOperand(i).getNode();
8957     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8958       return true;
8959   }
8960   return false;
8961 }
8962
8963 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8964 /// ISD::BUILD_VECTOR.
8965 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8966                                           TargetLowering::DAGCombinerInfo &DCI){
8967   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8968   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8969   // into a pair of GPRs, which is fine when the value is used as a scalar,
8970   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8971   SelectionDAG &DAG = DCI.DAG;
8972   if (N->getNumOperands() == 2) {
8973     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8974     if (RV.getNode())
8975       return RV;
8976   }
8977
8978   // Load i64 elements as f64 values so that type legalization does not split
8979   // them up into i32 values.
8980   EVT VT = N->getValueType(0);
8981   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8982     return SDValue();
8983   SDLoc dl(N);
8984   SmallVector<SDValue, 8> Ops;
8985   unsigned NumElts = VT.getVectorNumElements();
8986   for (unsigned i = 0; i < NumElts; ++i) {
8987     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8988     Ops.push_back(V);
8989     // Make the DAGCombiner fold the bitcast.
8990     DCI.AddToWorklist(V.getNode());
8991   }
8992   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8993   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
8994   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8995 }
8996
8997 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8998 static SDValue
8999 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9000   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9001   // At that time, we may have inserted bitcasts from integer to float.
9002   // If these bitcasts have survived DAGCombine, change the lowering of this
9003   // BUILD_VECTOR in something more vector friendly, i.e., that does not
9004   // force to use floating point types.
9005
9006   // Make sure we can change the type of the vector.
9007   // This is possible iff:
9008   // 1. The vector is only used in a bitcast to a integer type. I.e.,
9009   //    1.1. Vector is used only once.
9010   //    1.2. Use is a bit convert to an integer type.
9011   // 2. The size of its operands are 32-bits (64-bits are not legal).
9012   EVT VT = N->getValueType(0);
9013   EVT EltVT = VT.getVectorElementType();
9014
9015   // Check 1.1. and 2.
9016   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9017     return SDValue();
9018
9019   // By construction, the input type must be float.
9020   assert(EltVT == MVT::f32 && "Unexpected type!");
9021
9022   // Check 1.2.
9023   SDNode *Use = *N->use_begin();
9024   if (Use->getOpcode() != ISD::BITCAST ||
9025       Use->getValueType(0).isFloatingPoint())
9026     return SDValue();
9027
9028   // Check profitability.
9029   // Model is, if more than half of the relevant operands are bitcast from
9030   // i32, turn the build_vector into a sequence of insert_vector_elt.
9031   // Relevant operands are everything that is not statically
9032   // (i.e., at compile time) bitcasted.
9033   unsigned NumOfBitCastedElts = 0;
9034   unsigned NumElts = VT.getVectorNumElements();
9035   unsigned NumOfRelevantElts = NumElts;
9036   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9037     SDValue Elt = N->getOperand(Idx);
9038     if (Elt->getOpcode() == ISD::BITCAST) {
9039       // Assume only bit cast to i32 will go away.
9040       if (Elt->getOperand(0).getValueType() == MVT::i32)
9041         ++NumOfBitCastedElts;
9042     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9043       // Constants are statically casted, thus do not count them as
9044       // relevant operands.
9045       --NumOfRelevantElts;
9046   }
9047
9048   // Check if more than half of the elements require a non-free bitcast.
9049   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9050     return SDValue();
9051
9052   SelectionDAG &DAG = DCI.DAG;
9053   // Create the new vector type.
9054   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9055   // Check if the type is legal.
9056   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9057   if (!TLI.isTypeLegal(VecVT))
9058     return SDValue();
9059
9060   // Combine:
9061   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9062   // => BITCAST INSERT_VECTOR_ELT
9063   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9064   //                      (BITCAST EN), N.
9065   SDValue Vec = DAG.getUNDEF(VecVT);
9066   SDLoc dl(N);
9067   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9068     SDValue V = N->getOperand(Idx);
9069     if (V.getOpcode() == ISD::UNDEF)
9070       continue;
9071     if (V.getOpcode() == ISD::BITCAST &&
9072         V->getOperand(0).getValueType() == MVT::i32)
9073       // Fold obvious case.
9074       V = V.getOperand(0);
9075     else {
9076       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 
9077       // Make the DAGCombiner fold the bitcasts.
9078       DCI.AddToWorklist(V.getNode());
9079     }
9080     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
9081     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9082   }
9083   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9084   // Make the DAGCombiner fold the bitcasts.
9085   DCI.AddToWorklist(Vec.getNode());
9086   return Vec;
9087 }
9088
9089 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9090 /// ISD::INSERT_VECTOR_ELT.
9091 static SDValue PerformInsertEltCombine(SDNode *N,
9092                                        TargetLowering::DAGCombinerInfo &DCI) {
9093   // Bitcast an i64 load inserted into a vector to f64.
9094   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9095   EVT VT = N->getValueType(0);
9096   SDNode *Elt = N->getOperand(1).getNode();
9097   if (VT.getVectorElementType() != MVT::i64 ||
9098       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9099     return SDValue();
9100
9101   SelectionDAG &DAG = DCI.DAG;
9102   SDLoc dl(N);
9103   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9104                                  VT.getVectorNumElements());
9105   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9106   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9107   // Make the DAGCombiner fold the bitcasts.
9108   DCI.AddToWorklist(Vec.getNode());
9109   DCI.AddToWorklist(V.getNode());
9110   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9111                                Vec, V, N->getOperand(2));
9112   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9113 }
9114
9115 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9116 /// ISD::VECTOR_SHUFFLE.
9117 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9118   // The LLVM shufflevector instruction does not require the shuffle mask
9119   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9120   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
9121   // operands do not match the mask length, they are extended by concatenating
9122   // them with undef vectors.  That is probably the right thing for other
9123   // targets, but for NEON it is better to concatenate two double-register
9124   // size vector operands into a single quad-register size vector.  Do that
9125   // transformation here:
9126   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
9127   //   shuffle(concat(v1, v2), undef)
9128   SDValue Op0 = N->getOperand(0);
9129   SDValue Op1 = N->getOperand(1);
9130   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9131       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9132       Op0.getNumOperands() != 2 ||
9133       Op1.getNumOperands() != 2)
9134     return SDValue();
9135   SDValue Concat0Op1 = Op0.getOperand(1);
9136   SDValue Concat1Op1 = Op1.getOperand(1);
9137   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9138       Concat1Op1.getOpcode() != ISD::UNDEF)
9139     return SDValue();
9140   // Skip the transformation if any of the types are illegal.
9141   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9142   EVT VT = N->getValueType(0);
9143   if (!TLI.isTypeLegal(VT) ||
9144       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9145       !TLI.isTypeLegal(Concat1Op1.getValueType()))
9146     return SDValue();
9147
9148   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9149                                   Op0.getOperand(0), Op1.getOperand(0));
9150   // Translate the shuffle mask.
9151   SmallVector<int, 16> NewMask;
9152   unsigned NumElts = VT.getVectorNumElements();
9153   unsigned HalfElts = NumElts/2;
9154   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9155   for (unsigned n = 0; n < NumElts; ++n) {
9156     int MaskElt = SVN->getMaskElt(n);
9157     int NewElt = -1;
9158     if (MaskElt < (int)HalfElts)
9159       NewElt = MaskElt;
9160     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9161       NewElt = HalfElts + MaskElt - NumElts;
9162     NewMask.push_back(NewElt);
9163   }
9164   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9165                               DAG.getUNDEF(VT), NewMask.data());
9166 }
9167
9168 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
9169 /// NEON load/store intrinsics to merge base address updates.
9170 static SDValue CombineBaseUpdate(SDNode *N,
9171                                  TargetLowering::DAGCombinerInfo &DCI) {
9172   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9173     return SDValue();
9174
9175   SelectionDAG &DAG = DCI.DAG;
9176   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9177                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9178   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
9179   SDValue Addr = N->getOperand(AddrOpIdx);
9180
9181   // Search for a use of the address operand that is an increment.
9182   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9183          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9184     SDNode *User = *UI;
9185     if (User->getOpcode() != ISD::ADD ||
9186         UI.getUse().getResNo() != Addr.getResNo())
9187       continue;
9188
9189     // Check that the add is independent of the load/store.  Otherwise, folding
9190     // it would create a cycle.
9191     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9192       continue;
9193
9194     // Find the new opcode for the updating load/store.
9195     bool isLoad = true;
9196     bool isLaneOp = false;
9197     unsigned NewOpc = 0;
9198     unsigned NumVecs = 0;
9199     if (isIntrinsic) {
9200       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9201       switch (IntNo) {
9202       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9203       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9204         NumVecs = 1; break;
9205       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9206         NumVecs = 2; break;
9207       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9208         NumVecs = 3; break;
9209       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9210         NumVecs = 4; break;
9211       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9212         NumVecs = 2; isLaneOp = true; break;
9213       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9214         NumVecs = 3; isLaneOp = true; break;
9215       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9216         NumVecs = 4; isLaneOp = true; break;
9217       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9218         NumVecs = 1; isLoad = false; break;
9219       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9220         NumVecs = 2; isLoad = false; break;
9221       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9222         NumVecs = 3; isLoad = false; break;
9223       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9224         NumVecs = 4; isLoad = false; break;
9225       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9226         NumVecs = 2; isLoad = false; isLaneOp = true; break;
9227       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9228         NumVecs = 3; isLoad = false; isLaneOp = true; break;
9229       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9230         NumVecs = 4; isLoad = false; isLaneOp = true; break;
9231       }
9232     } else {
9233       isLaneOp = true;
9234       switch (N->getOpcode()) {
9235       default: llvm_unreachable("unexpected opcode for Neon base update");
9236       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9237       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9238       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9239       }
9240     }
9241
9242     // Find the size of memory referenced by the load/store.
9243     EVT VecTy;
9244     if (isLoad)
9245       VecTy = N->getValueType(0);
9246     else
9247       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9248     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9249     if (isLaneOp)
9250       NumBytes /= VecTy.getVectorNumElements();
9251
9252     // If the increment is a constant, it must match the memory ref size.
9253     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9254     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9255       uint64_t IncVal = CInc->getZExtValue();
9256       if (IncVal != NumBytes)
9257         continue;
9258     } else if (NumBytes >= 3 * 16) {
9259       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9260       // separate instructions that make it harder to use a non-constant update.
9261       continue;
9262     }
9263
9264     // Create the new updating load/store node.
9265     EVT Tys[6];
9266     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
9267     unsigned n;
9268     for (n = 0; n < NumResultVecs; ++n)
9269       Tys[n] = VecTy;
9270     Tys[n++] = MVT::i32;
9271     Tys[n] = MVT::Other;
9272     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
9273     SmallVector<SDValue, 8> Ops;
9274     Ops.push_back(N->getOperand(0)); // incoming chain
9275     Ops.push_back(N->getOperand(AddrOpIdx));
9276     Ops.push_back(Inc);
9277     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
9278       Ops.push_back(N->getOperand(i));
9279     }
9280     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9281     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9282                                            Ops.data(), Ops.size(),
9283                                            MemInt->getMemoryVT(),
9284                                            MemInt->getMemOperand());
9285
9286     // Update the uses.
9287     std::vector<SDValue> NewResults;
9288     for (unsigned i = 0; i < NumResultVecs; ++i) {
9289       NewResults.push_back(SDValue(UpdN.getNode(), i));
9290     }
9291     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9292     DCI.CombineTo(N, NewResults);
9293     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9294
9295     break;
9296   }
9297   return SDValue();
9298 }
9299
9300 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9301 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9302 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9303 /// return true.
9304 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9305   SelectionDAG &DAG = DCI.DAG;
9306   EVT VT = N->getValueType(0);
9307   // vldN-dup instructions only support 64-bit vectors for N > 1.
9308   if (!VT.is64BitVector())
9309     return false;
9310
9311   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9312   SDNode *VLD = N->getOperand(0).getNode();
9313   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9314     return false;
9315   unsigned NumVecs = 0;
9316   unsigned NewOpc = 0;
9317   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9318   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9319     NumVecs = 2;
9320     NewOpc = ARMISD::VLD2DUP;
9321   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9322     NumVecs = 3;
9323     NewOpc = ARMISD::VLD3DUP;
9324   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9325     NumVecs = 4;
9326     NewOpc = ARMISD::VLD4DUP;
9327   } else {
9328     return false;
9329   }
9330
9331   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9332   // numbers match the load.
9333   unsigned VLDLaneNo =
9334     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9335   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9336        UI != UE; ++UI) {
9337     // Ignore uses of the chain result.
9338     if (UI.getUse().getResNo() == NumVecs)
9339       continue;
9340     SDNode *User = *UI;
9341     if (User->getOpcode() != ARMISD::VDUPLANE ||
9342         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9343       return false;
9344   }
9345
9346   // Create the vldN-dup node.
9347   EVT Tys[5];
9348   unsigned n;
9349   for (n = 0; n < NumVecs; ++n)
9350     Tys[n] = VT;
9351   Tys[n] = MVT::Other;
9352   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
9353   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9354   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9355   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9356                                            Ops, 2, VLDMemInt->getMemoryVT(),
9357                                            VLDMemInt->getMemOperand());
9358
9359   // Update the uses.
9360   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9361        UI != UE; ++UI) {
9362     unsigned ResNo = UI.getUse().getResNo();
9363     // Ignore uses of the chain result.
9364     if (ResNo == NumVecs)
9365       continue;
9366     SDNode *User = *UI;
9367     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9368   }
9369
9370   // Now the vldN-lane intrinsic is dead except for its chain result.
9371   // Update uses of the chain.
9372   std::vector<SDValue> VLDDupResults;
9373   for (unsigned n = 0; n < NumVecs; ++n)
9374     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9375   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9376   DCI.CombineTo(VLD, VLDDupResults);
9377
9378   return true;
9379 }
9380
9381 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9382 /// ARMISD::VDUPLANE.
9383 static SDValue PerformVDUPLANECombine(SDNode *N,
9384                                       TargetLowering::DAGCombinerInfo &DCI) {
9385   SDValue Op = N->getOperand(0);
9386
9387   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9388   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9389   if (CombineVLDDUP(N, DCI))
9390     return SDValue(N, 0);
9391
9392   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9393   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9394   while (Op.getOpcode() == ISD::BITCAST)
9395     Op = Op.getOperand(0);
9396   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9397     return SDValue();
9398
9399   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9400   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9401   // The canonical VMOV for a zero vector uses a 32-bit element size.
9402   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9403   unsigned EltBits;
9404   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9405     EltSize = 8;
9406   EVT VT = N->getValueType(0);
9407   if (EltSize > VT.getVectorElementType().getSizeInBits())
9408     return SDValue();
9409
9410   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9411 }
9412
9413 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9414 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9415 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9416 {
9417   integerPart cN;
9418   integerPart c0 = 0;
9419   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9420        I != E; I++) {
9421     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9422     if (!C)
9423       return false;
9424
9425     bool isExact;
9426     APFloat APF = C->getValueAPF();
9427     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9428         != APFloat::opOK || !isExact)
9429       return false;
9430
9431     c0 = (I == 0) ? cN : c0;
9432     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9433       return false;
9434   }
9435   C = c0;
9436   return true;
9437 }
9438
9439 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9440 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9441 /// when the VMUL has a constant operand that is a power of 2.
9442 ///
9443 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9444 ///  vmul.f32        d16, d17, d16
9445 ///  vcvt.s32.f32    d16, d16
9446 /// becomes:
9447 ///  vcvt.s32.f32    d16, d16, #3
9448 static SDValue PerformVCVTCombine(SDNode *N,
9449                                   TargetLowering::DAGCombinerInfo &DCI,
9450                                   const ARMSubtarget *Subtarget) {
9451   SelectionDAG &DAG = DCI.DAG;
9452   SDValue Op = N->getOperand(0);
9453
9454   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9455       Op.getOpcode() != ISD::FMUL)
9456     return SDValue();
9457
9458   uint64_t C;
9459   SDValue N0 = Op->getOperand(0);
9460   SDValue ConstVec = Op->getOperand(1);
9461   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9462
9463   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9464       !isConstVecPow2(ConstVec, isSigned, C))
9465     return SDValue();
9466
9467   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9468   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9469   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9470     // These instructions only exist converting from f32 to i32. We can handle
9471     // smaller integers by generating an extra truncate, but larger ones would
9472     // be lossy.
9473     return SDValue();
9474   }
9475
9476   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9477     Intrinsic::arm_neon_vcvtfp2fxu;
9478   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9479   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9480                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9481                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9482                                  DAG.getConstant(Log2_64(C), MVT::i32));
9483
9484   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9485     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9486
9487   return FixConv;
9488 }
9489
9490 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9491 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9492 /// when the VDIV has a constant operand that is a power of 2.
9493 ///
9494 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9495 ///  vcvt.f32.s32    d16, d16
9496 ///  vdiv.f32        d16, d17, d16
9497 /// becomes:
9498 ///  vcvt.f32.s32    d16, d16, #3
9499 static SDValue PerformVDIVCombine(SDNode *N,
9500                                   TargetLowering::DAGCombinerInfo &DCI,
9501                                   const ARMSubtarget *Subtarget) {
9502   SelectionDAG &DAG = DCI.DAG;
9503   SDValue Op = N->getOperand(0);
9504   unsigned OpOpcode = Op.getNode()->getOpcode();
9505
9506   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9507       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9508     return SDValue();
9509
9510   uint64_t C;
9511   SDValue ConstVec = N->getOperand(1);
9512   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9513
9514   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9515       !isConstVecPow2(ConstVec, isSigned, C))
9516     return SDValue();
9517
9518   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9519   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9520   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9521     // These instructions only exist converting from i32 to f32. We can handle
9522     // smaller integers by generating an extra extend, but larger ones would
9523     // be lossy.
9524     return SDValue();
9525   }
9526
9527   SDValue ConvInput = Op.getOperand(0);
9528   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9529   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9530     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9531                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9532                             ConvInput);
9533
9534   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9535     Intrinsic::arm_neon_vcvtfxu2fp;
9536   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9537                      Op.getValueType(),
9538                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9539                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9540 }
9541
9542 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9543 /// operand of a vector shift operation, where all the elements of the
9544 /// build_vector must have the same constant integer value.
9545 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9546   // Ignore bit_converts.
9547   while (Op.getOpcode() == ISD::BITCAST)
9548     Op = Op.getOperand(0);
9549   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9550   APInt SplatBits, SplatUndef;
9551   unsigned SplatBitSize;
9552   bool HasAnyUndefs;
9553   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9554                                       HasAnyUndefs, ElementBits) ||
9555       SplatBitSize > ElementBits)
9556     return false;
9557   Cnt = SplatBits.getSExtValue();
9558   return true;
9559 }
9560
9561 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9562 /// operand of a vector shift left operation.  That value must be in the range:
9563 ///   0 <= Value < ElementBits for a left shift; or
9564 ///   0 <= Value <= ElementBits for a long left shift.
9565 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9566   assert(VT.isVector() && "vector shift count is not a vector type");
9567   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9568   if (! getVShiftImm(Op, ElementBits, Cnt))
9569     return false;
9570   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9571 }
9572
9573 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9574 /// operand of a vector shift right operation.  For a shift opcode, the value
9575 /// is positive, but for an intrinsic the value count must be negative. The
9576 /// absolute value must be in the range:
9577 ///   1 <= |Value| <= ElementBits for a right shift; or
9578 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9579 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9580                          int64_t &Cnt) {
9581   assert(VT.isVector() && "vector shift count is not a vector type");
9582   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9583   if (! getVShiftImm(Op, ElementBits, Cnt))
9584     return false;
9585   if (isIntrinsic)
9586     Cnt = -Cnt;
9587   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9588 }
9589
9590 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9591 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9592   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9593   switch (IntNo) {
9594   default:
9595     // Don't do anything for most intrinsics.
9596     break;
9597
9598   // Vector shifts: check for immediate versions and lower them.
9599   // Note: This is done during DAG combining instead of DAG legalizing because
9600   // the build_vectors for 64-bit vector element shift counts are generally
9601   // not legal, and it is hard to see their values after they get legalized to
9602   // loads from a constant pool.
9603   case Intrinsic::arm_neon_vshifts:
9604   case Intrinsic::arm_neon_vshiftu:
9605   case Intrinsic::arm_neon_vshiftls:
9606   case Intrinsic::arm_neon_vshiftlu:
9607   case Intrinsic::arm_neon_vshiftn:
9608   case Intrinsic::arm_neon_vrshifts:
9609   case Intrinsic::arm_neon_vrshiftu:
9610   case Intrinsic::arm_neon_vrshiftn:
9611   case Intrinsic::arm_neon_vqshifts:
9612   case Intrinsic::arm_neon_vqshiftu:
9613   case Intrinsic::arm_neon_vqshiftsu:
9614   case Intrinsic::arm_neon_vqshiftns:
9615   case Intrinsic::arm_neon_vqshiftnu:
9616   case Intrinsic::arm_neon_vqshiftnsu:
9617   case Intrinsic::arm_neon_vqrshiftns:
9618   case Intrinsic::arm_neon_vqrshiftnu:
9619   case Intrinsic::arm_neon_vqrshiftnsu: {
9620     EVT VT = N->getOperand(1).getValueType();
9621     int64_t Cnt;
9622     unsigned VShiftOpc = 0;
9623
9624     switch (IntNo) {
9625     case Intrinsic::arm_neon_vshifts:
9626     case Intrinsic::arm_neon_vshiftu:
9627       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9628         VShiftOpc = ARMISD::VSHL;
9629         break;
9630       }
9631       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9632         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9633                      ARMISD::VSHRs : ARMISD::VSHRu);
9634         break;
9635       }
9636       return SDValue();
9637
9638     case Intrinsic::arm_neon_vshiftls:
9639     case Intrinsic::arm_neon_vshiftlu:
9640       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
9641         break;
9642       llvm_unreachable("invalid shift count for vshll intrinsic");
9643
9644     case Intrinsic::arm_neon_vrshifts:
9645     case Intrinsic::arm_neon_vrshiftu:
9646       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9647         break;
9648       return SDValue();
9649
9650     case Intrinsic::arm_neon_vqshifts:
9651     case Intrinsic::arm_neon_vqshiftu:
9652       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9653         break;
9654       return SDValue();
9655
9656     case Intrinsic::arm_neon_vqshiftsu:
9657       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9658         break;
9659       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9660
9661     case Intrinsic::arm_neon_vshiftn:
9662     case Intrinsic::arm_neon_vrshiftn:
9663     case Intrinsic::arm_neon_vqshiftns:
9664     case Intrinsic::arm_neon_vqshiftnu:
9665     case Intrinsic::arm_neon_vqshiftnsu:
9666     case Intrinsic::arm_neon_vqrshiftns:
9667     case Intrinsic::arm_neon_vqrshiftnu:
9668     case Intrinsic::arm_neon_vqrshiftnsu:
9669       // Narrowing shifts require an immediate right shift.
9670       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9671         break;
9672       llvm_unreachable("invalid shift count for narrowing vector shift "
9673                        "intrinsic");
9674
9675     default:
9676       llvm_unreachable("unhandled vector shift");
9677     }
9678
9679     switch (IntNo) {
9680     case Intrinsic::arm_neon_vshifts:
9681     case Intrinsic::arm_neon_vshiftu:
9682       // Opcode already set above.
9683       break;
9684     case Intrinsic::arm_neon_vshiftls:
9685     case Intrinsic::arm_neon_vshiftlu:
9686       if (Cnt == VT.getVectorElementType().getSizeInBits())
9687         VShiftOpc = ARMISD::VSHLLi;
9688       else
9689         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
9690                      ARMISD::VSHLLs : ARMISD::VSHLLu);
9691       break;
9692     case Intrinsic::arm_neon_vshiftn:
9693       VShiftOpc = ARMISD::VSHRN; break;
9694     case Intrinsic::arm_neon_vrshifts:
9695       VShiftOpc = ARMISD::VRSHRs; break;
9696     case Intrinsic::arm_neon_vrshiftu:
9697       VShiftOpc = ARMISD::VRSHRu; break;
9698     case Intrinsic::arm_neon_vrshiftn:
9699       VShiftOpc = ARMISD::VRSHRN; break;
9700     case Intrinsic::arm_neon_vqshifts:
9701       VShiftOpc = ARMISD::VQSHLs; break;
9702     case Intrinsic::arm_neon_vqshiftu:
9703       VShiftOpc = ARMISD::VQSHLu; break;
9704     case Intrinsic::arm_neon_vqshiftsu:
9705       VShiftOpc = ARMISD::VQSHLsu; break;
9706     case Intrinsic::arm_neon_vqshiftns:
9707       VShiftOpc = ARMISD::VQSHRNs; break;
9708     case Intrinsic::arm_neon_vqshiftnu:
9709       VShiftOpc = ARMISD::VQSHRNu; break;
9710     case Intrinsic::arm_neon_vqshiftnsu:
9711       VShiftOpc = ARMISD::VQSHRNsu; break;
9712     case Intrinsic::arm_neon_vqrshiftns:
9713       VShiftOpc = ARMISD::VQRSHRNs; break;
9714     case Intrinsic::arm_neon_vqrshiftnu:
9715       VShiftOpc = ARMISD::VQRSHRNu; break;
9716     case Intrinsic::arm_neon_vqrshiftnsu:
9717       VShiftOpc = ARMISD::VQRSHRNsu; break;
9718     }
9719
9720     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9721                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9722   }
9723
9724   case Intrinsic::arm_neon_vshiftins: {
9725     EVT VT = N->getOperand(1).getValueType();
9726     int64_t Cnt;
9727     unsigned VShiftOpc = 0;
9728
9729     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9730       VShiftOpc = ARMISD::VSLI;
9731     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9732       VShiftOpc = ARMISD::VSRI;
9733     else {
9734       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9735     }
9736
9737     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9738                        N->getOperand(1), N->getOperand(2),
9739                        DAG.getConstant(Cnt, MVT::i32));
9740   }
9741
9742   case Intrinsic::arm_neon_vqrshifts:
9743   case Intrinsic::arm_neon_vqrshiftu:
9744     // No immediate versions of these to check for.
9745     break;
9746   }
9747
9748   return SDValue();
9749 }
9750
9751 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9752 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9753 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9754 /// vector element shift counts are generally not legal, and it is hard to see
9755 /// their values after they get legalized to loads from a constant pool.
9756 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9757                                    const ARMSubtarget *ST) {
9758   EVT VT = N->getValueType(0);
9759   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9760     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9761     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9762     SDValue N1 = N->getOperand(1);
9763     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9764       SDValue N0 = N->getOperand(0);
9765       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9766           DAG.MaskedValueIsZero(N0.getOperand(0),
9767                                 APInt::getHighBitsSet(32, 16)))
9768         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9769     }
9770   }
9771
9772   // Nothing to be done for scalar shifts.
9773   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9774   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9775     return SDValue();
9776
9777   assert(ST->hasNEON() && "unexpected vector shift");
9778   int64_t Cnt;
9779
9780   switch (N->getOpcode()) {
9781   default: llvm_unreachable("unexpected shift opcode");
9782
9783   case ISD::SHL:
9784     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9785       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9786                          DAG.getConstant(Cnt, MVT::i32));
9787     break;
9788
9789   case ISD::SRA:
9790   case ISD::SRL:
9791     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9792       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9793                             ARMISD::VSHRs : ARMISD::VSHRu);
9794       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9795                          DAG.getConstant(Cnt, MVT::i32));
9796     }
9797   }
9798   return SDValue();
9799 }
9800
9801 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9802 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9803 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9804                                     const ARMSubtarget *ST) {
9805   SDValue N0 = N->getOperand(0);
9806
9807   // Check for sign- and zero-extensions of vector extract operations of 8-
9808   // and 16-bit vector elements.  NEON supports these directly.  They are
9809   // handled during DAG combining because type legalization will promote them
9810   // to 32-bit types and it is messy to recognize the operations after that.
9811   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9812     SDValue Vec = N0.getOperand(0);
9813     SDValue Lane = N0.getOperand(1);
9814     EVT VT = N->getValueType(0);
9815     EVT EltVT = N0.getValueType();
9816     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9817
9818     if (VT == MVT::i32 &&
9819         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9820         TLI.isTypeLegal(Vec.getValueType()) &&
9821         isa<ConstantSDNode>(Lane)) {
9822
9823       unsigned Opc = 0;
9824       switch (N->getOpcode()) {
9825       default: llvm_unreachable("unexpected opcode");
9826       case ISD::SIGN_EXTEND:
9827         Opc = ARMISD::VGETLANEs;
9828         break;
9829       case ISD::ZERO_EXTEND:
9830       case ISD::ANY_EXTEND:
9831         Opc = ARMISD::VGETLANEu;
9832         break;
9833       }
9834       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9835     }
9836   }
9837
9838   return SDValue();
9839 }
9840
9841 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9842 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9843 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9844                                        const ARMSubtarget *ST) {
9845   // If the target supports NEON, try to use vmax/vmin instructions for f32
9846   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9847   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9848   // a NaN; only do the transformation when it matches that behavior.
9849
9850   // For now only do this when using NEON for FP operations; if using VFP, it
9851   // is not obvious that the benefit outweighs the cost of switching to the
9852   // NEON pipeline.
9853   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9854       N->getValueType(0) != MVT::f32)
9855     return SDValue();
9856
9857   SDValue CondLHS = N->getOperand(0);
9858   SDValue CondRHS = N->getOperand(1);
9859   SDValue LHS = N->getOperand(2);
9860   SDValue RHS = N->getOperand(3);
9861   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9862
9863   unsigned Opcode = 0;
9864   bool IsReversed;
9865   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9866     IsReversed = false; // x CC y ? x : y
9867   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9868     IsReversed = true ; // x CC y ? y : x
9869   } else {
9870     return SDValue();
9871   }
9872
9873   bool IsUnordered;
9874   switch (CC) {
9875   default: break;
9876   case ISD::SETOLT:
9877   case ISD::SETOLE:
9878   case ISD::SETLT:
9879   case ISD::SETLE:
9880   case ISD::SETULT:
9881   case ISD::SETULE:
9882     // If LHS is NaN, an ordered comparison will be false and the result will
9883     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9884     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9885     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9886     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9887       break;
9888     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9889     // will return -0, so vmin can only be used for unsafe math or if one of
9890     // the operands is known to be nonzero.
9891     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9892         !DAG.getTarget().Options.UnsafeFPMath &&
9893         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9894       break;
9895     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9896     break;
9897
9898   case ISD::SETOGT:
9899   case ISD::SETOGE:
9900   case ISD::SETGT:
9901   case ISD::SETGE:
9902   case ISD::SETUGT:
9903   case ISD::SETUGE:
9904     // If LHS is NaN, an ordered comparison will be false and the result will
9905     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9906     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9907     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9908     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9909       break;
9910     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9911     // will return +0, so vmax can only be used for unsafe math or if one of
9912     // the operands is known to be nonzero.
9913     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9914         !DAG.getTarget().Options.UnsafeFPMath &&
9915         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9916       break;
9917     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9918     break;
9919   }
9920
9921   if (!Opcode)
9922     return SDValue();
9923   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9924 }
9925
9926 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9927 SDValue
9928 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9929   SDValue Cmp = N->getOperand(4);
9930   if (Cmp.getOpcode() != ARMISD::CMPZ)
9931     // Only looking at EQ and NE cases.
9932     return SDValue();
9933
9934   EVT VT = N->getValueType(0);
9935   SDLoc dl(N);
9936   SDValue LHS = Cmp.getOperand(0);
9937   SDValue RHS = Cmp.getOperand(1);
9938   SDValue FalseVal = N->getOperand(0);
9939   SDValue TrueVal = N->getOperand(1);
9940   SDValue ARMcc = N->getOperand(2);
9941   ARMCC::CondCodes CC =
9942     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9943
9944   // Simplify
9945   //   mov     r1, r0
9946   //   cmp     r1, x
9947   //   mov     r0, y
9948   //   moveq   r0, x
9949   // to
9950   //   cmp     r0, x
9951   //   movne   r0, y
9952   //
9953   //   mov     r1, r0
9954   //   cmp     r1, x
9955   //   mov     r0, x
9956   //   movne   r0, y
9957   // to
9958   //   cmp     r0, x
9959   //   movne   r0, y
9960   /// FIXME: Turn this into a target neutral optimization?
9961   SDValue Res;
9962   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9963     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9964                       N->getOperand(3), Cmp);
9965   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9966     SDValue ARMcc;
9967     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9968     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9969                       N->getOperand(3), NewCmp);
9970   }
9971
9972   if (Res.getNode()) {
9973     APInt KnownZero, KnownOne;
9974     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
9975     // Capture demanded bits information that would be otherwise lost.
9976     if (KnownZero == 0xfffffffe)
9977       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9978                         DAG.getValueType(MVT::i1));
9979     else if (KnownZero == 0xffffff00)
9980       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9981                         DAG.getValueType(MVT::i8));
9982     else if (KnownZero == 0xffff0000)
9983       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9984                         DAG.getValueType(MVT::i16));
9985   }
9986
9987   return Res;
9988 }
9989
9990 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9991                                              DAGCombinerInfo &DCI) const {
9992   switch (N->getOpcode()) {
9993   default: break;
9994   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9995   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9996   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9997   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9998   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9999   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
10000   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
10001   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
10002   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
10003   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10004   case ISD::STORE:      return PerformSTORECombine(N, DCI);
10005   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
10006   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10007   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10008   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10009   case ISD::FP_TO_SINT:
10010   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10011   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
10012   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10013   case ISD::SHL:
10014   case ISD::SRA:
10015   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10016   case ISD::SIGN_EXTEND:
10017   case ISD::ZERO_EXTEND:
10018   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10019   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
10020   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10021   case ARMISD::VLD2DUP:
10022   case ARMISD::VLD3DUP:
10023   case ARMISD::VLD4DUP:
10024     return CombineBaseUpdate(N, DCI);
10025   case ARMISD::BUILD_VECTOR:
10026     return PerformARMBUILD_VECTORCombine(N, DCI);
10027   case ISD::INTRINSIC_VOID:
10028   case ISD::INTRINSIC_W_CHAIN:
10029     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10030     case Intrinsic::arm_neon_vld1:
10031     case Intrinsic::arm_neon_vld2:
10032     case Intrinsic::arm_neon_vld3:
10033     case Intrinsic::arm_neon_vld4:
10034     case Intrinsic::arm_neon_vld2lane:
10035     case Intrinsic::arm_neon_vld3lane:
10036     case Intrinsic::arm_neon_vld4lane:
10037     case Intrinsic::arm_neon_vst1:
10038     case Intrinsic::arm_neon_vst2:
10039     case Intrinsic::arm_neon_vst3:
10040     case Intrinsic::arm_neon_vst4:
10041     case Intrinsic::arm_neon_vst2lane:
10042     case Intrinsic::arm_neon_vst3lane:
10043     case Intrinsic::arm_neon_vst4lane:
10044       return CombineBaseUpdate(N, DCI);
10045     default: break;
10046     }
10047     break;
10048   }
10049   return SDValue();
10050 }
10051
10052 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10053                                                           EVT VT) const {
10054   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10055 }
10056
10057 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
10058   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10059   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10060
10061   switch (VT.getSimpleVT().SimpleTy) {
10062   default:
10063     return false;
10064   case MVT::i8:
10065   case MVT::i16:
10066   case MVT::i32: {
10067     // Unaligned access can use (for example) LRDB, LRDH, LDR
10068     if (AllowsUnaligned) {
10069       if (Fast)
10070         *Fast = Subtarget->hasV7Ops();
10071       return true;
10072     }
10073     return false;
10074   }
10075   case MVT::f64:
10076   case MVT::v2f64: {
10077     // For any little-endian targets with neon, we can support unaligned ld/st
10078     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10079     // A big-endian target may also explictly support unaligned accesses
10080     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
10081       if (Fast)
10082         *Fast = true;
10083       return true;
10084     }
10085     return false;
10086   }
10087   }
10088 }
10089
10090 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10091                        unsigned AlignCheck) {
10092   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10093           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10094 }
10095
10096 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10097                                            unsigned DstAlign, unsigned SrcAlign,
10098                                            bool IsMemset, bool ZeroMemset,
10099                                            bool MemcpyStrSrc,
10100                                            MachineFunction &MF) const {
10101   const Function *F = MF.getFunction();
10102
10103   // See if we can use NEON instructions for this...
10104   if ((!IsMemset || ZeroMemset) &&
10105       Subtarget->hasNEON() &&
10106       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
10107                                        Attribute::NoImplicitFloat)) {
10108     bool Fast;
10109     if (Size >= 16 &&
10110         (memOpAlign(SrcAlign, DstAlign, 16) ||
10111          (allowsUnalignedMemoryAccesses(MVT::v2f64, &Fast) && Fast))) {
10112       return MVT::v2f64;
10113     } else if (Size >= 8 &&
10114                (memOpAlign(SrcAlign, DstAlign, 8) ||
10115                 (allowsUnalignedMemoryAccesses(MVT::f64, &Fast) && Fast))) {
10116       return MVT::f64;
10117     }
10118   }
10119
10120   // Lowering to i32/i16 if the size permits.
10121   if (Size >= 4)
10122     return MVT::i32;
10123   else if (Size >= 2)
10124     return MVT::i16;
10125
10126   // Let the target-independent logic figure it out.
10127   return MVT::Other;
10128 }
10129
10130 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10131   if (Val.getOpcode() != ISD::LOAD)
10132     return false;
10133
10134   EVT VT1 = Val.getValueType();
10135   if (!VT1.isSimple() || !VT1.isInteger() ||
10136       !VT2.isSimple() || !VT2.isInteger())
10137     return false;
10138
10139   switch (VT1.getSimpleVT().SimpleTy) {
10140   default: break;
10141   case MVT::i1:
10142   case MVT::i8:
10143   case MVT::i16:
10144     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10145     return true;
10146   }
10147
10148   return false;
10149 }
10150
10151 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10152   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10153     return false;
10154
10155   if (!isTypeLegal(EVT::getEVT(Ty1)))
10156     return false;
10157
10158   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10159
10160   // Assuming the caller doesn't have a zeroext or signext return parameter,
10161   // truncation all the way down to i1 is valid.
10162   return true;
10163 }
10164
10165
10166 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10167   if (V < 0)
10168     return false;
10169
10170   unsigned Scale = 1;
10171   switch (VT.getSimpleVT().SimpleTy) {
10172   default: return false;
10173   case MVT::i1:
10174   case MVT::i8:
10175     // Scale == 1;
10176     break;
10177   case MVT::i16:
10178     // Scale == 2;
10179     Scale = 2;
10180     break;
10181   case MVT::i32:
10182     // Scale == 4;
10183     Scale = 4;
10184     break;
10185   }
10186
10187   if ((V & (Scale - 1)) != 0)
10188     return false;
10189   V /= Scale;
10190   return V == (V & ((1LL << 5) - 1));
10191 }
10192
10193 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10194                                       const ARMSubtarget *Subtarget) {
10195   bool isNeg = false;
10196   if (V < 0) {
10197     isNeg = true;
10198     V = - V;
10199   }
10200
10201   switch (VT.getSimpleVT().SimpleTy) {
10202   default: return false;
10203   case MVT::i1:
10204   case MVT::i8:
10205   case MVT::i16:
10206   case MVT::i32:
10207     // + imm12 or - imm8
10208     if (isNeg)
10209       return V == (V & ((1LL << 8) - 1));
10210     return V == (V & ((1LL << 12) - 1));
10211   case MVT::f32:
10212   case MVT::f64:
10213     // Same as ARM mode. FIXME: NEON?
10214     if (!Subtarget->hasVFP2())
10215       return false;
10216     if ((V & 3) != 0)
10217       return false;
10218     V >>= 2;
10219     return V == (V & ((1LL << 8) - 1));
10220   }
10221 }
10222
10223 /// isLegalAddressImmediate - Return true if the integer value can be used
10224 /// as the offset of the target addressing mode for load / store of the
10225 /// given type.
10226 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10227                                     const ARMSubtarget *Subtarget) {
10228   if (V == 0)
10229     return true;
10230
10231   if (!VT.isSimple())
10232     return false;
10233
10234   if (Subtarget->isThumb1Only())
10235     return isLegalT1AddressImmediate(V, VT);
10236   else if (Subtarget->isThumb2())
10237     return isLegalT2AddressImmediate(V, VT, Subtarget);
10238
10239   // ARM mode.
10240   if (V < 0)
10241     V = - V;
10242   switch (VT.getSimpleVT().SimpleTy) {
10243   default: return false;
10244   case MVT::i1:
10245   case MVT::i8:
10246   case MVT::i32:
10247     // +- imm12
10248     return V == (V & ((1LL << 12) - 1));
10249   case MVT::i16:
10250     // +- imm8
10251     return V == (V & ((1LL << 8) - 1));
10252   case MVT::f32:
10253   case MVT::f64:
10254     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10255       return false;
10256     if ((V & 3) != 0)
10257       return false;
10258     V >>= 2;
10259     return V == (V & ((1LL << 8) - 1));
10260   }
10261 }
10262
10263 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10264                                                       EVT VT) const {
10265   int Scale = AM.Scale;
10266   if (Scale < 0)
10267     return false;
10268
10269   switch (VT.getSimpleVT().SimpleTy) {
10270   default: return false;
10271   case MVT::i1:
10272   case MVT::i8:
10273   case MVT::i16:
10274   case MVT::i32:
10275     if (Scale == 1)
10276       return true;
10277     // r + r << imm
10278     Scale = Scale & ~1;
10279     return Scale == 2 || Scale == 4 || Scale == 8;
10280   case MVT::i64:
10281     // r + r
10282     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10283       return true;
10284     return false;
10285   case MVT::isVoid:
10286     // Note, we allow "void" uses (basically, uses that aren't loads or
10287     // stores), because arm allows folding a scale into many arithmetic
10288     // operations.  This should be made more precise and revisited later.
10289
10290     // Allow r << imm, but the imm has to be a multiple of two.
10291     if (Scale & 1) return false;
10292     return isPowerOf2_32(Scale);
10293   }
10294 }
10295
10296 /// isLegalAddressingMode - Return true if the addressing mode represented
10297 /// by AM is legal for this target, for a load/store of the specified type.
10298 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10299                                               Type *Ty) const {
10300   EVT VT = getValueType(Ty, true);
10301   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10302     return false;
10303
10304   // Can never fold addr of global into load/store.
10305   if (AM.BaseGV)
10306     return false;
10307
10308   switch (AM.Scale) {
10309   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10310     break;
10311   case 1:
10312     if (Subtarget->isThumb1Only())
10313       return false;
10314     // FALL THROUGH.
10315   default:
10316     // ARM doesn't support any R+R*scale+imm addr modes.
10317     if (AM.BaseOffs)
10318       return false;
10319
10320     if (!VT.isSimple())
10321       return false;
10322
10323     if (Subtarget->isThumb2())
10324       return isLegalT2ScaledAddressingMode(AM, VT);
10325
10326     int Scale = AM.Scale;
10327     switch (VT.getSimpleVT().SimpleTy) {
10328     default: return false;
10329     case MVT::i1:
10330     case MVT::i8:
10331     case MVT::i32:
10332       if (Scale < 0) Scale = -Scale;
10333       if (Scale == 1)
10334         return true;
10335       // r + r << imm
10336       return isPowerOf2_32(Scale & ~1);
10337     case MVT::i16:
10338     case MVT::i64:
10339       // r + r
10340       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10341         return true;
10342       return false;
10343
10344     case MVT::isVoid:
10345       // Note, we allow "void" uses (basically, uses that aren't loads or
10346       // stores), because arm allows folding a scale into many arithmetic
10347       // operations.  This should be made more precise and revisited later.
10348
10349       // Allow r << imm, but the imm has to be a multiple of two.
10350       if (Scale & 1) return false;
10351       return isPowerOf2_32(Scale);
10352     }
10353   }
10354   return true;
10355 }
10356
10357 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10358 /// icmp immediate, that is the target has icmp instructions which can compare
10359 /// a register against the immediate without having to materialize the
10360 /// immediate into a register.
10361 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10362   // Thumb2 and ARM modes can use cmn for negative immediates.
10363   if (!Subtarget->isThumb())
10364     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10365   if (Subtarget->isThumb2())
10366     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10367   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10368   return Imm >= 0 && Imm <= 255;
10369 }
10370
10371 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10372 /// *or sub* immediate, that is the target has add or sub instructions which can
10373 /// add a register with the immediate without having to materialize the
10374 /// immediate into a register.
10375 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10376   // Same encoding for add/sub, just flip the sign.
10377   int64_t AbsImm = llvm::abs64(Imm);
10378   if (!Subtarget->isThumb())
10379     return ARM_AM::getSOImmVal(AbsImm) != -1;
10380   if (Subtarget->isThumb2())
10381     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10382   // Thumb1 only has 8-bit unsigned immediate.
10383   return AbsImm >= 0 && AbsImm <= 255;
10384 }
10385
10386 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10387                                       bool isSEXTLoad, SDValue &Base,
10388                                       SDValue &Offset, bool &isInc,
10389                                       SelectionDAG &DAG) {
10390   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10391     return false;
10392
10393   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10394     // AddressingMode 3
10395     Base = Ptr->getOperand(0);
10396     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10397       int RHSC = (int)RHS->getZExtValue();
10398       if (RHSC < 0 && RHSC > -256) {
10399         assert(Ptr->getOpcode() == ISD::ADD);
10400         isInc = false;
10401         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10402         return true;
10403       }
10404     }
10405     isInc = (Ptr->getOpcode() == ISD::ADD);
10406     Offset = Ptr->getOperand(1);
10407     return true;
10408   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10409     // AddressingMode 2
10410     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10411       int RHSC = (int)RHS->getZExtValue();
10412       if (RHSC < 0 && RHSC > -0x1000) {
10413         assert(Ptr->getOpcode() == ISD::ADD);
10414         isInc = false;
10415         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10416         Base = Ptr->getOperand(0);
10417         return true;
10418       }
10419     }
10420
10421     if (Ptr->getOpcode() == ISD::ADD) {
10422       isInc = true;
10423       ARM_AM::ShiftOpc ShOpcVal=
10424         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10425       if (ShOpcVal != ARM_AM::no_shift) {
10426         Base = Ptr->getOperand(1);
10427         Offset = Ptr->getOperand(0);
10428       } else {
10429         Base = Ptr->getOperand(0);
10430         Offset = Ptr->getOperand(1);
10431       }
10432       return true;
10433     }
10434
10435     isInc = (Ptr->getOpcode() == ISD::ADD);
10436     Base = Ptr->getOperand(0);
10437     Offset = Ptr->getOperand(1);
10438     return true;
10439   }
10440
10441   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10442   return false;
10443 }
10444
10445 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10446                                      bool isSEXTLoad, SDValue &Base,
10447                                      SDValue &Offset, bool &isInc,
10448                                      SelectionDAG &DAG) {
10449   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10450     return false;
10451
10452   Base = Ptr->getOperand(0);
10453   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10454     int RHSC = (int)RHS->getZExtValue();
10455     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10456       assert(Ptr->getOpcode() == ISD::ADD);
10457       isInc = false;
10458       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10459       return true;
10460     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10461       isInc = Ptr->getOpcode() == ISD::ADD;
10462       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10463       return true;
10464     }
10465   }
10466
10467   return false;
10468 }
10469
10470 /// getPreIndexedAddressParts - returns true by value, base pointer and
10471 /// offset pointer and addressing mode by reference if the node's address
10472 /// can be legally represented as pre-indexed load / store address.
10473 bool
10474 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10475                                              SDValue &Offset,
10476                                              ISD::MemIndexedMode &AM,
10477                                              SelectionDAG &DAG) const {
10478   if (Subtarget->isThumb1Only())
10479     return false;
10480
10481   EVT VT;
10482   SDValue Ptr;
10483   bool isSEXTLoad = false;
10484   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10485     Ptr = LD->getBasePtr();
10486     VT  = LD->getMemoryVT();
10487     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10488   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10489     Ptr = ST->getBasePtr();
10490     VT  = ST->getMemoryVT();
10491   } else
10492     return false;
10493
10494   bool isInc;
10495   bool isLegal = false;
10496   if (Subtarget->isThumb2())
10497     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10498                                        Offset, isInc, DAG);
10499   else
10500     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10501                                         Offset, isInc, DAG);
10502   if (!isLegal)
10503     return false;
10504
10505   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10506   return true;
10507 }
10508
10509 /// getPostIndexedAddressParts - returns true by value, base pointer and
10510 /// offset pointer and addressing mode by reference if this node can be
10511 /// combined with a load / store to form a post-indexed load / store.
10512 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10513                                                    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     VT  = LD->getMemoryVT();
10525     Ptr = LD->getBasePtr();
10526     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10527   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10528     VT  = ST->getMemoryVT();
10529     Ptr = ST->getBasePtr();
10530   } else
10531     return false;
10532
10533   bool isInc;
10534   bool isLegal = false;
10535   if (Subtarget->isThumb2())
10536     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10537                                        isInc, DAG);
10538   else
10539     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10540                                         isInc, DAG);
10541   if (!isLegal)
10542     return false;
10543
10544   if (Ptr != Base) {
10545     // Swap base ptr and offset to catch more post-index load / store when
10546     // it's legal. In Thumb2 mode, offset must be an immediate.
10547     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10548         !Subtarget->isThumb2())
10549       std::swap(Base, Offset);
10550
10551     // Post-indexed load / store update the base pointer.
10552     if (Ptr != Base)
10553       return false;
10554   }
10555
10556   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10557   return true;
10558 }
10559
10560 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10561                                                        APInt &KnownZero,
10562                                                        APInt &KnownOne,
10563                                                        const SelectionDAG &DAG,
10564                                                        unsigned Depth) const {
10565   unsigned BitWidth = KnownOne.getBitWidth();
10566   KnownZero = KnownOne = APInt(BitWidth, 0);
10567   switch (Op.getOpcode()) {
10568   default: break;
10569   case ARMISD::ADDC:
10570   case ARMISD::ADDE:
10571   case ARMISD::SUBC:
10572   case ARMISD::SUBE:
10573     // These nodes' second result is a boolean
10574     if (Op.getResNo() == 0)
10575       break;
10576     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10577     break;
10578   case ARMISD::CMOV: {
10579     // Bits are known zero/one if known on the LHS and RHS.
10580     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10581     if (KnownZero == 0 && KnownOne == 0) return;
10582
10583     APInt KnownZeroRHS, KnownOneRHS;
10584     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10585     KnownZero &= KnownZeroRHS;
10586     KnownOne  &= KnownOneRHS;
10587     return;
10588   }
10589   }
10590 }
10591
10592 //===----------------------------------------------------------------------===//
10593 //                           ARM Inline Assembly Support
10594 //===----------------------------------------------------------------------===//
10595
10596 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10597   // Looking for "rev" which is V6+.
10598   if (!Subtarget->hasV6Ops())
10599     return false;
10600
10601   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10602   std::string AsmStr = IA->getAsmString();
10603   SmallVector<StringRef, 4> AsmPieces;
10604   SplitString(AsmStr, AsmPieces, ";\n");
10605
10606   switch (AsmPieces.size()) {
10607   default: return false;
10608   case 1:
10609     AsmStr = AsmPieces[0];
10610     AsmPieces.clear();
10611     SplitString(AsmStr, AsmPieces, " \t,");
10612
10613     // rev $0, $1
10614     if (AsmPieces.size() == 3 &&
10615         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10616         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10617       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10618       if (Ty && Ty->getBitWidth() == 32)
10619         return IntrinsicLowering::LowerToByteSwap(CI);
10620     }
10621     break;
10622   }
10623
10624   return false;
10625 }
10626
10627 /// getConstraintType - Given a constraint letter, return the type of
10628 /// constraint it is for this target.
10629 ARMTargetLowering::ConstraintType
10630 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10631   if (Constraint.size() == 1) {
10632     switch (Constraint[0]) {
10633     default:  break;
10634     case 'l': return C_RegisterClass;
10635     case 'w': return C_RegisterClass;
10636     case 'h': return C_RegisterClass;
10637     case 'x': return C_RegisterClass;
10638     case 't': return C_RegisterClass;
10639     case 'j': return C_Other; // Constant for movw.
10640       // An address with a single base register. Due to the way we
10641       // currently handle addresses it is the same as an 'r' memory constraint.
10642     case 'Q': return C_Memory;
10643     }
10644   } else if (Constraint.size() == 2) {
10645     switch (Constraint[0]) {
10646     default: break;
10647     // All 'U+' constraints are addresses.
10648     case 'U': return C_Memory;
10649     }
10650   }
10651   return TargetLowering::getConstraintType(Constraint);
10652 }
10653
10654 /// Examine constraint type and operand type and determine a weight value.
10655 /// This object must already have been set up with the operand type
10656 /// and the current alternative constraint selected.
10657 TargetLowering::ConstraintWeight
10658 ARMTargetLowering::getSingleConstraintMatchWeight(
10659     AsmOperandInfo &info, const char *constraint) const {
10660   ConstraintWeight weight = CW_Invalid;
10661   Value *CallOperandVal = info.CallOperandVal;
10662     // If we don't have a value, we can't do a match,
10663     // but allow it at the lowest weight.
10664   if (CallOperandVal == NULL)
10665     return CW_Default;
10666   Type *type = CallOperandVal->getType();
10667   // Look at the constraint type.
10668   switch (*constraint) {
10669   default:
10670     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10671     break;
10672   case 'l':
10673     if (type->isIntegerTy()) {
10674       if (Subtarget->isThumb())
10675         weight = CW_SpecificReg;
10676       else
10677         weight = CW_Register;
10678     }
10679     break;
10680   case 'w':
10681     if (type->isFloatingPointTy())
10682       weight = CW_Register;
10683     break;
10684   }
10685   return weight;
10686 }
10687
10688 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10689 RCPair
10690 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10691                                                 MVT VT) const {
10692   if (Constraint.size() == 1) {
10693     // GCC ARM Constraint Letters
10694     switch (Constraint[0]) {
10695     case 'l': // Low regs or general regs.
10696       if (Subtarget->isThumb())
10697         return RCPair(0U, &ARM::tGPRRegClass);
10698       return RCPair(0U, &ARM::GPRRegClass);
10699     case 'h': // High regs or no regs.
10700       if (Subtarget->isThumb())
10701         return RCPair(0U, &ARM::hGPRRegClass);
10702       break;
10703     case 'r':
10704       return RCPair(0U, &ARM::GPRRegClass);
10705     case 'w':
10706       if (VT == MVT::f32)
10707         return RCPair(0U, &ARM::SPRRegClass);
10708       if (VT.getSizeInBits() == 64)
10709         return RCPair(0U, &ARM::DPRRegClass);
10710       if (VT.getSizeInBits() == 128)
10711         return RCPair(0U, &ARM::QPRRegClass);
10712       break;
10713     case 'x':
10714       if (VT == MVT::f32)
10715         return RCPair(0U, &ARM::SPR_8RegClass);
10716       if (VT.getSizeInBits() == 64)
10717         return RCPair(0U, &ARM::DPR_8RegClass);
10718       if (VT.getSizeInBits() == 128)
10719         return RCPair(0U, &ARM::QPR_8RegClass);
10720       break;
10721     case 't':
10722       if (VT == MVT::f32)
10723         return RCPair(0U, &ARM::SPRRegClass);
10724       break;
10725     }
10726   }
10727   if (StringRef("{cc}").equals_lower(Constraint))
10728     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10729
10730   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10731 }
10732
10733 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10734 /// vector.  If it is invalid, don't add anything to Ops.
10735 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10736                                                      std::string &Constraint,
10737                                                      std::vector<SDValue>&Ops,
10738                                                      SelectionDAG &DAG) const {
10739   SDValue Result(0, 0);
10740
10741   // Currently only support length 1 constraints.
10742   if (Constraint.length() != 1) return;
10743
10744   char ConstraintLetter = Constraint[0];
10745   switch (ConstraintLetter) {
10746   default: break;
10747   case 'j':
10748   case 'I': case 'J': case 'K': case 'L':
10749   case 'M': case 'N': case 'O':
10750     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10751     if (!C)
10752       return;
10753
10754     int64_t CVal64 = C->getSExtValue();
10755     int CVal = (int) CVal64;
10756     // None of these constraints allow values larger than 32 bits.  Check
10757     // that the value fits in an int.
10758     if (CVal != CVal64)
10759       return;
10760
10761     switch (ConstraintLetter) {
10762       case 'j':
10763         // Constant suitable for movw, must be between 0 and
10764         // 65535.
10765         if (Subtarget->hasV6T2Ops())
10766           if (CVal >= 0 && CVal <= 65535)
10767             break;
10768         return;
10769       case 'I':
10770         if (Subtarget->isThumb1Only()) {
10771           // This must be a constant between 0 and 255, for ADD
10772           // immediates.
10773           if (CVal >= 0 && CVal <= 255)
10774             break;
10775         } else if (Subtarget->isThumb2()) {
10776           // A constant that can be used as an immediate value in a
10777           // data-processing instruction.
10778           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10779             break;
10780         } else {
10781           // A constant that can be used as an immediate value in a
10782           // data-processing instruction.
10783           if (ARM_AM::getSOImmVal(CVal) != -1)
10784             break;
10785         }
10786         return;
10787
10788       case 'J':
10789         if (Subtarget->isThumb()) {  // FIXME thumb2
10790           // This must be a constant between -255 and -1, for negated ADD
10791           // immediates. This can be used in GCC with an "n" modifier that
10792           // prints the negated value, for use with SUB instructions. It is
10793           // not useful otherwise but is implemented for compatibility.
10794           if (CVal >= -255 && CVal <= -1)
10795             break;
10796         } else {
10797           // This must be a constant between -4095 and 4095. It is not clear
10798           // what this constraint is intended for. Implemented for
10799           // compatibility with GCC.
10800           if (CVal >= -4095 && CVal <= 4095)
10801             break;
10802         }
10803         return;
10804
10805       case 'K':
10806         if (Subtarget->isThumb1Only()) {
10807           // A 32-bit value where only one byte has a nonzero value. Exclude
10808           // zero to match GCC. This constraint is used by GCC internally for
10809           // constants that can be loaded with a move/shift combination.
10810           // It is not useful otherwise but is implemented for compatibility.
10811           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10812             break;
10813         } else if (Subtarget->isThumb2()) {
10814           // A constant whose bitwise inverse can be used as an immediate
10815           // value in a data-processing instruction. This can be used in GCC
10816           // with a "B" modifier that prints the inverted value, for use with
10817           // BIC and MVN instructions. It is not useful otherwise but is
10818           // implemented for compatibility.
10819           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10820             break;
10821         } else {
10822           // A constant whose bitwise inverse can be used as an immediate
10823           // value in a data-processing instruction. This can be used in GCC
10824           // with a "B" modifier that prints the inverted value, for use with
10825           // BIC and MVN instructions. It is not useful otherwise but is
10826           // implemented for compatibility.
10827           if (ARM_AM::getSOImmVal(~CVal) != -1)
10828             break;
10829         }
10830         return;
10831
10832       case 'L':
10833         if (Subtarget->isThumb1Only()) {
10834           // This must be a constant between -7 and 7,
10835           // for 3-operand ADD/SUB immediate instructions.
10836           if (CVal >= -7 && CVal < 7)
10837             break;
10838         } else if (Subtarget->isThumb2()) {
10839           // A constant whose negation can be used as an immediate value in a
10840           // data-processing instruction. This can be used in GCC with an "n"
10841           // modifier that prints the negated value, for use with SUB
10842           // instructions. It is not useful otherwise but is implemented for
10843           // compatibility.
10844           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10845             break;
10846         } else {
10847           // A constant whose negation can be used as an immediate value in a
10848           // data-processing instruction. This can be used in GCC with an "n"
10849           // modifier that prints the negated value, for use with SUB
10850           // instructions. It is not useful otherwise but is implemented for
10851           // compatibility.
10852           if (ARM_AM::getSOImmVal(-CVal) != -1)
10853             break;
10854         }
10855         return;
10856
10857       case 'M':
10858         if (Subtarget->isThumb()) { // FIXME thumb2
10859           // This must be a multiple of 4 between 0 and 1020, for
10860           // ADD sp + immediate.
10861           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10862             break;
10863         } else {
10864           // A power of two or a constant between 0 and 32.  This is used in
10865           // GCC for the shift amount on shifted register operands, but it is
10866           // useful in general for any shift amounts.
10867           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10868             break;
10869         }
10870         return;
10871
10872       case 'N':
10873         if (Subtarget->isThumb()) {  // FIXME thumb2
10874           // This must be a constant between 0 and 31, for shift amounts.
10875           if (CVal >= 0 && CVal <= 31)
10876             break;
10877         }
10878         return;
10879
10880       case 'O':
10881         if (Subtarget->isThumb()) {  // FIXME thumb2
10882           // This must be a multiple of 4 between -508 and 508, for
10883           // ADD/SUB sp = sp + immediate.
10884           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10885             break;
10886         }
10887         return;
10888     }
10889     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10890     break;
10891   }
10892
10893   if (Result.getNode()) {
10894     Ops.push_back(Result);
10895     return;
10896   }
10897   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10898 }
10899
10900 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10901   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10902   unsigned Opcode = Op->getOpcode();
10903   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10904       "Invalid opcode for Div/Rem lowering");
10905   bool isSigned = (Opcode == ISD::SDIVREM);
10906   EVT VT = Op->getValueType(0);
10907   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10908
10909   RTLIB::Libcall LC;
10910   switch (VT.getSimpleVT().SimpleTy) {
10911   default: llvm_unreachable("Unexpected request for libcall!");
10912   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10913   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10914   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10915   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10916   }
10917
10918   SDValue InChain = DAG.getEntryNode();
10919
10920   TargetLowering::ArgListTy Args;
10921   TargetLowering::ArgListEntry Entry;
10922   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10923     EVT ArgVT = Op->getOperand(i).getValueType();
10924     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10925     Entry.Node = Op->getOperand(i);
10926     Entry.Ty = ArgTy;
10927     Entry.isSExt = isSigned;
10928     Entry.isZExt = !isSigned;
10929     Args.push_back(Entry);
10930   }
10931
10932   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10933                                          getPointerTy());
10934
10935   Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10936
10937   SDLoc dl(Op);
10938   TargetLowering::
10939   CallLoweringInfo CLI(InChain, RetTy, isSigned, !isSigned, false, true,
10940                     0, getLibcallCallingConv(LC), /*isTailCall=*/false,
10941                     /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
10942                     Callee, Args, DAG, dl);
10943   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10944
10945   return CallInfo.first;
10946 }
10947
10948 bool
10949 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10950   // The ARM target isn't yet aware of offsets.
10951   return false;
10952 }
10953
10954 bool ARM::isBitFieldInvertedMask(unsigned v) {
10955   if (v == 0xffffffff)
10956     return false;
10957
10958   // there can be 1's on either or both "outsides", all the "inside"
10959   // bits must be 0's
10960   unsigned TO = CountTrailingOnes_32(v);
10961   unsigned LO = CountLeadingOnes_32(v);
10962   v = (v >> TO) << TO;
10963   v = (v << LO) >> LO;
10964   return v == 0;
10965 }
10966
10967 /// isFPImmLegal - Returns true if the target can instruction select the
10968 /// specified FP immediate natively. If false, the legalizer will
10969 /// materialize the FP immediate as a load from a constant pool.
10970 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10971   if (!Subtarget->hasVFP3())
10972     return false;
10973   if (VT == MVT::f32)
10974     return ARM_AM::getFP32Imm(Imm) != -1;
10975   if (VT == MVT::f64)
10976     return ARM_AM::getFP64Imm(Imm) != -1;
10977   return false;
10978 }
10979
10980 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10981 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10982 /// specified in the intrinsic calls.
10983 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10984                                            const CallInst &I,
10985                                            unsigned Intrinsic) const {
10986   switch (Intrinsic) {
10987   case Intrinsic::arm_neon_vld1:
10988   case Intrinsic::arm_neon_vld2:
10989   case Intrinsic::arm_neon_vld3:
10990   case Intrinsic::arm_neon_vld4:
10991   case Intrinsic::arm_neon_vld2lane:
10992   case Intrinsic::arm_neon_vld3lane:
10993   case Intrinsic::arm_neon_vld4lane: {
10994     Info.opc = ISD::INTRINSIC_W_CHAIN;
10995     // Conservatively set memVT to the entire set of vectors loaded.
10996     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10997     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10998     Info.ptrVal = I.getArgOperand(0);
10999     Info.offset = 0;
11000     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11001     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11002     Info.vol = false; // volatile loads with NEON intrinsics not supported
11003     Info.readMem = true;
11004     Info.writeMem = false;
11005     return true;
11006   }
11007   case Intrinsic::arm_neon_vst1:
11008   case Intrinsic::arm_neon_vst2:
11009   case Intrinsic::arm_neon_vst3:
11010   case Intrinsic::arm_neon_vst4:
11011   case Intrinsic::arm_neon_vst2lane:
11012   case Intrinsic::arm_neon_vst3lane:
11013   case Intrinsic::arm_neon_vst4lane: {
11014     Info.opc = ISD::INTRINSIC_VOID;
11015     // Conservatively set memVT to the entire set of vectors stored.
11016     unsigned NumElts = 0;
11017     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11018       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11019       if (!ArgTy->isVectorTy())
11020         break;
11021       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
11022     }
11023     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11024     Info.ptrVal = I.getArgOperand(0);
11025     Info.offset = 0;
11026     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11027     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11028     Info.vol = false; // volatile stores with NEON intrinsics not supported
11029     Info.readMem = false;
11030     Info.writeMem = true;
11031     return true;
11032   }
11033   case Intrinsic::arm_ldrex: {
11034     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11035     Info.opc = ISD::INTRINSIC_W_CHAIN;
11036     Info.memVT = MVT::getVT(PtrTy->getElementType());
11037     Info.ptrVal = I.getArgOperand(0);
11038     Info.offset = 0;
11039     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11040     Info.vol = true;
11041     Info.readMem = true;
11042     Info.writeMem = false;
11043     return true;
11044   }
11045   case Intrinsic::arm_strex: {
11046     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11047     Info.opc = ISD::INTRINSIC_W_CHAIN;
11048     Info.memVT = MVT::getVT(PtrTy->getElementType());
11049     Info.ptrVal = I.getArgOperand(1);
11050     Info.offset = 0;
11051     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11052     Info.vol = true;
11053     Info.readMem = false;
11054     Info.writeMem = true;
11055     return true;
11056   }
11057   case Intrinsic::arm_strexd: {
11058     Info.opc = ISD::INTRINSIC_W_CHAIN;
11059     Info.memVT = MVT::i64;
11060     Info.ptrVal = I.getArgOperand(2);
11061     Info.offset = 0;
11062     Info.align = 8;
11063     Info.vol = true;
11064     Info.readMem = false;
11065     Info.writeMem = true;
11066     return true;
11067   }
11068   case Intrinsic::arm_ldrexd: {
11069     Info.opc = ISD::INTRINSIC_W_CHAIN;
11070     Info.memVT = MVT::i64;
11071     Info.ptrVal = I.getArgOperand(0);
11072     Info.offset = 0;
11073     Info.align = 8;
11074     Info.vol = true;
11075     Info.readMem = true;
11076     Info.writeMem = false;
11077     return true;
11078   }
11079   default:
11080     break;
11081   }
11082
11083   return false;
11084 }