IR: add a second ordering operand to cmpxhg for failure
[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 #include <utility>
52 using namespace llvm;
53
54 STATISTIC(NumTailCalls, "Number of tail calls");
55 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
56 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
57
58 // This option should go away when tail calls fully work.
59 static cl::opt<bool>
60 EnableARMTailCalls("arm-tail-calls", cl::Hidden,
61   cl::desc("Generate tail calls (TEMPORARY OPTION)."),
62   cl::init(false));
63
64 cl::opt<bool>
65 EnableARMLongCalls("arm-long-calls", cl::Hidden,
66   cl::desc("Generate calls via indirect call instructions"),
67   cl::init(false));
68
69 static cl::opt<bool>
70 ARMInterworking("arm-interworking", cl::Hidden,
71   cl::desc("Enable / disable ARM interworking (for debugging only)"),
72   cl::init(true));
73
74 namespace {
75   class ARMCCState : public CCState {
76   public:
77     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
78                const TargetMachine &TM, SmallVectorImpl<CCValAssign> &locs,
79                LLVMContext &C, ParmContext PC)
80         : CCState(CC, isVarArg, MF, TM, locs, C) {
81       assert(((PC == Call) || (PC == Prologue)) &&
82              "ARMCCState users must specify whether their context is call"
83              "or prologue generation.");
84       CallOrPrologue = PC;
85     }
86   };
87 }
88
89 // The APCS parameter registers.
90 static const uint16_t GPRArgRegs[] = {
91   ARM::R0, ARM::R1, ARM::R2, ARM::R3
92 };
93
94 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
95                                        MVT PromotedBitwiseVT) {
96   if (VT != PromotedLdStVT) {
97     setOperationAction(ISD::LOAD, VT, Promote);
98     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
99
100     setOperationAction(ISD::STORE, VT, Promote);
101     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
102   }
103
104   MVT ElemTy = VT.getVectorElementType();
105   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
106     setOperationAction(ISD::SETCC, VT, Custom);
107   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
108   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
109   if (ElemTy == MVT::i32) {
110     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
111     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
112     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
113     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
114   } else {
115     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
116     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
117     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
118     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
119   }
120   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
121   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
122   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
123   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
124   setOperationAction(ISD::SELECT,            VT, Expand);
125   setOperationAction(ISD::SELECT_CC,         VT, Expand);
126   setOperationAction(ISD::VSELECT,           VT, Expand);
127   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
128   if (VT.isInteger()) {
129     setOperationAction(ISD::SHL, VT, Custom);
130     setOperationAction(ISD::SRA, VT, Custom);
131     setOperationAction(ISD::SRL, VT, Custom);
132   }
133
134   // Promote all bit-wise operations.
135   if (VT.isInteger() && VT != PromotedBitwiseVT) {
136     setOperationAction(ISD::AND, VT, Promote);
137     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
138     setOperationAction(ISD::OR,  VT, Promote);
139     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
140     setOperationAction(ISD::XOR, VT, Promote);
141     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
142   }
143
144   // Neon does not support vector divide/remainder operations.
145   setOperationAction(ISD::SDIV, VT, Expand);
146   setOperationAction(ISD::UDIV, VT, Expand);
147   setOperationAction(ISD::FDIV, VT, Expand);
148   setOperationAction(ISD::SREM, VT, Expand);
149   setOperationAction(ISD::UREM, VT, Expand);
150   setOperationAction(ISD::FREM, VT, Expand);
151 }
152
153 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
154   addRegisterClass(VT, &ARM::DPRRegClass);
155   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
156 }
157
158 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
159   addRegisterClass(VT, &ARM::DPairRegClass);
160   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
161 }
162
163 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
164   if (TM.getSubtarget<ARMSubtarget>().isTargetMachO())
165     return new TargetLoweringObjectFileMachO();
166
167   return new ARMElfTargetObjectFile();
168 }
169
170 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
171     : TargetLowering(TM, createTLOF(TM)) {
172   Subtarget = &TM.getSubtarget<ARMSubtarget>();
173   RegInfo = TM.getRegisterInfo();
174   Itins = TM.getInstrItineraryData();
175
176   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
177
178   if (Subtarget->isTargetMachO()) {
179     // Uses VFP for Thumb libfuncs if available.
180     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
181         Subtarget->hasARMOps()) {
182       // Single-precision floating-point arithmetic.
183       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
184       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
185       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
186       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
187
188       // Double-precision floating-point arithmetic.
189       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
190       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
191       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
192       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
193
194       // Single-precision comparisons.
195       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
196       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
197       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
198       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
199       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
200       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
201       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
202       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
203
204       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
205       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
206       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
207       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
208       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
209       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
210       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
211       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
212
213       // Double-precision comparisons.
214       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
215       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
216       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
217       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
218       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
219       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
220       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
221       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
222
223       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
224       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
225       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
226       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
227       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
228       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
229       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
230       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
231
232       // Floating-point to integer conversions.
233       // i64 conversions are done via library routines even when generating VFP
234       // instructions, so use the same ones.
235       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
236       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
237       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
238       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
239
240       // Conversions between floating types.
241       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
242       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
243
244       // Integer to floating-point conversions.
245       // i64 conversions are done via library routines even when generating VFP
246       // instructions, so use the same ones.
247       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
248       // e.g., __floatunsidf vs. __floatunssidfvfp.
249       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
250       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
251       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
252       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
253     }
254   }
255
256   // These libcalls are not available in 32-bit.
257   setLibcallName(RTLIB::SHL_I128, 0);
258   setLibcallName(RTLIB::SRL_I128, 0);
259   setLibcallName(RTLIB::SRA_I128, 0);
260
261   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO()) {
262     // Double-precision floating-point arithmetic helper functions
263     // RTABI chapter 4.1.2, Table 2
264     setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
265     setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
266     setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
267     setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
268     setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
269     setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
270     setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
271     setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
272
273     // Double-precision floating-point comparison helper functions
274     // RTABI chapter 4.1.2, Table 3
275     setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
276     setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
277     setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
278     setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
279     setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
280     setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
281     setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
282     setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
283     setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
284     setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
285     setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
286     setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
287     setLibcallName(RTLIB::UO_F64,  "__aeabi_dcmpun");
288     setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
289     setLibcallName(RTLIB::O_F64,   "__aeabi_dcmpun");
290     setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
291     setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
292     setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
293     setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
294     setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
295     setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
296     setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
297     setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
298     setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
299
300     // Single-precision floating-point arithmetic helper functions
301     // RTABI chapter 4.1.2, Table 4
302     setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
303     setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
304     setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
305     setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
306     setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
307     setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
308     setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
309     setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
310
311     // Single-precision floating-point comparison helper functions
312     // RTABI chapter 4.1.2, Table 5
313     setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
314     setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
315     setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
316     setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
317     setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
318     setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
319     setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
320     setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
321     setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
322     setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
323     setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
324     setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
325     setLibcallName(RTLIB::UO_F32,  "__aeabi_fcmpun");
326     setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
327     setLibcallName(RTLIB::O_F32,   "__aeabi_fcmpun");
328     setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
329     setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
330     setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
331     setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
332     setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
333     setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
334     setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
335     setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
336     setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
337
338     // Floating-point to integer conversions.
339     // RTABI chapter 4.1.2, Table 6
340     setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
341     setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
342     setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
343     setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
344     setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
345     setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
346     setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
347     setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
348     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
349     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
350     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
351     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
352     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
353     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
354     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
355     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
356
357     // Conversions between floating types.
358     // RTABI chapter 4.1.2, Table 7
359     setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
360     setLibcallName(RTLIB::FPEXT_F32_F64,   "__aeabi_f2d");
361     setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
362     setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
363
364     // Integer to floating-point conversions.
365     // RTABI chapter 4.1.2, Table 8
366     setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
367     setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
368     setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
369     setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
370     setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
371     setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
372     setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
373     setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
374     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
375     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
376     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
377     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
378     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
379     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
380     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
381     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
382
383     // Long long helper functions
384     // RTABI chapter 4.2, Table 9
385     setLibcallName(RTLIB::MUL_I64,  "__aeabi_lmul");
386     setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
387     setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
388     setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
389     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
390     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
391     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
392     setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
393     setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
394     setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
395
396     // Integer division functions
397     // RTABI chapter 4.3.1
398     setLibcallName(RTLIB::SDIV_I8,  "__aeabi_idiv");
399     setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
400     setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
401     setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
402     setLibcallName(RTLIB::UDIV_I8,  "__aeabi_uidiv");
403     setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
404     setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
405     setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
406     setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
407     setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
408     setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
409     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
410     setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
411     setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
412     setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
413     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
414
415     // Memory operations
416     // RTABI chapter 4.3.4
417     setLibcallName(RTLIB::MEMCPY,  "__aeabi_memcpy");
418     setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
419     setLibcallName(RTLIB::MEMSET,  "__aeabi_memset");
420     setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
421     setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
422     setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
423   }
424
425   // Use divmod compiler-rt calls for iOS 5.0 and later.
426   if (Subtarget->getTargetTriple().isiOS() &&
427       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
428     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
429     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
430   }
431
432   if (Subtarget->isThumb1Only())
433     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
434   else
435     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
436   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
437       !Subtarget->isThumb1Only()) {
438     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
439     if (!Subtarget->isFPOnlySP())
440       addRegisterClass(MVT::f64, &ARM::DPRRegClass);
441
442     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
443   }
444
445   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
446        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
447     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
448          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
449       setTruncStoreAction((MVT::SimpleValueType)VT,
450                           (MVT::SimpleValueType)InnerVT, Expand);
451     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
452     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
453     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
454   }
455
456   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
457   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
458
459   if (Subtarget->hasNEON()) {
460     addDRTypeForNEON(MVT::v2f32);
461     addDRTypeForNEON(MVT::v8i8);
462     addDRTypeForNEON(MVT::v4i16);
463     addDRTypeForNEON(MVT::v2i32);
464     addDRTypeForNEON(MVT::v1i64);
465
466     addQRTypeForNEON(MVT::v4f32);
467     addQRTypeForNEON(MVT::v2f64);
468     addQRTypeForNEON(MVT::v16i8);
469     addQRTypeForNEON(MVT::v8i16);
470     addQRTypeForNEON(MVT::v4i32);
471     addQRTypeForNEON(MVT::v2i64);
472
473     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
474     // neither Neon nor VFP support any arithmetic operations on it.
475     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
476     // supported for v4f32.
477     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
478     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
479     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
480     // FIXME: Code duplication: FDIV and FREM are expanded always, see
481     // ARMTargetLowering::addTypeForNEON method for details.
482     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
483     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
484     // FIXME: Create unittest.
485     // In another words, find a way when "copysign" appears in DAG with vector
486     // operands.
487     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
488     // FIXME: Code duplication: SETCC has custom operation action, see
489     // ARMTargetLowering::addTypeForNEON method for details.
490     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
491     // FIXME: Create unittest for FNEG and for FABS.
492     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
493     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
494     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
495     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
496     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
497     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
498     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
499     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
500     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
501     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
502     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
503     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
504     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
505     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
506     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
507     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
508     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
509     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
510     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
511
512     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
513     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
514     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
515     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
516     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
517     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
518     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
519     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
520     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
521     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
522     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
523     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
524     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
525     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
526     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
527
528     // Mark v2f32 intrinsics.
529     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
530     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
531     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
532     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
533     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
534     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
535     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
536     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
537     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
538     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
539     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
540     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
541     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
542     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
543     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
544
545     // Neon does not support some operations on v1i64 and v2i64 types.
546     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
547     // Custom handling for some quad-vector types to detect VMULL.
548     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
549     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
550     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
551     // Custom handling for some vector types to avoid expensive expansions
552     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
553     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
554     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
555     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
556     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
557     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
558     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
559     // a destination type that is wider than the source, and nor does
560     // it have a FP_TO_[SU]INT instruction with a narrower destination than
561     // source.
562     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
563     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
564     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
565     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
566
567     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
568     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
569
570     // NEON does not have single instruction CTPOP for vectors with element
571     // types wider than 8-bits.  However, custom lowering can leverage the
572     // v8i8/v16i8 vcnt instruction.
573     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
574     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
575     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
576     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
577
578     // NEON only has FMA instructions as of VFP4.
579     if (!Subtarget->hasVFP4()) {
580       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
581       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
582     }
583
584     setTargetDAGCombine(ISD::INTRINSIC_VOID);
585     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
586     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
587     setTargetDAGCombine(ISD::SHL);
588     setTargetDAGCombine(ISD::SRL);
589     setTargetDAGCombine(ISD::SRA);
590     setTargetDAGCombine(ISD::SIGN_EXTEND);
591     setTargetDAGCombine(ISD::ZERO_EXTEND);
592     setTargetDAGCombine(ISD::ANY_EXTEND);
593     setTargetDAGCombine(ISD::SELECT_CC);
594     setTargetDAGCombine(ISD::BUILD_VECTOR);
595     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
596     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
597     setTargetDAGCombine(ISD::STORE);
598     setTargetDAGCombine(ISD::FP_TO_SINT);
599     setTargetDAGCombine(ISD::FP_TO_UINT);
600     setTargetDAGCombine(ISD::FDIV);
601
602     // It is legal to extload from v4i8 to v4i16 or v4i32.
603     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
604                   MVT::v4i16, MVT::v2i16,
605                   MVT::v2i32};
606     for (unsigned i = 0; i < 6; ++i) {
607       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
608       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
609       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
610     }
611   }
612
613   // ARM and Thumb2 support UMLAL/SMLAL.
614   if (!Subtarget->isThumb1Only())
615     setTargetDAGCombine(ISD::ADDC);
616
617
618   computeRegisterProperties();
619
620   // ARM does not have f32 extending load.
621   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
622
623   // ARM does not have i1 sign extending load.
624   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
625
626   // ARM supports all 4 flavors of integer indexed load / store.
627   if (!Subtarget->isThumb1Only()) {
628     for (unsigned im = (unsigned)ISD::PRE_INC;
629          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
630       setIndexedLoadAction(im,  MVT::i1,  Legal);
631       setIndexedLoadAction(im,  MVT::i8,  Legal);
632       setIndexedLoadAction(im,  MVT::i16, Legal);
633       setIndexedLoadAction(im,  MVT::i32, Legal);
634       setIndexedStoreAction(im, MVT::i1,  Legal);
635       setIndexedStoreAction(im, MVT::i8,  Legal);
636       setIndexedStoreAction(im, MVT::i16, Legal);
637       setIndexedStoreAction(im, MVT::i32, Legal);
638     }
639   }
640
641   // i64 operation support.
642   setOperationAction(ISD::MUL,     MVT::i64, Expand);
643   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
644   if (Subtarget->isThumb1Only()) {
645     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
646     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
647   }
648   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
649       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
650     setOperationAction(ISD::MULHS, MVT::i32, Expand);
651
652   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
653   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
654   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
655   setOperationAction(ISD::SRL,       MVT::i64, Custom);
656   setOperationAction(ISD::SRA,       MVT::i64, Custom);
657
658   if (!Subtarget->isThumb1Only()) {
659     // FIXME: We should do this for Thumb1 as well.
660     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
661     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
662     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
663     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
664   }
665
666   // ARM does not have ROTL.
667   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
668   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
669   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
670   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
671     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
672
673   // These just redirect to CTTZ and CTLZ on ARM.
674   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
675   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
676
677   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
678
679   // Only ARMv6 has BSWAP.
680   if (!Subtarget->hasV6Ops())
681     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
682
683   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
684       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
685     // These are expanded into libcalls if the cpu doesn't have HW divider.
686     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
687     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
688   }
689
690   // FIXME: Also set divmod for SREM on EABI
691   setOperationAction(ISD::SREM,  MVT::i32, Expand);
692   setOperationAction(ISD::UREM,  MVT::i32, Expand);
693   // Register based DivRem for AEABI (RTABI 4.2)
694   if (Subtarget->isTargetAEABI()) {
695     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
696     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
697     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
698     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
699     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
700     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
701     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
702     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
703
704     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
705     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
706     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
707     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
708     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
709     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
710     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
711     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
712
713     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
714     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
715   } else {
716     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
717     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
718   }
719
720   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
721   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
722   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
723   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
724   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
725
726   setOperationAction(ISD::TRAP, MVT::Other, Legal);
727
728   // Use the default implementation.
729   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
730   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
731   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
732   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
733   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
734   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
735
736   if (!Subtarget->isTargetMachO()) {
737     // Non-MachO platforms may return values in these registers via the
738     // personality function.
739     setExceptionPointerRegister(ARM::R0);
740     setExceptionSelectorRegister(ARM::R1);
741   }
742
743   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
744   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
745   // the default expansion.
746   if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
747     // ATOMIC_FENCE needs custom lowering; the other 32-bit ones are legal and
748     // handled normally.
749     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
750     // Custom lowering for 64-bit ops
751     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i64, Custom);
752     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i64, Custom);
753     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i64, Custom);
754     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i64, Custom);
755     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i64, Custom);
756     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i64, Custom);
757     setOperationAction(ISD::ATOMIC_LOAD_MIN,  MVT::i64, Custom);
758     setOperationAction(ISD::ATOMIC_LOAD_MAX,  MVT::i64, Custom);
759     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
760     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
761     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
762     // On v8, we have particularly efficient implementations of atomic fences
763     // if they can be combined with nearby atomic loads and stores.
764     if (!Subtarget->hasV8Ops()) {
765       // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
766       setInsertFencesForAtomic(true);
767     }
768     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
769   } else {
770     // If there's anything we can use as a barrier, go through custom lowering
771     // for ATOMIC_FENCE.
772     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
773                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
774
775     // Set them all for expansion, which will force libcalls.
776     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
777     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
778     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
779     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
780     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
781     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
782     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
783     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
784     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
785     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
786     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
787     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
788     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
789     // Unordered/Monotonic case.
790     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
791     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
792   }
793
794   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
795
796   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
797   if (!Subtarget->hasV6Ops()) {
798     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
799     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
800   }
801   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
802
803   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
804       !Subtarget->isThumb1Only()) {
805     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
806     // iff target supports vfp2.
807     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
808     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
809   }
810
811   // We want to custom lower some of our intrinsics.
812   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
813   if (Subtarget->isTargetDarwin()) {
814     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
815     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
816     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
817   }
818
819   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
820   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
821   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
822   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
823   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
824   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
825   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
826   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
827   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
828
829   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
830   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
831   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
832   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
833   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
834
835   // We don't support sin/cos/fmod/copysign/pow
836   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
837   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
838   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
839   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
840   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
841   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
842   setOperationAction(ISD::FREM,      MVT::f64, Expand);
843   setOperationAction(ISD::FREM,      MVT::f32, Expand);
844   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
845       !Subtarget->isThumb1Only()) {
846     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
847     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
848   }
849   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
850   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
851
852   if (!Subtarget->hasVFP4()) {
853     setOperationAction(ISD::FMA, MVT::f64, Expand);
854     setOperationAction(ISD::FMA, MVT::f32, Expand);
855   }
856
857   // Various VFP goodness
858   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
859     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
860     if (Subtarget->hasVFP2()) {
861       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
862       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
863       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
864       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
865     }
866     // Special handling for half-precision FP.
867     if (!Subtarget->hasFP16()) {
868       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
869       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
870     }
871   }
872       
873   // Combine sin / cos into one node or libcall if possible.
874   if (Subtarget->hasSinCos()) {
875     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
876     setLibcallName(RTLIB::SINCOS_F64, "sincos");
877     if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
878       // For iOS, we don't want to the normal expansion of a libcall to
879       // sincos. We want to issue a libcall to __sincos_stret.
880       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
881       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
882     }
883   }
884
885   // We have target-specific dag combine patterns for the following nodes:
886   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
887   setTargetDAGCombine(ISD::ADD);
888   setTargetDAGCombine(ISD::SUB);
889   setTargetDAGCombine(ISD::MUL);
890   setTargetDAGCombine(ISD::AND);
891   setTargetDAGCombine(ISD::OR);
892   setTargetDAGCombine(ISD::XOR);
893
894   if (Subtarget->hasV6Ops())
895     setTargetDAGCombine(ISD::SRL);
896
897   setStackPointerRegisterToSaveRestore(ARM::SP);
898
899   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
900       !Subtarget->hasVFP2())
901     setSchedulingPreference(Sched::RegPressure);
902   else
903     setSchedulingPreference(Sched::Hybrid);
904
905   //// temporary - rewrite interface to use type
906   MaxStoresPerMemset = 8;
907   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
908   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
909   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
910   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
911   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
912
913   // On ARM arguments smaller than 4 bytes are extended, so all arguments
914   // are at least 4 bytes aligned.
915   setMinStackArgumentAlignment(4);
916
917   // Prefer likely predicted branches to selects on out-of-order cores.
918   PredictableSelectIsExpensive = Subtarget->isLikeA9();
919
920   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
921 }
922
923 static void getExclusiveOperation(unsigned Size, AtomicOrdering Ord,
924                                   bool isThumb2, unsigned &LdrOpc,
925                                   unsigned &StrOpc) {
926   static const unsigned LoadBares[4][2] =  {{ARM::LDREXB, ARM::t2LDREXB},
927                                             {ARM::LDREXH, ARM::t2LDREXH},
928                                             {ARM::LDREX,  ARM::t2LDREX},
929                                             {ARM::LDREXD, ARM::t2LDREXD}};
930   static const unsigned LoadAcqs[4][2] =   {{ARM::LDAEXB, ARM::t2LDAEXB},
931                                             {ARM::LDAEXH, ARM::t2LDAEXH},
932                                             {ARM::LDAEX,  ARM::t2LDAEX},
933                                             {ARM::LDAEXD, ARM::t2LDAEXD}};
934   static const unsigned StoreBares[4][2] = {{ARM::STREXB, ARM::t2STREXB},
935                                             {ARM::STREXH, ARM::t2STREXH},
936                                             {ARM::STREX,  ARM::t2STREX},
937                                             {ARM::STREXD, ARM::t2STREXD}};
938   static const unsigned StoreRels[4][2] =  {{ARM::STLEXB, ARM::t2STLEXB},
939                                             {ARM::STLEXH, ARM::t2STLEXH},
940                                             {ARM::STLEX,  ARM::t2STLEX},
941                                             {ARM::STLEXD, ARM::t2STLEXD}};
942
943   const unsigned (*LoadOps)[2], (*StoreOps)[2];
944   if (Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent)
945     LoadOps = LoadAcqs;
946   else
947     LoadOps = LoadBares;
948
949   if (Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent)
950     StoreOps = StoreRels;
951   else
952     StoreOps = StoreBares;
953
954   assert(isPowerOf2_32(Size) && Size <= 8 &&
955          "unsupported size for atomic binary op!");
956
957   LdrOpc = LoadOps[Log2_32(Size)][isThumb2];
958   StrOpc = StoreOps[Log2_32(Size)][isThumb2];
959 }
960
961 // FIXME: It might make sense to define the representative register class as the
962 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
963 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
964 // SPR's representative would be DPR_VFP2. This should work well if register
965 // pressure tracking were modified such that a register use would increment the
966 // pressure of the register class's representative and all of it's super
967 // classes' representatives transitively. We have not implemented this because
968 // of the difficulty prior to coalescing of modeling operand register classes
969 // due to the common occurrence of cross class copies and subregister insertions
970 // and extractions.
971 std::pair<const TargetRegisterClass*, uint8_t>
972 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
973   const TargetRegisterClass *RRC = 0;
974   uint8_t Cost = 1;
975   switch (VT.SimpleTy) {
976   default:
977     return TargetLowering::findRepresentativeClass(VT);
978   // Use DPR as representative register class for all floating point
979   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
980   // the cost is 1 for both f32 and f64.
981   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
982   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
983     RRC = &ARM::DPRRegClass;
984     // When NEON is used for SP, only half of the register file is available
985     // because operations that define both SP and DP results will be constrained
986     // to the VFP2 class (D0-D15). We currently model this constraint prior to
987     // coalescing by double-counting the SP regs. See the FIXME above.
988     if (Subtarget->useNEONForSinglePrecisionFP())
989       Cost = 2;
990     break;
991   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
992   case MVT::v4f32: case MVT::v2f64:
993     RRC = &ARM::DPRRegClass;
994     Cost = 2;
995     break;
996   case MVT::v4i64:
997     RRC = &ARM::DPRRegClass;
998     Cost = 4;
999     break;
1000   case MVT::v8i64:
1001     RRC = &ARM::DPRRegClass;
1002     Cost = 8;
1003     break;
1004   }
1005   return std::make_pair(RRC, Cost);
1006 }
1007
1008 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1009   switch (Opcode) {
1010   default: return 0;
1011   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1012   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1013   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1014   case ARMISD::CALL:          return "ARMISD::CALL";
1015   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1016   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1017   case ARMISD::tCALL:         return "ARMISD::tCALL";
1018   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1019   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1020   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1021   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1022   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1023   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1024   case ARMISD::CMP:           return "ARMISD::CMP";
1025   case ARMISD::CMN:           return "ARMISD::CMN";
1026   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1027   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1028   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1029   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1030   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1031
1032   case ARMISD::CMOV:          return "ARMISD::CMOV";
1033
1034   case ARMISD::RBIT:          return "ARMISD::RBIT";
1035
1036   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
1037   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
1038   case ARMISD::SITOF:         return "ARMISD::SITOF";
1039   case ARMISD::UITOF:         return "ARMISD::UITOF";
1040
1041   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1042   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1043   case ARMISD::RRX:           return "ARMISD::RRX";
1044
1045   case ARMISD::ADDC:          return "ARMISD::ADDC";
1046   case ARMISD::ADDE:          return "ARMISD::ADDE";
1047   case ARMISD::SUBC:          return "ARMISD::SUBC";
1048   case ARMISD::SUBE:          return "ARMISD::SUBE";
1049
1050   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1051   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1052
1053   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1054   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1055
1056   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1057
1058   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1059
1060   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1061
1062   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1063
1064   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1065
1066   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1067   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1068   case ARMISD::VCGE:          return "ARMISD::VCGE";
1069   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1070   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1071   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1072   case ARMISD::VCGT:          return "ARMISD::VCGT";
1073   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1074   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1075   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1076   case ARMISD::VTST:          return "ARMISD::VTST";
1077
1078   case ARMISD::VSHL:          return "ARMISD::VSHL";
1079   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1080   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1081   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1082   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1083   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1084   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1085   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1086   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1087   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1088   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1089   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1090   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1091   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1092   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1093   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1094   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1095   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1096   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1097   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1098   case ARMISD::VDUP:          return "ARMISD::VDUP";
1099   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1100   case ARMISD::VEXT:          return "ARMISD::VEXT";
1101   case ARMISD::VREV64:        return "ARMISD::VREV64";
1102   case ARMISD::VREV32:        return "ARMISD::VREV32";
1103   case ARMISD::VREV16:        return "ARMISD::VREV16";
1104   case ARMISD::VZIP:          return "ARMISD::VZIP";
1105   case ARMISD::VUZP:          return "ARMISD::VUZP";
1106   case ARMISD::VTRN:          return "ARMISD::VTRN";
1107   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1108   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1109   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1110   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1111   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1112   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1113   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1114   case ARMISD::FMAX:          return "ARMISD::FMAX";
1115   case ARMISD::FMIN:          return "ARMISD::FMIN";
1116   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1117   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1118   case ARMISD::BFI:           return "ARMISD::BFI";
1119   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1120   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1121   case ARMISD::VBSL:          return "ARMISD::VBSL";
1122   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1123   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1124   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1125   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1126   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1127   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1128   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1129   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1130   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1131   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1132   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1133   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1134   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1135   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1136   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1137   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1138   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1139   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1140   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1141   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1142   }
1143 }
1144
1145 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1146   if (!VT.isVector()) return getPointerTy();
1147   return VT.changeVectorElementTypeToInteger();
1148 }
1149
1150 /// getRegClassFor - Return the register class that should be used for the
1151 /// specified value type.
1152 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1153   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1154   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1155   // load / store 4 to 8 consecutive D registers.
1156   if (Subtarget->hasNEON()) {
1157     if (VT == MVT::v4i64)
1158       return &ARM::QQPRRegClass;
1159     if (VT == MVT::v8i64)
1160       return &ARM::QQQQPRRegClass;
1161   }
1162   return TargetLowering::getRegClassFor(VT);
1163 }
1164
1165 // Create a fast isel object.
1166 FastISel *
1167 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1168                                   const TargetLibraryInfo *libInfo) const {
1169   return ARM::createFastISel(funcInfo, libInfo);
1170 }
1171
1172 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1173 /// be used for loads / stores from the global.
1174 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1175   return (Subtarget->isThumb1Only() ? 127 : 4095);
1176 }
1177
1178 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1179   unsigned NumVals = N->getNumValues();
1180   if (!NumVals)
1181     return Sched::RegPressure;
1182
1183   for (unsigned i = 0; i != NumVals; ++i) {
1184     EVT VT = N->getValueType(i);
1185     if (VT == MVT::Glue || VT == MVT::Other)
1186       continue;
1187     if (VT.isFloatingPoint() || VT.isVector())
1188       return Sched::ILP;
1189   }
1190
1191   if (!N->isMachineOpcode())
1192     return Sched::RegPressure;
1193
1194   // Load are scheduled for latency even if there instruction itinerary
1195   // is not available.
1196   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1197   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1198
1199   if (MCID.getNumDefs() == 0)
1200     return Sched::RegPressure;
1201   if (!Itins->isEmpty() &&
1202       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1203     return Sched::ILP;
1204
1205   return Sched::RegPressure;
1206 }
1207
1208 //===----------------------------------------------------------------------===//
1209 // Lowering Code
1210 //===----------------------------------------------------------------------===//
1211
1212 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1213 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1214   switch (CC) {
1215   default: llvm_unreachable("Unknown condition code!");
1216   case ISD::SETNE:  return ARMCC::NE;
1217   case ISD::SETEQ:  return ARMCC::EQ;
1218   case ISD::SETGT:  return ARMCC::GT;
1219   case ISD::SETGE:  return ARMCC::GE;
1220   case ISD::SETLT:  return ARMCC::LT;
1221   case ISD::SETLE:  return ARMCC::LE;
1222   case ISD::SETUGT: return ARMCC::HI;
1223   case ISD::SETUGE: return ARMCC::HS;
1224   case ISD::SETULT: return ARMCC::LO;
1225   case ISD::SETULE: return ARMCC::LS;
1226   }
1227 }
1228
1229 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1230 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1231                         ARMCC::CondCodes &CondCode2) {
1232   CondCode2 = ARMCC::AL;
1233   switch (CC) {
1234   default: llvm_unreachable("Unknown FP condition!");
1235   case ISD::SETEQ:
1236   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1237   case ISD::SETGT:
1238   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1239   case ISD::SETGE:
1240   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1241   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1242   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1243   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1244   case ISD::SETO:   CondCode = ARMCC::VC; break;
1245   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1246   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1247   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1248   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1249   case ISD::SETLT:
1250   case ISD::SETULT: CondCode = ARMCC::LT; break;
1251   case ISD::SETLE:
1252   case ISD::SETULE: CondCode = ARMCC::LE; break;
1253   case ISD::SETNE:
1254   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1255   }
1256 }
1257
1258 //===----------------------------------------------------------------------===//
1259 //                      Calling Convention Implementation
1260 //===----------------------------------------------------------------------===//
1261
1262 #include "ARMGenCallingConv.inc"
1263
1264 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1265 /// given CallingConvention value.
1266 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1267                                                  bool Return,
1268                                                  bool isVarArg) const {
1269   switch (CC) {
1270   default:
1271     llvm_unreachable("Unsupported calling convention");
1272   case CallingConv::Fast:
1273     if (Subtarget->hasVFP2() && !isVarArg) {
1274       if (!Subtarget->isAAPCS_ABI())
1275         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1276       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1277       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1278     }
1279     // Fallthrough
1280   case CallingConv::C: {
1281     // Use target triple & subtarget features to do actual dispatch.
1282     if (!Subtarget->isAAPCS_ABI())
1283       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1284     else if (Subtarget->hasVFP2() &&
1285              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1286              !isVarArg)
1287       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1288     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1289   }
1290   case CallingConv::ARM_AAPCS_VFP:
1291     if (!isVarArg)
1292       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1293     // Fallthrough
1294   case CallingConv::ARM_AAPCS:
1295     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1296   case CallingConv::ARM_APCS:
1297     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1298   case CallingConv::GHC:
1299     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1300   }
1301 }
1302
1303 /// LowerCallResult - Lower the result values of a call into the
1304 /// appropriate copies out of appropriate physical registers.
1305 SDValue
1306 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1307                                    CallingConv::ID CallConv, bool isVarArg,
1308                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1309                                    SDLoc dl, SelectionDAG &DAG,
1310                                    SmallVectorImpl<SDValue> &InVals,
1311                                    bool isThisReturn, SDValue ThisVal) const {
1312
1313   // Assign locations to each value returned by this call.
1314   SmallVector<CCValAssign, 16> RVLocs;
1315   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1316                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1317   CCInfo.AnalyzeCallResult(Ins,
1318                            CCAssignFnForNode(CallConv, /* Return*/ true,
1319                                              isVarArg));
1320
1321   // Copy all of the result registers out of their specified physreg.
1322   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1323     CCValAssign VA = RVLocs[i];
1324
1325     // Pass 'this' value directly from the argument to return value, to avoid
1326     // reg unit interference
1327     if (i == 0 && isThisReturn) {
1328       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1329              "unexpected return calling convention register assignment");
1330       InVals.push_back(ThisVal);
1331       continue;
1332     }
1333
1334     SDValue Val;
1335     if (VA.needsCustom()) {
1336       // Handle f64 or half of a v2f64.
1337       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1338                                       InFlag);
1339       Chain = Lo.getValue(1);
1340       InFlag = Lo.getValue(2);
1341       VA = RVLocs[++i]; // skip ahead to next loc
1342       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1343                                       InFlag);
1344       Chain = Hi.getValue(1);
1345       InFlag = Hi.getValue(2);
1346       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1347
1348       if (VA.getLocVT() == MVT::v2f64) {
1349         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1350         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1351                           DAG.getConstant(0, MVT::i32));
1352
1353         VA = RVLocs[++i]; // skip ahead to next loc
1354         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1355         Chain = Lo.getValue(1);
1356         InFlag = Lo.getValue(2);
1357         VA = RVLocs[++i]; // skip ahead to next loc
1358         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1359         Chain = Hi.getValue(1);
1360         InFlag = Hi.getValue(2);
1361         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1362         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1363                           DAG.getConstant(1, MVT::i32));
1364       }
1365     } else {
1366       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1367                                InFlag);
1368       Chain = Val.getValue(1);
1369       InFlag = Val.getValue(2);
1370     }
1371
1372     switch (VA.getLocInfo()) {
1373     default: llvm_unreachable("Unknown loc info!");
1374     case CCValAssign::Full: break;
1375     case CCValAssign::BCvt:
1376       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1377       break;
1378     }
1379
1380     InVals.push_back(Val);
1381   }
1382
1383   return Chain;
1384 }
1385
1386 /// LowerMemOpCallTo - Store the argument to the stack.
1387 SDValue
1388 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1389                                     SDValue StackPtr, SDValue Arg,
1390                                     SDLoc dl, SelectionDAG &DAG,
1391                                     const CCValAssign &VA,
1392                                     ISD::ArgFlagsTy Flags) const {
1393   unsigned LocMemOffset = VA.getLocMemOffset();
1394   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1395   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1396   return DAG.getStore(Chain, dl, Arg, PtrOff,
1397                       MachinePointerInfo::getStack(LocMemOffset),
1398                       false, false, 0);
1399 }
1400
1401 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1402                                          SDValue Chain, SDValue &Arg,
1403                                          RegsToPassVector &RegsToPass,
1404                                          CCValAssign &VA, CCValAssign &NextVA,
1405                                          SDValue &StackPtr,
1406                                          SmallVectorImpl<SDValue> &MemOpChains,
1407                                          ISD::ArgFlagsTy Flags) const {
1408
1409   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1410                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1411   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1412
1413   if (NextVA.isRegLoc())
1414     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1415   else {
1416     assert(NextVA.isMemLoc());
1417     if (StackPtr.getNode() == 0)
1418       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1419
1420     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1421                                            dl, DAG, NextVA,
1422                                            Flags));
1423   }
1424 }
1425
1426 /// LowerCall - Lowering a call into a callseq_start <-
1427 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1428 /// nodes.
1429 SDValue
1430 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1431                              SmallVectorImpl<SDValue> &InVals) const {
1432   SelectionDAG &DAG                     = CLI.DAG;
1433   SDLoc &dl                          = CLI.DL;
1434   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1435   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1436   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1437   SDValue Chain                         = CLI.Chain;
1438   SDValue Callee                        = CLI.Callee;
1439   bool &isTailCall                      = CLI.IsTailCall;
1440   CallingConv::ID CallConv              = CLI.CallConv;
1441   bool doesNotRet                       = CLI.DoesNotReturn;
1442   bool isVarArg                         = CLI.IsVarArg;
1443
1444   MachineFunction &MF = DAG.getMachineFunction();
1445   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1446   bool isThisReturn   = false;
1447   bool isSibCall      = false;
1448   // Disable tail calls if they're not supported.
1449   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1450     isTailCall = false;
1451   if (isTailCall) {
1452     // Check if it's really possible to do a tail call.
1453     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1454                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1455                                                    Outs, OutVals, Ins, DAG);
1456     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1457     // detected sibcalls.
1458     if (isTailCall) {
1459       ++NumTailCalls;
1460       isSibCall = true;
1461     }
1462   }
1463
1464   // Analyze operands of the call, assigning locations to each operand.
1465   SmallVector<CCValAssign, 16> ArgLocs;
1466   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1467                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1468   CCInfo.AnalyzeCallOperands(Outs,
1469                              CCAssignFnForNode(CallConv, /* Return*/ false,
1470                                                isVarArg));
1471
1472   // Get a count of how many bytes are to be pushed on the stack.
1473   unsigned NumBytes = CCInfo.getNextStackOffset();
1474
1475   // For tail calls, memory operands are available in our caller's stack.
1476   if (isSibCall)
1477     NumBytes = 0;
1478
1479   // Adjust the stack pointer for the new arguments...
1480   // These operations are automatically eliminated by the prolog/epilog pass
1481   if (!isSibCall)
1482     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1483                                  dl);
1484
1485   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1486
1487   RegsToPassVector RegsToPass;
1488   SmallVector<SDValue, 8> MemOpChains;
1489
1490   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1491   // of tail call optimization, arguments are handled later.
1492   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1493        i != e;
1494        ++i, ++realArgIdx) {
1495     CCValAssign &VA = ArgLocs[i];
1496     SDValue Arg = OutVals[realArgIdx];
1497     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1498     bool isByVal = Flags.isByVal();
1499
1500     // Promote the value if needed.
1501     switch (VA.getLocInfo()) {
1502     default: llvm_unreachable("Unknown loc info!");
1503     case CCValAssign::Full: break;
1504     case CCValAssign::SExt:
1505       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1506       break;
1507     case CCValAssign::ZExt:
1508       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1509       break;
1510     case CCValAssign::AExt:
1511       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1512       break;
1513     case CCValAssign::BCvt:
1514       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1515       break;
1516     }
1517
1518     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1519     if (VA.needsCustom()) {
1520       if (VA.getLocVT() == MVT::v2f64) {
1521         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1522                                   DAG.getConstant(0, MVT::i32));
1523         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1524                                   DAG.getConstant(1, MVT::i32));
1525
1526         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1527                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1528
1529         VA = ArgLocs[++i]; // skip ahead to next loc
1530         if (VA.isRegLoc()) {
1531           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1532                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1533         } else {
1534           assert(VA.isMemLoc());
1535
1536           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1537                                                  dl, DAG, VA, Flags));
1538         }
1539       } else {
1540         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1541                          StackPtr, MemOpChains, Flags);
1542       }
1543     } else if (VA.isRegLoc()) {
1544       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1545         assert(VA.getLocVT() == MVT::i32 &&
1546                "unexpected calling convention register assignment");
1547         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1548                "unexpected use of 'returned'");
1549         isThisReturn = true;
1550       }
1551       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1552     } else if (isByVal) {
1553       assert(VA.isMemLoc());
1554       unsigned offset = 0;
1555
1556       // True if this byval aggregate will be split between registers
1557       // and memory.
1558       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1559       unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1560
1561       if (CurByValIdx < ByValArgsCount) {
1562
1563         unsigned RegBegin, RegEnd;
1564         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1565
1566         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1567         unsigned int i, j;
1568         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1569           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1570           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1571           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1572                                      MachinePointerInfo(),
1573                                      false, false, false,
1574                                      DAG.InferPtrAlignment(AddArg));
1575           MemOpChains.push_back(Load.getValue(1));
1576           RegsToPass.push_back(std::make_pair(j, Load));
1577         }
1578
1579         // If parameter size outsides register area, "offset" value
1580         // helps us to calculate stack slot for remained part properly.
1581         offset = RegEnd - RegBegin;
1582
1583         CCInfo.nextInRegsParam();
1584       }
1585
1586       if (Flags.getByValSize() > 4*offset) {
1587         unsigned LocMemOffset = VA.getLocMemOffset();
1588         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1589         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1590                                   StkPtrOff);
1591         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1592         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1593         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1594                                            MVT::i32);
1595         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1596
1597         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1598         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1599         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1600                                           Ops, array_lengthof(Ops)));
1601       }
1602     } else if (!isSibCall) {
1603       assert(VA.isMemLoc());
1604
1605       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1606                                              dl, DAG, VA, Flags));
1607     }
1608   }
1609
1610   if (!MemOpChains.empty())
1611     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1612                         &MemOpChains[0], MemOpChains.size());
1613
1614   // Build a sequence of copy-to-reg nodes chained together with token chain
1615   // and flag operands which copy the outgoing args into the appropriate regs.
1616   SDValue InFlag;
1617   // Tail call byval lowering might overwrite argument registers so in case of
1618   // tail call optimization the copies to registers are lowered later.
1619   if (!isTailCall)
1620     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1621       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1622                                RegsToPass[i].second, InFlag);
1623       InFlag = Chain.getValue(1);
1624     }
1625
1626   // For tail calls lower the arguments to the 'real' stack slot.
1627   if (isTailCall) {
1628     // Force all the incoming stack arguments to be loaded from the stack
1629     // before any new outgoing arguments are stored to the stack, because the
1630     // outgoing stack slots may alias the incoming argument stack slots, and
1631     // the alias isn't otherwise explicit. This is slightly more conservative
1632     // than necessary, because it means that each store effectively depends
1633     // on every argument instead of just those arguments it would clobber.
1634
1635     // Do not flag preceding copytoreg stuff together with the following stuff.
1636     InFlag = SDValue();
1637     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1638       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1639                                RegsToPass[i].second, InFlag);
1640       InFlag = Chain.getValue(1);
1641     }
1642     InFlag = SDValue();
1643   }
1644
1645   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1646   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1647   // node so that legalize doesn't hack it.
1648   bool isDirect = false;
1649   bool isARMFunc = false;
1650   bool isLocalARMFunc = false;
1651   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1652
1653   if (EnableARMLongCalls) {
1654     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1655             && "long-calls with non-static relocation model!");
1656     // Handle a global address or an external symbol. If it's not one of
1657     // those, the target's already in a register, so we don't need to do
1658     // anything extra.
1659     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1660       const GlobalValue *GV = G->getGlobal();
1661       // Create a constant pool entry for the callee address
1662       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1663       ARMConstantPoolValue *CPV =
1664         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1665
1666       // Get the address of the callee into a register
1667       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1668       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1669       Callee = DAG.getLoad(getPointerTy(), dl,
1670                            DAG.getEntryNode(), CPAddr,
1671                            MachinePointerInfo::getConstantPool(),
1672                            false, false, false, 0);
1673     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1674       const char *Sym = S->getSymbol();
1675
1676       // Create a constant pool entry for the callee address
1677       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1678       ARMConstantPoolValue *CPV =
1679         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1680                                       ARMPCLabelIndex, 0);
1681       // Get the address of the callee into a register
1682       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1683       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1684       Callee = DAG.getLoad(getPointerTy(), dl,
1685                            DAG.getEntryNode(), CPAddr,
1686                            MachinePointerInfo::getConstantPool(),
1687                            false, false, false, 0);
1688     }
1689   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1690     const GlobalValue *GV = G->getGlobal();
1691     isDirect = true;
1692     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1693     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1694                    getTargetMachine().getRelocationModel() != Reloc::Static;
1695     isARMFunc = !Subtarget->isThumb() || isStub;
1696     // ARM call to a local ARM function is predicable.
1697     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1698     // tBX takes a register source operand.
1699     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1700       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1701       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1702                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy()));
1703     } else {
1704       // On ELF targets for PIC code, direct calls should go through the PLT
1705       unsigned OpFlags = 0;
1706       if (Subtarget->isTargetELF() &&
1707           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1708         OpFlags = ARMII::MO_PLT;
1709       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1710     }
1711   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1712     isDirect = true;
1713     bool isStub = Subtarget->isTargetMachO() &&
1714                   getTargetMachine().getRelocationModel() != Reloc::Static;
1715     isARMFunc = !Subtarget->isThumb() || isStub;
1716     // tBX takes a register source operand.
1717     const char *Sym = S->getSymbol();
1718     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1719       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1720       ARMConstantPoolValue *CPV =
1721         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1722                                       ARMPCLabelIndex, 4);
1723       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1724       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1725       Callee = DAG.getLoad(getPointerTy(), dl,
1726                            DAG.getEntryNode(), CPAddr,
1727                            MachinePointerInfo::getConstantPool(),
1728                            false, false, false, 0);
1729       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1730       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1731                            getPointerTy(), Callee, PICLabel);
1732     } else {
1733       unsigned OpFlags = 0;
1734       // On ELF targets for PIC code, direct calls should go through the PLT
1735       if (Subtarget->isTargetELF() &&
1736                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1737         OpFlags = ARMII::MO_PLT;
1738       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1739     }
1740   }
1741
1742   // FIXME: handle tail calls differently.
1743   unsigned CallOpc;
1744   bool HasMinSizeAttr = Subtarget->isMinSize();
1745   if (Subtarget->isThumb()) {
1746     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1747       CallOpc = ARMISD::CALL_NOLINK;
1748     else
1749       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1750   } else {
1751     if (!isDirect && !Subtarget->hasV5TOps())
1752       CallOpc = ARMISD::CALL_NOLINK;
1753     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1754                // Emit regular call when code size is the priority
1755                !HasMinSizeAttr)
1756       // "mov lr, pc; b _foo" to avoid confusing the RSP
1757       CallOpc = ARMISD::CALL_NOLINK;
1758     else
1759       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1760   }
1761
1762   std::vector<SDValue> Ops;
1763   Ops.push_back(Chain);
1764   Ops.push_back(Callee);
1765
1766   // Add argument registers to the end of the list so that they are known live
1767   // into the call.
1768   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1769     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1770                                   RegsToPass[i].second.getValueType()));
1771
1772   // Add a register mask operand representing the call-preserved registers.
1773   if (!isTailCall) {
1774     const uint32_t *Mask;
1775     const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1776     const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1777     if (isThisReturn) {
1778       // For 'this' returns, use the R0-preserving mask if applicable
1779       Mask = ARI->getThisReturnPreservedMask(CallConv);
1780       if (!Mask) {
1781         // Set isThisReturn to false if the calling convention is not one that
1782         // allows 'returned' to be modeled in this way, so LowerCallResult does
1783         // not try to pass 'this' straight through
1784         isThisReturn = false;
1785         Mask = ARI->getCallPreservedMask(CallConv);
1786       }
1787     } else
1788       Mask = ARI->getCallPreservedMask(CallConv);
1789
1790     assert(Mask && "Missing call preserved mask for calling convention");
1791     Ops.push_back(DAG.getRegisterMask(Mask));
1792   }
1793
1794   if (InFlag.getNode())
1795     Ops.push_back(InFlag);
1796
1797   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1798   if (isTailCall)
1799     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1800
1801   // Returns a chain and a flag for retval copy to use.
1802   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1803   InFlag = Chain.getValue(1);
1804
1805   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1806                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1807   if (!Ins.empty())
1808     InFlag = Chain.getValue(1);
1809
1810   // Handle result values, copying them out of physregs into vregs that we
1811   // return.
1812   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1813                          InVals, isThisReturn,
1814                          isThisReturn ? OutVals[0] : SDValue());
1815 }
1816
1817 /// HandleByVal - Every parameter *after* a byval parameter is passed
1818 /// on the stack.  Remember the next parameter register to allocate,
1819 /// and then confiscate the rest of the parameter registers to insure
1820 /// this.
1821 void
1822 ARMTargetLowering::HandleByVal(
1823     CCState *State, unsigned &size, unsigned Align) const {
1824   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1825   assert((State->getCallOrPrologue() == Prologue ||
1826           State->getCallOrPrologue() == Call) &&
1827          "unhandled ParmContext");
1828
1829   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1830     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1831       unsigned AlignInRegs = Align / 4;
1832       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1833       for (unsigned i = 0; i < Waste; ++i)
1834         reg = State->AllocateReg(GPRArgRegs, 4);
1835     }
1836     if (reg != 0) {
1837       unsigned excess = 4 * (ARM::R4 - reg);
1838
1839       // Special case when NSAA != SP and parameter size greater than size of
1840       // all remained GPR regs. In that case we can't split parameter, we must
1841       // send it to stack. We also must set NCRN to R4, so waste all
1842       // remained registers.
1843       const unsigned NSAAOffset = State->getNextStackOffset();
1844       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1845         while (State->AllocateReg(GPRArgRegs, 4))
1846           ;
1847         return;
1848       }
1849
1850       // First register for byval parameter is the first register that wasn't
1851       // allocated before this method call, so it would be "reg".
1852       // If parameter is small enough to be saved in range [reg, r4), then
1853       // the end (first after last) register would be reg + param-size-in-regs,
1854       // else parameter would be splitted between registers and stack,
1855       // end register would be r4 in this case.
1856       unsigned ByValRegBegin = reg;
1857       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1858       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1859       // Note, first register is allocated in the beginning of function already,
1860       // allocate remained amount of registers we need.
1861       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1862         State->AllocateReg(GPRArgRegs, 4);
1863       // A byval parameter that is split between registers and memory needs its
1864       // size truncated here.
1865       // In the case where the entire structure fits in registers, we set the
1866       // size in memory to zero.
1867       if (size < excess)
1868         size = 0;
1869       else
1870         size -= excess;
1871     }
1872   }
1873 }
1874
1875 /// MatchingStackOffset - Return true if the given stack call argument is
1876 /// already available in the same position (relatively) of the caller's
1877 /// incoming argument stack.
1878 static
1879 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1880                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1881                          const TargetInstrInfo *TII) {
1882   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1883   int FI = INT_MAX;
1884   if (Arg.getOpcode() == ISD::CopyFromReg) {
1885     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1886     if (!TargetRegisterInfo::isVirtualRegister(VR))
1887       return false;
1888     MachineInstr *Def = MRI->getVRegDef(VR);
1889     if (!Def)
1890       return false;
1891     if (!Flags.isByVal()) {
1892       if (!TII->isLoadFromStackSlot(Def, FI))
1893         return false;
1894     } else {
1895       return false;
1896     }
1897   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1898     if (Flags.isByVal())
1899       // ByVal argument is passed in as a pointer but it's now being
1900       // dereferenced. e.g.
1901       // define @foo(%struct.X* %A) {
1902       //   tail call @bar(%struct.X* byval %A)
1903       // }
1904       return false;
1905     SDValue Ptr = Ld->getBasePtr();
1906     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1907     if (!FINode)
1908       return false;
1909     FI = FINode->getIndex();
1910   } else
1911     return false;
1912
1913   assert(FI != INT_MAX);
1914   if (!MFI->isFixedObjectIndex(FI))
1915     return false;
1916   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1917 }
1918
1919 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1920 /// for tail call optimization. Targets which want to do tail call
1921 /// optimization should implement this function.
1922 bool
1923 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1924                                                      CallingConv::ID CalleeCC,
1925                                                      bool isVarArg,
1926                                                      bool isCalleeStructRet,
1927                                                      bool isCallerStructRet,
1928                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1929                                     const SmallVectorImpl<SDValue> &OutVals,
1930                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1931                                                      SelectionDAG& DAG) const {
1932   const Function *CallerF = DAG.getMachineFunction().getFunction();
1933   CallingConv::ID CallerCC = CallerF->getCallingConv();
1934   bool CCMatch = CallerCC == CalleeCC;
1935
1936   // Look for obvious safe cases to perform tail call optimization that do not
1937   // require ABI changes. This is what gcc calls sibcall.
1938
1939   // Do not sibcall optimize vararg calls unless the call site is not passing
1940   // any arguments.
1941   if (isVarArg && !Outs.empty())
1942     return false;
1943
1944   // Exception-handling functions need a special set of instructions to indicate
1945   // a return to the hardware. Tail-calling another function would probably
1946   // break this.
1947   if (CallerF->hasFnAttribute("interrupt"))
1948     return false;
1949
1950   // Also avoid sibcall optimization if either caller or callee uses struct
1951   // return semantics.
1952   if (isCalleeStructRet || isCallerStructRet)
1953     return false;
1954
1955   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1956   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1957   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1958   // support in the assembler and linker to be used. This would need to be
1959   // fixed to fully support tail calls in Thumb1.
1960   //
1961   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1962   // LR.  This means if we need to reload LR, it takes an extra instructions,
1963   // which outweighs the value of the tail call; but here we don't know yet
1964   // whether LR is going to be used.  Probably the right approach is to
1965   // generate the tail call here and turn it back into CALL/RET in
1966   // emitEpilogue if LR is used.
1967
1968   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1969   // but we need to make sure there are enough registers; the only valid
1970   // registers are the 4 used for parameters.  We don't currently do this
1971   // case.
1972   if (Subtarget->isThumb1Only())
1973     return false;
1974
1975   // If the calling conventions do not match, then we'd better make sure the
1976   // results are returned in the same way as what the caller expects.
1977   if (!CCMatch) {
1978     SmallVector<CCValAssign, 16> RVLocs1;
1979     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1980                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1981     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1982
1983     SmallVector<CCValAssign, 16> RVLocs2;
1984     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1985                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1986     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1987
1988     if (RVLocs1.size() != RVLocs2.size())
1989       return false;
1990     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1991       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1992         return false;
1993       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1994         return false;
1995       if (RVLocs1[i].isRegLoc()) {
1996         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1997           return false;
1998       } else {
1999         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2000           return false;
2001       }
2002     }
2003   }
2004
2005   // If Caller's vararg or byval argument has been split between registers and
2006   // stack, do not perform tail call, since part of the argument is in caller's
2007   // local frame.
2008   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2009                                       getInfo<ARMFunctionInfo>();
2010   if (AFI_Caller->getArgRegsSaveSize())
2011     return false;
2012
2013   // If the callee takes no arguments then go on to check the results of the
2014   // call.
2015   if (!Outs.empty()) {
2016     // Check if stack adjustment is needed. For now, do not do this if any
2017     // argument is passed on the stack.
2018     SmallVector<CCValAssign, 16> ArgLocs;
2019     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2020                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
2021     CCInfo.AnalyzeCallOperands(Outs,
2022                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2023     if (CCInfo.getNextStackOffset()) {
2024       MachineFunction &MF = DAG.getMachineFunction();
2025
2026       // Check if the arguments are already laid out in the right way as
2027       // the caller's fixed stack objects.
2028       MachineFrameInfo *MFI = MF.getFrameInfo();
2029       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2030       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2031       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2032            i != e;
2033            ++i, ++realArgIdx) {
2034         CCValAssign &VA = ArgLocs[i];
2035         EVT RegVT = VA.getLocVT();
2036         SDValue Arg = OutVals[realArgIdx];
2037         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2038         if (VA.getLocInfo() == CCValAssign::Indirect)
2039           return false;
2040         if (VA.needsCustom()) {
2041           // f64 and vector types are split into multiple registers or
2042           // register/stack-slot combinations.  The types will not match
2043           // the registers; give up on memory f64 refs until we figure
2044           // out what to do about this.
2045           if (!VA.isRegLoc())
2046             return false;
2047           if (!ArgLocs[++i].isRegLoc())
2048             return false;
2049           if (RegVT == MVT::v2f64) {
2050             if (!ArgLocs[++i].isRegLoc())
2051               return false;
2052             if (!ArgLocs[++i].isRegLoc())
2053               return false;
2054           }
2055         } else if (!VA.isRegLoc()) {
2056           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2057                                    MFI, MRI, TII))
2058             return false;
2059         }
2060       }
2061     }
2062   }
2063
2064   return true;
2065 }
2066
2067 bool
2068 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2069                                   MachineFunction &MF, bool isVarArg,
2070                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2071                                   LLVMContext &Context) const {
2072   SmallVector<CCValAssign, 16> RVLocs;
2073   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2074   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2075                                                     isVarArg));
2076 }
2077
2078 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2079                                     SDLoc DL, SelectionDAG &DAG) {
2080   const MachineFunction &MF = DAG.getMachineFunction();
2081   const Function *F = MF.getFunction();
2082
2083   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2084
2085   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2086   // version of the "preferred return address". These offsets affect the return
2087   // instruction if this is a return from PL1 without hypervisor extensions.
2088   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2089   //    SWI:     0      "subs pc, lr, #0"
2090   //    ABORT:   +4     "subs pc, lr, #4"
2091   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2092   // UNDEF varies depending on where the exception came from ARM or Thumb
2093   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2094
2095   int64_t LROffset;
2096   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2097       IntKind == "ABORT")
2098     LROffset = 4;
2099   else if (IntKind == "SWI" || IntKind == "UNDEF")
2100     LROffset = 0;
2101   else
2102     report_fatal_error("Unsupported interrupt attribute. If present, value "
2103                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2104
2105   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2106
2107   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other,
2108                      RetOps.data(), RetOps.size());
2109 }
2110
2111 SDValue
2112 ARMTargetLowering::LowerReturn(SDValue Chain,
2113                                CallingConv::ID CallConv, bool isVarArg,
2114                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2115                                const SmallVectorImpl<SDValue> &OutVals,
2116                                SDLoc dl, SelectionDAG &DAG) const {
2117
2118   // CCValAssign - represent the assignment of the return value to a location.
2119   SmallVector<CCValAssign, 16> RVLocs;
2120
2121   // CCState - Info about the registers and stack slots.
2122   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2123                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2124
2125   // Analyze outgoing return values.
2126   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2127                                                isVarArg));
2128
2129   SDValue Flag;
2130   SmallVector<SDValue, 4> RetOps;
2131   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2132
2133   // Copy the result values into the output registers.
2134   for (unsigned i = 0, realRVLocIdx = 0;
2135        i != RVLocs.size();
2136        ++i, ++realRVLocIdx) {
2137     CCValAssign &VA = RVLocs[i];
2138     assert(VA.isRegLoc() && "Can only return in registers!");
2139
2140     SDValue Arg = OutVals[realRVLocIdx];
2141
2142     switch (VA.getLocInfo()) {
2143     default: llvm_unreachable("Unknown loc info!");
2144     case CCValAssign::Full: break;
2145     case CCValAssign::BCvt:
2146       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2147       break;
2148     }
2149
2150     if (VA.needsCustom()) {
2151       if (VA.getLocVT() == MVT::v2f64) {
2152         // Extract the first half and return it in two registers.
2153         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2154                                    DAG.getConstant(0, MVT::i32));
2155         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2156                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2157
2158         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
2159         Flag = Chain.getValue(1);
2160         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2161         VA = RVLocs[++i]; // skip ahead to next loc
2162         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2163                                  HalfGPRs.getValue(1), Flag);
2164         Flag = Chain.getValue(1);
2165         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2166         VA = RVLocs[++i]; // skip ahead to next loc
2167
2168         // Extract the 2nd half and fall through to handle it as an f64 value.
2169         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2170                           DAG.getConstant(1, MVT::i32));
2171       }
2172       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2173       // available.
2174       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2175                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
2176       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
2177       Flag = Chain.getValue(1);
2178       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2179       VA = RVLocs[++i]; // skip ahead to next loc
2180       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
2181                                Flag);
2182     } else
2183       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2184
2185     // Guarantee that all emitted copies are
2186     // stuck together, avoiding something bad.
2187     Flag = Chain.getValue(1);
2188     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2189   }
2190
2191   // Update chain and glue.
2192   RetOps[0] = Chain;
2193   if (Flag.getNode())
2194     RetOps.push_back(Flag);
2195
2196   // CPUs which aren't M-class use a special sequence to return from
2197   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2198   // though we use "subs pc, lr, #N").
2199   //
2200   // M-class CPUs actually use a normal return sequence with a special
2201   // (hardware-provided) value in LR, so the normal code path works.
2202   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2203       !Subtarget->isMClass()) {
2204     if (Subtarget->isThumb1Only())
2205       report_fatal_error("interrupt attribute is not supported in Thumb1");
2206     return LowerInterruptReturn(RetOps, dl, DAG);
2207   }
2208
2209   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
2210                      RetOps.data(), RetOps.size());
2211 }
2212
2213 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2214   if (N->getNumValues() != 1)
2215     return false;
2216   if (!N->hasNUsesOfValue(1, 0))
2217     return false;
2218
2219   SDValue TCChain = Chain;
2220   SDNode *Copy = *N->use_begin();
2221   if (Copy->getOpcode() == ISD::CopyToReg) {
2222     // If the copy has a glue operand, we conservatively assume it isn't safe to
2223     // perform a tail call.
2224     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2225       return false;
2226     TCChain = Copy->getOperand(0);
2227   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2228     SDNode *VMov = Copy;
2229     // f64 returned in a pair of GPRs.
2230     SmallPtrSet<SDNode*, 2> Copies;
2231     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2232          UI != UE; ++UI) {
2233       if (UI->getOpcode() != ISD::CopyToReg)
2234         return false;
2235       Copies.insert(*UI);
2236     }
2237     if (Copies.size() > 2)
2238       return false;
2239
2240     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2241          UI != UE; ++UI) {
2242       SDValue UseChain = UI->getOperand(0);
2243       if (Copies.count(UseChain.getNode()))
2244         // Second CopyToReg
2245         Copy = *UI;
2246       else
2247         // First CopyToReg
2248         TCChain = UseChain;
2249     }
2250   } else if (Copy->getOpcode() == ISD::BITCAST) {
2251     // f32 returned in a single GPR.
2252     if (!Copy->hasOneUse())
2253       return false;
2254     Copy = *Copy->use_begin();
2255     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2256       return false;
2257     TCChain = Copy->getOperand(0);
2258   } else {
2259     return false;
2260   }
2261
2262   bool HasRet = false;
2263   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2264        UI != UE; ++UI) {
2265     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2266         UI->getOpcode() != ARMISD::INTRET_FLAG)
2267       return false;
2268     HasRet = true;
2269   }
2270
2271   if (!HasRet)
2272     return false;
2273
2274   Chain = TCChain;
2275   return true;
2276 }
2277
2278 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2279   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2280     return false;
2281
2282   if (!CI->isTailCall())
2283     return false;
2284
2285   return !Subtarget->isThumb1Only();
2286 }
2287
2288 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2289 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2290 // one of the above mentioned nodes. It has to be wrapped because otherwise
2291 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2292 // be used to form addressing mode. These wrapped nodes will be selected
2293 // into MOVi.
2294 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2295   EVT PtrVT = Op.getValueType();
2296   // FIXME there is no actual debug info here
2297   SDLoc dl(Op);
2298   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2299   SDValue Res;
2300   if (CP->isMachineConstantPoolEntry())
2301     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2302                                     CP->getAlignment());
2303   else
2304     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2305                                     CP->getAlignment());
2306   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2307 }
2308
2309 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2310   return MachineJumpTableInfo::EK_Inline;
2311 }
2312
2313 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2314                                              SelectionDAG &DAG) const {
2315   MachineFunction &MF = DAG.getMachineFunction();
2316   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2317   unsigned ARMPCLabelIndex = 0;
2318   SDLoc DL(Op);
2319   EVT PtrVT = getPointerTy();
2320   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2321   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2322   SDValue CPAddr;
2323   if (RelocM == Reloc::Static) {
2324     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2325   } else {
2326     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2327     ARMPCLabelIndex = AFI->createPICLabelUId();
2328     ARMConstantPoolValue *CPV =
2329       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2330                                       ARMCP::CPBlockAddress, PCAdj);
2331     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2332   }
2333   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2334   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2335                                MachinePointerInfo::getConstantPool(),
2336                                false, false, false, 0);
2337   if (RelocM == Reloc::Static)
2338     return Result;
2339   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2340   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2341 }
2342
2343 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2344 SDValue
2345 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2346                                                  SelectionDAG &DAG) const {
2347   SDLoc dl(GA);
2348   EVT PtrVT = getPointerTy();
2349   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2350   MachineFunction &MF = DAG.getMachineFunction();
2351   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2352   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2353   ARMConstantPoolValue *CPV =
2354     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2355                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2356   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2357   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2358   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2359                          MachinePointerInfo::getConstantPool(),
2360                          false, false, false, 0);
2361   SDValue Chain = Argument.getValue(1);
2362
2363   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2364   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2365
2366   // call __tls_get_addr.
2367   ArgListTy Args;
2368   ArgListEntry Entry;
2369   Entry.Node = Argument;
2370   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2371   Args.push_back(Entry);
2372   // FIXME: is there useful debug info available here?
2373   TargetLowering::CallLoweringInfo CLI(Chain,
2374                 (Type *) Type::getInt32Ty(*DAG.getContext()),
2375                 false, false, false, false,
2376                 0, CallingConv::C, /*isTailCall=*/false,
2377                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2378                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2379   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2380   return CallResult.first;
2381 }
2382
2383 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2384 // "local exec" model.
2385 SDValue
2386 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2387                                         SelectionDAG &DAG,
2388                                         TLSModel::Model model) const {
2389   const GlobalValue *GV = GA->getGlobal();
2390   SDLoc dl(GA);
2391   SDValue Offset;
2392   SDValue Chain = DAG.getEntryNode();
2393   EVT PtrVT = getPointerTy();
2394   // Get the Thread Pointer
2395   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2396
2397   if (model == TLSModel::InitialExec) {
2398     MachineFunction &MF = DAG.getMachineFunction();
2399     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2400     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2401     // Initial exec model.
2402     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2403     ARMConstantPoolValue *CPV =
2404       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2405                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2406                                       true);
2407     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2408     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2409     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2410                          MachinePointerInfo::getConstantPool(),
2411                          false, false, false, 0);
2412     Chain = Offset.getValue(1);
2413
2414     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2415     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2416
2417     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2418                          MachinePointerInfo::getConstantPool(),
2419                          false, false, false, 0);
2420   } else {
2421     // local exec model
2422     assert(model == TLSModel::LocalExec);
2423     ARMConstantPoolValue *CPV =
2424       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2425     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2426     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2427     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2428                          MachinePointerInfo::getConstantPool(),
2429                          false, false, false, 0);
2430   }
2431
2432   // The address of the thread local variable is the add of the thread
2433   // pointer with the offset of the variable.
2434   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2435 }
2436
2437 SDValue
2438 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2439   // TODO: implement the "local dynamic" model
2440   assert(Subtarget->isTargetELF() &&
2441          "TLS not implemented for non-ELF targets");
2442   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2443
2444   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2445
2446   switch (model) {
2447     case TLSModel::GeneralDynamic:
2448     case TLSModel::LocalDynamic:
2449       return LowerToTLSGeneralDynamicModel(GA, DAG);
2450     case TLSModel::InitialExec:
2451     case TLSModel::LocalExec:
2452       return LowerToTLSExecModels(GA, DAG, model);
2453   }
2454   llvm_unreachable("bogus TLS model");
2455 }
2456
2457 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2458                                                  SelectionDAG &DAG) const {
2459   EVT PtrVT = getPointerTy();
2460   SDLoc dl(Op);
2461   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2462   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2463     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2464     ARMConstantPoolValue *CPV =
2465       ARMConstantPoolConstant::Create(GV,
2466                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2467     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2468     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2469     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2470                                  CPAddr,
2471                                  MachinePointerInfo::getConstantPool(),
2472                                  false, false, false, 0);
2473     SDValue Chain = Result.getValue(1);
2474     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2475     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2476     if (!UseGOTOFF)
2477       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2478                            MachinePointerInfo::getGOT(),
2479                            false, false, false, 0);
2480     return Result;
2481   }
2482
2483   // If we have T2 ops, we can materialize the address directly via movt/movw
2484   // pair. This is always cheaper.
2485   if (Subtarget->useMovt()) {
2486     ++NumMovwMovt;
2487     // FIXME: Once remat is capable of dealing with instructions with register
2488     // operands, expand this into two nodes.
2489     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2490                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2491   } else {
2492     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2493     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2494     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2495                        MachinePointerInfo::getConstantPool(),
2496                        false, false, false, 0);
2497   }
2498 }
2499
2500 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2501                                                     SelectionDAG &DAG) const {
2502   EVT PtrVT = getPointerTy();
2503   SDLoc dl(Op);
2504   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2505   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2506
2507   if (Subtarget->useMovt())
2508     ++NumMovwMovt;
2509
2510   // FIXME: Once remat is capable of dealing with instructions with register
2511   // operands, expand this into multiple nodes
2512   unsigned Wrapper =
2513       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2514
2515   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2516   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2517
2518   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2519     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2520                          MachinePointerInfo::getGOT(), false, false, false, 0);
2521   return Result;
2522 }
2523
2524 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2525                                                     SelectionDAG &DAG) const {
2526   assert(Subtarget->isTargetELF() &&
2527          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2528   MachineFunction &MF = DAG.getMachineFunction();
2529   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2530   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2531   EVT PtrVT = getPointerTy();
2532   SDLoc dl(Op);
2533   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2534   ARMConstantPoolValue *CPV =
2535     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2536                                   ARMPCLabelIndex, PCAdj);
2537   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2538   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2539   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2540                                MachinePointerInfo::getConstantPool(),
2541                                false, false, false, 0);
2542   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2543   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2544 }
2545
2546 SDValue
2547 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2548   SDLoc dl(Op);
2549   SDValue Val = DAG.getConstant(0, MVT::i32);
2550   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2551                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2552                      Op.getOperand(1), Val);
2553 }
2554
2555 SDValue
2556 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2557   SDLoc dl(Op);
2558   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2559                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2560 }
2561
2562 SDValue
2563 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2564                                           const ARMSubtarget *Subtarget) const {
2565   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2566   SDLoc dl(Op);
2567   switch (IntNo) {
2568   default: return SDValue();    // Don't custom lower most intrinsics.
2569   case Intrinsic::arm_thread_pointer: {
2570     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2571     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2572   }
2573   case Intrinsic::eh_sjlj_lsda: {
2574     MachineFunction &MF = DAG.getMachineFunction();
2575     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2576     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2577     EVT PtrVT = getPointerTy();
2578     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2579     SDValue CPAddr;
2580     unsigned PCAdj = (RelocM != Reloc::PIC_)
2581       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2582     ARMConstantPoolValue *CPV =
2583       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2584                                       ARMCP::CPLSDA, PCAdj);
2585     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2586     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2587     SDValue Result =
2588       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2589                   MachinePointerInfo::getConstantPool(),
2590                   false, false, false, 0);
2591
2592     if (RelocM == Reloc::PIC_) {
2593       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2594       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2595     }
2596     return Result;
2597   }
2598   case Intrinsic::arm_neon_vmulls:
2599   case Intrinsic::arm_neon_vmullu: {
2600     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2601       ? ARMISD::VMULLs : ARMISD::VMULLu;
2602     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2603                        Op.getOperand(1), Op.getOperand(2));
2604   }
2605   }
2606 }
2607
2608 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2609                                  const ARMSubtarget *Subtarget) {
2610   // FIXME: handle "fence singlethread" more efficiently.
2611   SDLoc dl(Op);
2612   if (!Subtarget->hasDataBarrier()) {
2613     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2614     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2615     // here.
2616     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2617            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2618     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2619                        DAG.getConstant(0, MVT::i32));
2620   }
2621
2622   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2623   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2624   unsigned Domain = ARM_MB::ISH;
2625   if (Subtarget->isMClass()) {
2626     // Only a full system barrier exists in the M-class architectures.
2627     Domain = ARM_MB::SY;
2628   } else if (Subtarget->isSwift() && Ord == Release) {
2629     // Swift happens to implement ISHST barriers in a way that's compatible with
2630     // Release semantics but weaker than ISH so we'd be fools not to use
2631     // it. Beware: other processors probably don't!
2632     Domain = ARM_MB::ISHST;
2633   }
2634
2635   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2636                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2637                      DAG.getConstant(Domain, MVT::i32));
2638 }
2639
2640 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2641                              const ARMSubtarget *Subtarget) {
2642   // ARM pre v5TE and Thumb1 does not have preload instructions.
2643   if (!(Subtarget->isThumb2() ||
2644         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2645     // Just preserve the chain.
2646     return Op.getOperand(0);
2647
2648   SDLoc dl(Op);
2649   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2650   if (!isRead &&
2651       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2652     // ARMv7 with MP extension has PLDW.
2653     return Op.getOperand(0);
2654
2655   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2656   if (Subtarget->isThumb()) {
2657     // Invert the bits.
2658     isRead = ~isRead & 1;
2659     isData = ~isData & 1;
2660   }
2661
2662   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2663                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2664                      DAG.getConstant(isData, MVT::i32));
2665 }
2666
2667 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2668   MachineFunction &MF = DAG.getMachineFunction();
2669   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2670
2671   // vastart just stores the address of the VarArgsFrameIndex slot into the
2672   // memory location argument.
2673   SDLoc dl(Op);
2674   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2675   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2676   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2677   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2678                       MachinePointerInfo(SV), false, false, 0);
2679 }
2680
2681 SDValue
2682 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2683                                         SDValue &Root, SelectionDAG &DAG,
2684                                         SDLoc dl) const {
2685   MachineFunction &MF = DAG.getMachineFunction();
2686   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2687
2688   const TargetRegisterClass *RC;
2689   if (AFI->isThumb1OnlyFunction())
2690     RC = &ARM::tGPRRegClass;
2691   else
2692     RC = &ARM::GPRRegClass;
2693
2694   // Transform the arguments stored in physical registers into virtual ones.
2695   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2696   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2697
2698   SDValue ArgValue2;
2699   if (NextVA.isMemLoc()) {
2700     MachineFrameInfo *MFI = MF.getFrameInfo();
2701     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2702
2703     // Create load node to retrieve arguments from the stack.
2704     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2705     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2706                             MachinePointerInfo::getFixedStack(FI),
2707                             false, false, false, 0);
2708   } else {
2709     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2710     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2711   }
2712
2713   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2714 }
2715
2716 void
2717 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2718                                   unsigned InRegsParamRecordIdx,
2719                                   unsigned ArgSize,
2720                                   unsigned &ArgRegsSize,
2721                                   unsigned &ArgRegsSaveSize)
2722   const {
2723   unsigned NumGPRs;
2724   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2725     unsigned RBegin, REnd;
2726     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2727     NumGPRs = REnd - RBegin;
2728   } else {
2729     unsigned int firstUnalloced;
2730     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2731                                                 sizeof(GPRArgRegs) /
2732                                                 sizeof(GPRArgRegs[0]));
2733     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2734   }
2735
2736   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2737   ArgRegsSize = NumGPRs * 4;
2738
2739   // If parameter is split between stack and GPRs...
2740   if (NumGPRs && Align > 4 &&
2741       (ArgRegsSize < ArgSize ||
2742         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2743     // Add padding for part of param recovered from GPRs.  For example,
2744     // if Align == 8, its last byte must be at address K*8 - 1.
2745     // We need to do it, since remained (stack) part of parameter has
2746     // stack alignment, and we need to "attach" "GPRs head" without gaps
2747     // to it:
2748     // Stack:
2749     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2750     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2751     //
2752     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2753     unsigned Padding =
2754         OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2755     ArgRegsSaveSize = ArgRegsSize + Padding;
2756   } else
2757     // We don't need to extend regs save size for byval parameters if they
2758     // are passed via GPRs only.
2759     ArgRegsSaveSize = ArgRegsSize;
2760 }
2761
2762 // The remaining GPRs hold either the beginning of variable-argument
2763 // data, or the beginning of an aggregate passed by value (usually
2764 // byval).  Either way, we allocate stack slots adjacent to the data
2765 // provided by our caller, and store the unallocated registers there.
2766 // If this is a variadic function, the va_list pointer will begin with
2767 // these values; otherwise, this reassembles a (byval) structure that
2768 // was split between registers and memory.
2769 // Return: The frame index registers were stored into.
2770 int
2771 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2772                                   SDLoc dl, SDValue &Chain,
2773                                   const Value *OrigArg,
2774                                   unsigned InRegsParamRecordIdx,
2775                                   unsigned OffsetFromOrigArg,
2776                                   unsigned ArgOffset,
2777                                   unsigned ArgSize,
2778                                   bool ForceMutable,
2779                                   unsigned ByValStoreOffset,
2780                                   unsigned TotalArgRegsSaveSize) const {
2781
2782   // Currently, two use-cases possible:
2783   // Case #1. Non-var-args function, and we meet first byval parameter.
2784   //          Setup first unallocated register as first byval register;
2785   //          eat all remained registers
2786   //          (these two actions are performed by HandleByVal method).
2787   //          Then, here, we initialize stack frame with
2788   //          "store-reg" instructions.
2789   // Case #2. Var-args function, that doesn't contain byval parameters.
2790   //          The same: eat all remained unallocated registers,
2791   //          initialize stack frame.
2792
2793   MachineFunction &MF = DAG.getMachineFunction();
2794   MachineFrameInfo *MFI = MF.getFrameInfo();
2795   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2796   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2797   unsigned RBegin, REnd;
2798   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2799     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2800     firstRegToSaveIndex = RBegin - ARM::R0;
2801     lastRegToSaveIndex = REnd - ARM::R0;
2802   } else {
2803     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2804       (GPRArgRegs, array_lengthof(GPRArgRegs));
2805     lastRegToSaveIndex = 4;
2806   }
2807
2808   unsigned ArgRegsSize, ArgRegsSaveSize;
2809   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2810                  ArgRegsSize, ArgRegsSaveSize);
2811
2812   // Store any by-val regs to their spots on the stack so that they may be
2813   // loaded by deferencing the result of formal parameter pointer or va_next.
2814   // Note: once stack area for byval/varargs registers
2815   // was initialized, it can't be initialized again.
2816   if (ArgRegsSaveSize) {
2817     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2818
2819     if (Padding) {
2820       assert(AFI->getStoredByValParamsPadding() == 0 &&
2821              "The only parameter may be padded.");
2822       AFI->setStoredByValParamsPadding(Padding);
2823     }
2824
2825     int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2826                                             Padding +
2827                                               ByValStoreOffset -
2828                                               (int64_t)TotalArgRegsSaveSize,
2829                                             false);
2830     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2831     if (Padding) {
2832        MFI->CreateFixedObject(Padding,
2833                               ArgOffset + ByValStoreOffset -
2834                                 (int64_t)ArgRegsSaveSize,
2835                               false);
2836     }
2837
2838     SmallVector<SDValue, 4> MemOps;
2839     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2840          ++firstRegToSaveIndex, ++i) {
2841       const TargetRegisterClass *RC;
2842       if (AFI->isThumb1OnlyFunction())
2843         RC = &ARM::tGPRRegClass;
2844       else
2845         RC = &ARM::GPRRegClass;
2846
2847       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2848       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2849       SDValue Store =
2850         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2851                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2852                      false, false, 0);
2853       MemOps.push_back(Store);
2854       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2855                         DAG.getConstant(4, getPointerTy()));
2856     }
2857
2858     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2859
2860     if (!MemOps.empty())
2861       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2862                           &MemOps[0], MemOps.size());
2863     return FrameIndex;
2864   } else {
2865     if (ArgSize == 0) {
2866       // We cannot allocate a zero-byte object for the first variadic argument,
2867       // so just make up a size.
2868       ArgSize = 4;
2869     }
2870     // This will point to the next argument passed via stack.
2871     return MFI->CreateFixedObject(
2872       ArgSize, ArgOffset, !ForceMutable);
2873   }
2874 }
2875
2876 // Setup stack frame, the va_list pointer will start from.
2877 void
2878 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2879                                         SDLoc dl, SDValue &Chain,
2880                                         unsigned ArgOffset,
2881                                         unsigned TotalArgRegsSaveSize,
2882                                         bool ForceMutable) const {
2883   MachineFunction &MF = DAG.getMachineFunction();
2884   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2885
2886   // Try to store any remaining integer argument regs
2887   // to their spots on the stack so that they may be loaded by deferencing
2888   // the result of va_next.
2889   // If there is no regs to be stored, just point address after last
2890   // argument passed via stack.
2891   int FrameIndex =
2892     StoreByValRegs(CCInfo, DAG, dl, Chain, 0, CCInfo.getInRegsParamsCount(),
2893                    0, ArgOffset, 0, ForceMutable, 0, TotalArgRegsSaveSize);
2894
2895   AFI->setVarArgsFrameIndex(FrameIndex);
2896 }
2897
2898 SDValue
2899 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2900                                         CallingConv::ID CallConv, bool isVarArg,
2901                                         const SmallVectorImpl<ISD::InputArg>
2902                                           &Ins,
2903                                         SDLoc dl, SelectionDAG &DAG,
2904                                         SmallVectorImpl<SDValue> &InVals)
2905                                           const {
2906   MachineFunction &MF = DAG.getMachineFunction();
2907   MachineFrameInfo *MFI = MF.getFrameInfo();
2908
2909   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2910
2911   // Assign locations to all of the incoming arguments.
2912   SmallVector<CCValAssign, 16> ArgLocs;
2913   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2914                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2915   CCInfo.AnalyzeFormalArguments(Ins,
2916                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2917                                                   isVarArg));
2918
2919   SmallVector<SDValue, 16> ArgValues;
2920   int lastInsIndex = -1;
2921   SDValue ArgValue;
2922   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2923   unsigned CurArgIdx = 0;
2924
2925   // Initially ArgRegsSaveSize is zero.
2926   // Then we increase this value each time we meet byval parameter.
2927   // We also increase this value in case of varargs function.
2928   AFI->setArgRegsSaveSize(0);
2929
2930   unsigned ByValStoreOffset = 0;
2931   unsigned TotalArgRegsSaveSize = 0;
2932   unsigned ArgRegsSaveSizeMaxAlign = 4;
2933
2934   // Calculate the amount of stack space that we need to allocate to store
2935   // byval and variadic arguments that are passed in registers.
2936   // We need to know this before we allocate the first byval or variadic
2937   // argument, as they will be allocated a stack slot below the CFA (Canonical
2938   // Frame Address, the stack pointer at entry to the function).
2939   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2940     CCValAssign &VA = ArgLocs[i];
2941     if (VA.isMemLoc()) {
2942       int index = VA.getValNo();
2943       if (index != lastInsIndex) {
2944         ISD::ArgFlagsTy Flags = Ins[index].Flags;
2945         if (Flags.isByVal()) {
2946           unsigned ExtraArgRegsSize;
2947           unsigned ExtraArgRegsSaveSize;
2948           computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
2949                          Flags.getByValSize(),
2950                          ExtraArgRegsSize, ExtraArgRegsSaveSize);
2951
2952           TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2953           if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
2954               ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
2955           CCInfo.nextInRegsParam();
2956         }
2957         lastInsIndex = index;
2958       }
2959     }
2960   }
2961   CCInfo.rewindByValRegsInfo();
2962   lastInsIndex = -1;
2963   if (isVarArg) {
2964     unsigned ExtraArgRegsSize;
2965     unsigned ExtraArgRegsSaveSize;
2966     computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
2967                    ExtraArgRegsSize, ExtraArgRegsSaveSize);
2968     TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2969   }
2970   // If the arg regs save area contains N-byte aligned values, the
2971   // bottom of it must be at least N-byte aligned.
2972   TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
2973   TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
2974
2975   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2976     CCValAssign &VA = ArgLocs[i];
2977     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2978     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2979     // Arguments stored in registers.
2980     if (VA.isRegLoc()) {
2981       EVT RegVT = VA.getLocVT();
2982
2983       if (VA.needsCustom()) {
2984         // f64 and vector types are split up into multiple registers or
2985         // combinations of registers and stack slots.
2986         if (VA.getLocVT() == MVT::v2f64) {
2987           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2988                                                    Chain, DAG, dl);
2989           VA = ArgLocs[++i]; // skip ahead to next loc
2990           SDValue ArgValue2;
2991           if (VA.isMemLoc()) {
2992             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2993             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2994             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2995                                     MachinePointerInfo::getFixedStack(FI),
2996                                     false, false, false, 0);
2997           } else {
2998             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2999                                              Chain, DAG, dl);
3000           }
3001           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3002           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3003                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3004           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3005                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3006         } else
3007           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3008
3009       } else {
3010         const TargetRegisterClass *RC;
3011
3012         if (RegVT == MVT::f32)
3013           RC = &ARM::SPRRegClass;
3014         else if (RegVT == MVT::f64)
3015           RC = &ARM::DPRRegClass;
3016         else if (RegVT == MVT::v2f64)
3017           RC = &ARM::QPRRegClass;
3018         else if (RegVT == MVT::i32)
3019           RC = AFI->isThumb1OnlyFunction() ?
3020             (const TargetRegisterClass*)&ARM::tGPRRegClass :
3021             (const TargetRegisterClass*)&ARM::GPRRegClass;
3022         else
3023           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3024
3025         // Transform the arguments in physical registers into virtual ones.
3026         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3027         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3028       }
3029
3030       // If this is an 8 or 16-bit value, it is really passed promoted
3031       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3032       // truncate to the right size.
3033       switch (VA.getLocInfo()) {
3034       default: llvm_unreachable("Unknown loc info!");
3035       case CCValAssign::Full: break;
3036       case CCValAssign::BCvt:
3037         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3038         break;
3039       case CCValAssign::SExt:
3040         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3041                                DAG.getValueType(VA.getValVT()));
3042         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3043         break;
3044       case CCValAssign::ZExt:
3045         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3046                                DAG.getValueType(VA.getValVT()));
3047         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3048         break;
3049       }
3050
3051       InVals.push_back(ArgValue);
3052
3053     } else { // VA.isRegLoc()
3054
3055       // sanity check
3056       assert(VA.isMemLoc());
3057       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3058
3059       int index = ArgLocs[i].getValNo();
3060
3061       // Some Ins[] entries become multiple ArgLoc[] entries.
3062       // Process them only once.
3063       if (index != lastInsIndex)
3064         {
3065           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3066           // FIXME: For now, all byval parameter objects are marked mutable.
3067           // This can be changed with more analysis.
3068           // In case of tail call optimization mark all arguments mutable.
3069           // Since they could be overwritten by lowering of arguments in case of
3070           // a tail call.
3071           if (Flags.isByVal()) {
3072             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3073
3074             ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3075             int FrameIndex = StoreByValRegs(
3076                 CCInfo, DAG, dl, Chain, CurOrigArg,
3077                 CurByValIndex,
3078                 Ins[VA.getValNo()].PartOffset,
3079                 VA.getLocMemOffset(),
3080                 Flags.getByValSize(),
3081                 true /*force mutable frames*/,
3082                 ByValStoreOffset,
3083                 TotalArgRegsSaveSize);
3084             ByValStoreOffset += Flags.getByValSize();
3085             ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3086             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3087             CCInfo.nextInRegsParam();
3088           } else {
3089             unsigned FIOffset = VA.getLocMemOffset();
3090             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3091                                             FIOffset, true);
3092
3093             // Create load nodes to retrieve arguments from the stack.
3094             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3095             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3096                                          MachinePointerInfo::getFixedStack(FI),
3097                                          false, false, false, 0));
3098           }
3099           lastInsIndex = index;
3100         }
3101     }
3102   }
3103
3104   // varargs
3105   if (isVarArg)
3106     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3107                          CCInfo.getNextStackOffset(),
3108                          TotalArgRegsSaveSize);
3109
3110   return Chain;
3111 }
3112
3113 /// isFloatingPointZero - Return true if this is +0.0.
3114 static bool isFloatingPointZero(SDValue Op) {
3115   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3116     return CFP->getValueAPF().isPosZero();
3117   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3118     // Maybe this has already been legalized into the constant pool?
3119     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3120       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3121       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3122         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3123           return CFP->getValueAPF().isPosZero();
3124     }
3125   }
3126   return false;
3127 }
3128
3129 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3130 /// the given operands.
3131 SDValue
3132 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3133                              SDValue &ARMcc, SelectionDAG &DAG,
3134                              SDLoc dl) const {
3135   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3136     unsigned C = RHSC->getZExtValue();
3137     if (!isLegalICmpImmediate(C)) {
3138       // Constant does not fit, try adjusting it by one?
3139       switch (CC) {
3140       default: break;
3141       case ISD::SETLT:
3142       case ISD::SETGE:
3143         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3144           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3145           RHS = DAG.getConstant(C-1, MVT::i32);
3146         }
3147         break;
3148       case ISD::SETULT:
3149       case ISD::SETUGE:
3150         if (C != 0 && isLegalICmpImmediate(C-1)) {
3151           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3152           RHS = DAG.getConstant(C-1, MVT::i32);
3153         }
3154         break;
3155       case ISD::SETLE:
3156       case ISD::SETGT:
3157         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3158           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3159           RHS = DAG.getConstant(C+1, MVT::i32);
3160         }
3161         break;
3162       case ISD::SETULE:
3163       case ISD::SETUGT:
3164         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3165           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3166           RHS = DAG.getConstant(C+1, MVT::i32);
3167         }
3168         break;
3169       }
3170     }
3171   }
3172
3173   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3174   ARMISD::NodeType CompareType;
3175   switch (CondCode) {
3176   default:
3177     CompareType = ARMISD::CMP;
3178     break;
3179   case ARMCC::EQ:
3180   case ARMCC::NE:
3181     // Uses only Z Flag
3182     CompareType = ARMISD::CMPZ;
3183     break;
3184   }
3185   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3186   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3187 }
3188
3189 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3190 SDValue
3191 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3192                              SDLoc dl) const {
3193   SDValue Cmp;
3194   if (!isFloatingPointZero(RHS))
3195     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3196   else
3197     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3198   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3199 }
3200
3201 /// duplicateCmp - Glue values can have only one use, so this function
3202 /// duplicates a comparison node.
3203 SDValue
3204 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3205   unsigned Opc = Cmp.getOpcode();
3206   SDLoc DL(Cmp);
3207   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3208     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3209
3210   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3211   Cmp = Cmp.getOperand(0);
3212   Opc = Cmp.getOpcode();
3213   if (Opc == ARMISD::CMPFP)
3214     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3215   else {
3216     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3217     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3218   }
3219   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3220 }
3221
3222 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3223   SDValue Cond = Op.getOperand(0);
3224   SDValue SelectTrue = Op.getOperand(1);
3225   SDValue SelectFalse = Op.getOperand(2);
3226   SDLoc dl(Op);
3227
3228   // Convert:
3229   //
3230   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3231   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3232   //
3233   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3234     const ConstantSDNode *CMOVTrue =
3235       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3236     const ConstantSDNode *CMOVFalse =
3237       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3238
3239     if (CMOVTrue && CMOVFalse) {
3240       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3241       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3242
3243       SDValue True;
3244       SDValue False;
3245       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3246         True = SelectTrue;
3247         False = SelectFalse;
3248       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3249         True = SelectFalse;
3250         False = SelectTrue;
3251       }
3252
3253       if (True.getNode() && False.getNode()) {
3254         EVT VT = Op.getValueType();
3255         SDValue ARMcc = Cond.getOperand(2);
3256         SDValue CCR = Cond.getOperand(3);
3257         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3258         assert(True.getValueType() == VT);
3259         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3260       }
3261     }
3262   }
3263
3264   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3265   // undefined bits before doing a full-word comparison with zero.
3266   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3267                      DAG.getConstant(1, Cond.getValueType()));
3268
3269   return DAG.getSelectCC(dl, Cond,
3270                          DAG.getConstant(0, Cond.getValueType()),
3271                          SelectTrue, SelectFalse, ISD::SETNE);
3272 }
3273
3274 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3275   if (CC == ISD::SETNE)
3276     return ISD::SETEQ;
3277   return ISD::getSetCCInverse(CC, true);
3278 }
3279
3280 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3281                                  bool &swpCmpOps, bool &swpVselOps) {
3282   // Start by selecting the GE condition code for opcodes that return true for
3283   // 'equality'
3284   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3285       CC == ISD::SETULE)
3286     CondCode = ARMCC::GE;
3287
3288   // and GT for opcodes that return false for 'equality'.
3289   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3290            CC == ISD::SETULT)
3291     CondCode = ARMCC::GT;
3292
3293   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3294   // to swap the compare operands.
3295   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3296       CC == ISD::SETULT)
3297     swpCmpOps = true;
3298
3299   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3300   // If we have an unordered opcode, we need to swap the operands to the VSEL
3301   // instruction (effectively negating the condition).
3302   //
3303   // This also has the effect of swapping which one of 'less' or 'greater'
3304   // returns true, so we also swap the compare operands. It also switches
3305   // whether we return true for 'equality', so we compensate by picking the
3306   // opposite condition code to our original choice.
3307   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3308       CC == ISD::SETUGT) {
3309     swpCmpOps = !swpCmpOps;
3310     swpVselOps = !swpVselOps;
3311     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3312   }
3313
3314   // 'ordered' is 'anything but unordered', so use the VS condition code and
3315   // swap the VSEL operands.
3316   if (CC == ISD::SETO) {
3317     CondCode = ARMCC::VS;
3318     swpVselOps = true;
3319   }
3320
3321   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3322   // code and swap the VSEL operands.
3323   if (CC == ISD::SETUNE) {
3324     CondCode = ARMCC::EQ;
3325     swpVselOps = true;
3326   }
3327 }
3328
3329 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3330   EVT VT = Op.getValueType();
3331   SDValue LHS = Op.getOperand(0);
3332   SDValue RHS = Op.getOperand(1);
3333   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3334   SDValue TrueVal = Op.getOperand(2);
3335   SDValue FalseVal = Op.getOperand(3);
3336   SDLoc dl(Op);
3337
3338   if (LHS.getValueType() == MVT::i32) {
3339     // Try to generate VSEL on ARMv8.
3340     // The VSEL instruction can't use all the usual ARM condition
3341     // codes: it only has two bits to select the condition code, so it's
3342     // constrained to use only GE, GT, VS and EQ.
3343     //
3344     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3345     // swap the operands of the previous compare instruction (effectively
3346     // inverting the compare condition, swapping 'less' and 'greater') and
3347     // sometimes need to swap the operands to the VSEL (which inverts the
3348     // condition in the sense of firing whenever the previous condition didn't)
3349     if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3350                                       TrueVal.getValueType() == MVT::f64)) {
3351       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3352       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3353           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3354         CC = getInverseCCForVSEL(CC);
3355         std::swap(TrueVal, FalseVal);
3356       }
3357     }
3358
3359     SDValue ARMcc;
3360     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3361     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3362     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3363                        Cmp);
3364   }
3365
3366   ARMCC::CondCodes CondCode, CondCode2;
3367   FPCCToARMCC(CC, CondCode, CondCode2);
3368
3369   // Try to generate VSEL on ARMv8.
3370   if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3371                                     TrueVal.getValueType() == MVT::f64)) {
3372     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3373     // same operands, as follows:
3374     //   c = fcmp [ogt, olt, ugt, ult] a, b
3375     //   select c, a, b
3376     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3377     // handled differently than the original code sequence.
3378     if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3379         RHS == FalseVal) {
3380       if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3381         return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3382       if (CC == ISD::SETOLT || CC == ISD::SETULT)
3383         return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3384     }
3385
3386     bool swpCmpOps = false;
3387     bool swpVselOps = false;
3388     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3389
3390     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3391         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3392       if (swpCmpOps)
3393         std::swap(LHS, RHS);
3394       if (swpVselOps)
3395         std::swap(TrueVal, FalseVal);
3396     }
3397   }
3398
3399   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3400   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3401   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3402   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3403                                ARMcc, CCR, Cmp);
3404   if (CondCode2 != ARMCC::AL) {
3405     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3406     // FIXME: Needs another CMP because flag can have but one use.
3407     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3408     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3409                          Result, TrueVal, ARMcc2, CCR, Cmp2);
3410   }
3411   return Result;
3412 }
3413
3414 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3415 /// to morph to an integer compare sequence.
3416 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3417                            const ARMSubtarget *Subtarget) {
3418   SDNode *N = Op.getNode();
3419   if (!N->hasOneUse())
3420     // Otherwise it requires moving the value from fp to integer registers.
3421     return false;
3422   if (!N->getNumValues())
3423     return false;
3424   EVT VT = Op.getValueType();
3425   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3426     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3427     // vmrs are very slow, e.g. cortex-a8.
3428     return false;
3429
3430   if (isFloatingPointZero(Op)) {
3431     SeenZero = true;
3432     return true;
3433   }
3434   return ISD::isNormalLoad(N);
3435 }
3436
3437 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3438   if (isFloatingPointZero(Op))
3439     return DAG.getConstant(0, MVT::i32);
3440
3441   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3442     return DAG.getLoad(MVT::i32, SDLoc(Op),
3443                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3444                        Ld->isVolatile(), Ld->isNonTemporal(),
3445                        Ld->isInvariant(), Ld->getAlignment());
3446
3447   llvm_unreachable("Unknown VFP cmp argument!");
3448 }
3449
3450 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3451                            SDValue &RetVal1, SDValue &RetVal2) {
3452   if (isFloatingPointZero(Op)) {
3453     RetVal1 = DAG.getConstant(0, MVT::i32);
3454     RetVal2 = DAG.getConstant(0, MVT::i32);
3455     return;
3456   }
3457
3458   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3459     SDValue Ptr = Ld->getBasePtr();
3460     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3461                           Ld->getChain(), Ptr,
3462                           Ld->getPointerInfo(),
3463                           Ld->isVolatile(), Ld->isNonTemporal(),
3464                           Ld->isInvariant(), Ld->getAlignment());
3465
3466     EVT PtrType = Ptr.getValueType();
3467     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3468     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3469                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3470     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3471                           Ld->getChain(), NewPtr,
3472                           Ld->getPointerInfo().getWithOffset(4),
3473                           Ld->isVolatile(), Ld->isNonTemporal(),
3474                           Ld->isInvariant(), NewAlign);
3475     return;
3476   }
3477
3478   llvm_unreachable("Unknown VFP cmp argument!");
3479 }
3480
3481 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3482 /// f32 and even f64 comparisons to integer ones.
3483 SDValue
3484 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3485   SDValue Chain = Op.getOperand(0);
3486   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3487   SDValue LHS = Op.getOperand(2);
3488   SDValue RHS = Op.getOperand(3);
3489   SDValue Dest = Op.getOperand(4);
3490   SDLoc dl(Op);
3491
3492   bool LHSSeenZero = false;
3493   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3494   bool RHSSeenZero = false;
3495   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3496   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3497     // If unsafe fp math optimization is enabled and there are no other uses of
3498     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3499     // to an integer comparison.
3500     if (CC == ISD::SETOEQ)
3501       CC = ISD::SETEQ;
3502     else if (CC == ISD::SETUNE)
3503       CC = ISD::SETNE;
3504
3505     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3506     SDValue ARMcc;
3507     if (LHS.getValueType() == MVT::f32) {
3508       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3509                         bitcastf32Toi32(LHS, DAG), Mask);
3510       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3511                         bitcastf32Toi32(RHS, DAG), Mask);
3512       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3513       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3514       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3515                          Chain, Dest, ARMcc, CCR, Cmp);
3516     }
3517
3518     SDValue LHS1, LHS2;
3519     SDValue RHS1, RHS2;
3520     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3521     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3522     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3523     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3524     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3525     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3526     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3527     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3528     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3529   }
3530
3531   return SDValue();
3532 }
3533
3534 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3535   SDValue Chain = Op.getOperand(0);
3536   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3537   SDValue LHS = Op.getOperand(2);
3538   SDValue RHS = Op.getOperand(3);
3539   SDValue Dest = Op.getOperand(4);
3540   SDLoc dl(Op);
3541
3542   if (LHS.getValueType() == MVT::i32) {
3543     SDValue ARMcc;
3544     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3545     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3546     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3547                        Chain, Dest, ARMcc, CCR, Cmp);
3548   }
3549
3550   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3551
3552   if (getTargetMachine().Options.UnsafeFPMath &&
3553       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3554        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3555     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3556     if (Result.getNode())
3557       return Result;
3558   }
3559
3560   ARMCC::CondCodes CondCode, CondCode2;
3561   FPCCToARMCC(CC, CondCode, CondCode2);
3562
3563   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3564   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3565   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3566   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3567   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3568   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3569   if (CondCode2 != ARMCC::AL) {
3570     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3571     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3572     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3573   }
3574   return Res;
3575 }
3576
3577 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3578   SDValue Chain = Op.getOperand(0);
3579   SDValue Table = Op.getOperand(1);
3580   SDValue Index = Op.getOperand(2);
3581   SDLoc dl(Op);
3582
3583   EVT PTy = getPointerTy();
3584   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3585   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3586   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3587   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3588   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3589   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3590   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3591   if (Subtarget->isThumb2()) {
3592     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3593     // which does another jump to the destination. This also makes it easier
3594     // to translate it to TBB / TBH later.
3595     // FIXME: This might not work if the function is extremely large.
3596     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3597                        Addr, Op.getOperand(2), JTI, UId);
3598   }
3599   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3600     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3601                        MachinePointerInfo::getJumpTable(),
3602                        false, false, false, 0);
3603     Chain = Addr.getValue(1);
3604     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3605     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3606   } else {
3607     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3608                        MachinePointerInfo::getJumpTable(),
3609                        false, false, false, 0);
3610     Chain = Addr.getValue(1);
3611     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3612   }
3613 }
3614
3615 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3616   EVT VT = Op.getValueType();
3617   SDLoc dl(Op);
3618
3619   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3620     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3621       return Op;
3622     return DAG.UnrollVectorOp(Op.getNode());
3623   }
3624
3625   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3626          "Invalid type for custom lowering!");
3627   if (VT != MVT::v4i16)
3628     return DAG.UnrollVectorOp(Op.getNode());
3629
3630   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3631   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3632 }
3633
3634 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3635   EVT VT = Op.getValueType();
3636   if (VT.isVector())
3637     return LowerVectorFP_TO_INT(Op, DAG);
3638
3639   SDLoc dl(Op);
3640   unsigned Opc;
3641
3642   switch (Op.getOpcode()) {
3643   default: llvm_unreachable("Invalid opcode!");
3644   case ISD::FP_TO_SINT:
3645     Opc = ARMISD::FTOSI;
3646     break;
3647   case ISD::FP_TO_UINT:
3648     Opc = ARMISD::FTOUI;
3649     break;
3650   }
3651   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3652   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3653 }
3654
3655 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3656   EVT VT = Op.getValueType();
3657   SDLoc dl(Op);
3658
3659   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3660     if (VT.getVectorElementType() == MVT::f32)
3661       return Op;
3662     return DAG.UnrollVectorOp(Op.getNode());
3663   }
3664
3665   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3666          "Invalid type for custom lowering!");
3667   if (VT != MVT::v4f32)
3668     return DAG.UnrollVectorOp(Op.getNode());
3669
3670   unsigned CastOpc;
3671   unsigned Opc;
3672   switch (Op.getOpcode()) {
3673   default: llvm_unreachable("Invalid opcode!");
3674   case ISD::SINT_TO_FP:
3675     CastOpc = ISD::SIGN_EXTEND;
3676     Opc = ISD::SINT_TO_FP;
3677     break;
3678   case ISD::UINT_TO_FP:
3679     CastOpc = ISD::ZERO_EXTEND;
3680     Opc = ISD::UINT_TO_FP;
3681     break;
3682   }
3683
3684   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3685   return DAG.getNode(Opc, dl, VT, Op);
3686 }
3687
3688 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3689   EVT VT = Op.getValueType();
3690   if (VT.isVector())
3691     return LowerVectorINT_TO_FP(Op, DAG);
3692
3693   SDLoc dl(Op);
3694   unsigned Opc;
3695
3696   switch (Op.getOpcode()) {
3697   default: llvm_unreachable("Invalid opcode!");
3698   case ISD::SINT_TO_FP:
3699     Opc = ARMISD::SITOF;
3700     break;
3701   case ISD::UINT_TO_FP:
3702     Opc = ARMISD::UITOF;
3703     break;
3704   }
3705
3706   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3707   return DAG.getNode(Opc, dl, VT, Op);
3708 }
3709
3710 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3711   // Implement fcopysign with a fabs and a conditional fneg.
3712   SDValue Tmp0 = Op.getOperand(0);
3713   SDValue Tmp1 = Op.getOperand(1);
3714   SDLoc dl(Op);
3715   EVT VT = Op.getValueType();
3716   EVT SrcVT = Tmp1.getValueType();
3717   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3718     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3719   bool UseNEON = !InGPR && Subtarget->hasNEON();
3720
3721   if (UseNEON) {
3722     // Use VBSL to copy the sign bit.
3723     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3724     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3725                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3726     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3727     if (VT == MVT::f64)
3728       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3729                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3730                          DAG.getConstant(32, MVT::i32));
3731     else /*if (VT == MVT::f32)*/
3732       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3733     if (SrcVT == MVT::f32) {
3734       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3735       if (VT == MVT::f64)
3736         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3737                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3738                            DAG.getConstant(32, MVT::i32));
3739     } else if (VT == MVT::f32)
3740       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3741                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3742                          DAG.getConstant(32, MVT::i32));
3743     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3744     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3745
3746     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3747                                             MVT::i32);
3748     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3749     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3750                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3751
3752     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3753                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3754                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3755     if (VT == MVT::f32) {
3756       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3757       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3758                         DAG.getConstant(0, MVT::i32));
3759     } else {
3760       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3761     }
3762
3763     return Res;
3764   }
3765
3766   // Bitcast operand 1 to i32.
3767   if (SrcVT == MVT::f64)
3768     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3769                        &Tmp1, 1).getValue(1);
3770   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3771
3772   // Or in the signbit with integer operations.
3773   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3774   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3775   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3776   if (VT == MVT::f32) {
3777     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3778                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3779     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3780                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3781   }
3782
3783   // f64: Or the high part with signbit and then combine two parts.
3784   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3785                      &Tmp0, 1);
3786   SDValue Lo = Tmp0.getValue(0);
3787   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3788   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3789   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3790 }
3791
3792 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3793   MachineFunction &MF = DAG.getMachineFunction();
3794   MachineFrameInfo *MFI = MF.getFrameInfo();
3795   MFI->setReturnAddressIsTaken(true);
3796
3797   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3798     return SDValue();
3799
3800   EVT VT = Op.getValueType();
3801   SDLoc dl(Op);
3802   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3803   if (Depth) {
3804     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3805     SDValue Offset = DAG.getConstant(4, MVT::i32);
3806     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3807                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3808                        MachinePointerInfo(), false, false, false, 0);
3809   }
3810
3811   // Return LR, which contains the return address. Mark it an implicit live-in.
3812   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3813   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3814 }
3815
3816 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3817   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3818   MFI->setFrameAddressIsTaken(true);
3819
3820   EVT VT = Op.getValueType();
3821   SDLoc dl(Op);  // FIXME probably not meaningful
3822   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3823   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetMachO())
3824     ? ARM::R7 : ARM::R11;
3825   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3826   while (Depth--)
3827     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3828                             MachinePointerInfo(),
3829                             false, false, false, 0);
3830   return FrameAddr;
3831 }
3832
3833 /// ExpandBITCAST - If the target supports VFP, this function is called to
3834 /// expand a bit convert where either the source or destination type is i64 to
3835 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3836 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3837 /// vectors), since the legalizer won't know what to do with that.
3838 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3839   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3840   SDLoc dl(N);
3841   SDValue Op = N->getOperand(0);
3842
3843   // This function is only supposed to be called for i64 types, either as the
3844   // source or destination of the bit convert.
3845   EVT SrcVT = Op.getValueType();
3846   EVT DstVT = N->getValueType(0);
3847   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3848          "ExpandBITCAST called for non-i64 type");
3849
3850   // Turn i64->f64 into VMOVDRR.
3851   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3852     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3853                              DAG.getConstant(0, MVT::i32));
3854     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3855                              DAG.getConstant(1, MVT::i32));
3856     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3857                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3858   }
3859
3860   // Turn f64->i64 into VMOVRRD.
3861   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3862     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3863                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3864     // Merge the pieces into a single i64 value.
3865     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3866   }
3867
3868   return SDValue();
3869 }
3870
3871 /// getZeroVector - Returns a vector of specified type with all zero elements.
3872 /// Zero vectors are used to represent vector negation and in those cases
3873 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3874 /// not support i64 elements, so sometimes the zero vectors will need to be
3875 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3876 /// zero vector.
3877 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3878   assert(VT.isVector() && "Expected a vector type");
3879   // The canonical modified immediate encoding of a zero vector is....0!
3880   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3881   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3882   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3883   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3884 }
3885
3886 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3887 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3888 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3889                                                 SelectionDAG &DAG) const {
3890   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3891   EVT VT = Op.getValueType();
3892   unsigned VTBits = VT.getSizeInBits();
3893   SDLoc dl(Op);
3894   SDValue ShOpLo = Op.getOperand(0);
3895   SDValue ShOpHi = Op.getOperand(1);
3896   SDValue ShAmt  = Op.getOperand(2);
3897   SDValue ARMcc;
3898   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3899
3900   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3901
3902   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3903                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3904   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3905   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3906                                    DAG.getConstant(VTBits, MVT::i32));
3907   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3908   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3909   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3910
3911   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3912   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3913                           ARMcc, DAG, dl);
3914   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3915   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3916                            CCR, Cmp);
3917
3918   SDValue Ops[2] = { Lo, Hi };
3919   return DAG.getMergeValues(Ops, 2, dl);
3920 }
3921
3922 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3923 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3924 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3925                                                SelectionDAG &DAG) const {
3926   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3927   EVT VT = Op.getValueType();
3928   unsigned VTBits = VT.getSizeInBits();
3929   SDLoc dl(Op);
3930   SDValue ShOpLo = Op.getOperand(0);
3931   SDValue ShOpHi = Op.getOperand(1);
3932   SDValue ShAmt  = Op.getOperand(2);
3933   SDValue ARMcc;
3934
3935   assert(Op.getOpcode() == ISD::SHL_PARTS);
3936   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3937                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3938   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3939   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3940                                    DAG.getConstant(VTBits, MVT::i32));
3941   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3942   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3943
3944   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3945   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3946   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3947                           ARMcc, DAG, dl);
3948   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3949   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3950                            CCR, Cmp);
3951
3952   SDValue Ops[2] = { Lo, Hi };
3953   return DAG.getMergeValues(Ops, 2, dl);
3954 }
3955
3956 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3957                                             SelectionDAG &DAG) const {
3958   // The rounding mode is in bits 23:22 of the FPSCR.
3959   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3960   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3961   // so that the shift + and get folded into a bitfield extract.
3962   SDLoc dl(Op);
3963   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3964                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3965                                               MVT::i32));
3966   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3967                                   DAG.getConstant(1U << 22, MVT::i32));
3968   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3969                               DAG.getConstant(22, MVT::i32));
3970   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3971                      DAG.getConstant(3, MVT::i32));
3972 }
3973
3974 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3975                          const ARMSubtarget *ST) {
3976   EVT VT = N->getValueType(0);
3977   SDLoc dl(N);
3978
3979   if (!ST->hasV6T2Ops())
3980     return SDValue();
3981
3982   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3983   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3984 }
3985
3986 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3987 /// for each 16-bit element from operand, repeated.  The basic idea is to
3988 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3989 ///
3990 /// Trace for v4i16:
3991 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
3992 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3993 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3994 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3995 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
3996 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
3997 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3998 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
3999 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4000   EVT VT = N->getValueType(0);
4001   SDLoc DL(N);
4002
4003   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4004   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4005   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4006   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4007   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4008   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4009 }
4010
4011 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4012 /// bit-count for each 16-bit element from the operand.  We need slightly
4013 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4014 /// 64/128-bit registers.
4015 ///
4016 /// Trace for v4i16:
4017 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4018 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4019 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4020 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4021 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4022   EVT VT = N->getValueType(0);
4023   SDLoc DL(N);
4024
4025   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4026   if (VT.is64BitVector()) {
4027     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4028     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4029                        DAG.getIntPtrConstant(0));
4030   } else {
4031     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4032                                     BitCounts, DAG.getIntPtrConstant(0));
4033     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4034   }
4035 }
4036
4037 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4038 /// bit-count for each 32-bit element from the operand.  The idea here is
4039 /// to split the vector into 16-bit elements, leverage the 16-bit count
4040 /// routine, and then combine the results.
4041 ///
4042 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4043 /// input    = [v0    v1    ] (vi: 32-bit elements)
4044 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4045 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4046 /// vrev: N0 = [k1 k0 k3 k2 ]
4047 ///            [k0 k1 k2 k3 ]
4048 ///       N1 =+[k1 k0 k3 k2 ]
4049 ///            [k0 k2 k1 k3 ]
4050 ///       N2 =+[k1 k3 k0 k2 ]
4051 ///            [k0    k2    k1    k3    ]
4052 /// Extended =+[k1    k3    k0    k2    ]
4053 ///            [k0    k2    ]
4054 /// Extracted=+[k1    k3    ]
4055 ///
4056 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4057   EVT VT = N->getValueType(0);
4058   SDLoc DL(N);
4059
4060   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4061
4062   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4063   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4064   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4065   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4066   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4067
4068   if (VT.is64BitVector()) {
4069     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4070     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4071                        DAG.getIntPtrConstant(0));
4072   } else {
4073     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4074                                     DAG.getIntPtrConstant(0));
4075     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4076   }
4077 }
4078
4079 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4080                           const ARMSubtarget *ST) {
4081   EVT VT = N->getValueType(0);
4082
4083   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4084   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4085           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4086          "Unexpected type for custom ctpop lowering");
4087
4088   if (VT.getVectorElementType() == MVT::i32)
4089     return lowerCTPOP32BitElements(N, DAG);
4090   else
4091     return lowerCTPOP16BitElements(N, DAG);
4092 }
4093
4094 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4095                           const ARMSubtarget *ST) {
4096   EVT VT = N->getValueType(0);
4097   SDLoc dl(N);
4098
4099   if (!VT.isVector())
4100     return SDValue();
4101
4102   // Lower vector shifts on NEON to use VSHL.
4103   assert(ST->hasNEON() && "unexpected vector shift");
4104
4105   // Left shifts translate directly to the vshiftu intrinsic.
4106   if (N->getOpcode() == ISD::SHL)
4107     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4108                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4109                        N->getOperand(0), N->getOperand(1));
4110
4111   assert((N->getOpcode() == ISD::SRA ||
4112           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4113
4114   // NEON uses the same intrinsics for both left and right shifts.  For
4115   // right shifts, the shift amounts are negative, so negate the vector of
4116   // shift amounts.
4117   EVT ShiftVT = N->getOperand(1).getValueType();
4118   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4119                                      getZeroVector(ShiftVT, DAG, dl),
4120                                      N->getOperand(1));
4121   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4122                              Intrinsic::arm_neon_vshifts :
4123                              Intrinsic::arm_neon_vshiftu);
4124   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4125                      DAG.getConstant(vshiftInt, MVT::i32),
4126                      N->getOperand(0), NegatedCount);
4127 }
4128
4129 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4130                                 const ARMSubtarget *ST) {
4131   EVT VT = N->getValueType(0);
4132   SDLoc dl(N);
4133
4134   // We can get here for a node like i32 = ISD::SHL i32, i64
4135   if (VT != MVT::i64)
4136     return SDValue();
4137
4138   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4139          "Unknown shift to lower!");
4140
4141   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4142   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4143       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4144     return SDValue();
4145
4146   // If we are in thumb mode, we don't have RRX.
4147   if (ST->isThumb1Only()) return SDValue();
4148
4149   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4150   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4151                            DAG.getConstant(0, MVT::i32));
4152   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4153                            DAG.getConstant(1, MVT::i32));
4154
4155   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4156   // captures the result into a carry flag.
4157   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4158   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
4159
4160   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4161   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4162
4163   // Merge the pieces into a single i64 value.
4164  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4165 }
4166
4167 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4168   SDValue TmpOp0, TmpOp1;
4169   bool Invert = false;
4170   bool Swap = false;
4171   unsigned Opc = 0;
4172
4173   SDValue Op0 = Op.getOperand(0);
4174   SDValue Op1 = Op.getOperand(1);
4175   SDValue CC = Op.getOperand(2);
4176   EVT VT = Op.getValueType();
4177   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4178   SDLoc dl(Op);
4179
4180   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4181     switch (SetCCOpcode) {
4182     default: llvm_unreachable("Illegal FP comparison");
4183     case ISD::SETUNE:
4184     case ISD::SETNE:  Invert = true; // Fallthrough
4185     case ISD::SETOEQ:
4186     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4187     case ISD::SETOLT:
4188     case ISD::SETLT: Swap = true; // Fallthrough
4189     case ISD::SETOGT:
4190     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4191     case ISD::SETOLE:
4192     case ISD::SETLE:  Swap = true; // Fallthrough
4193     case ISD::SETOGE:
4194     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4195     case ISD::SETUGE: Swap = true; // Fallthrough
4196     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4197     case ISD::SETUGT: Swap = true; // Fallthrough
4198     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4199     case ISD::SETUEQ: Invert = true; // Fallthrough
4200     case ISD::SETONE:
4201       // Expand this to (OLT | OGT).
4202       TmpOp0 = Op0;
4203       TmpOp1 = Op1;
4204       Opc = ISD::OR;
4205       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4206       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4207       break;
4208     case ISD::SETUO: Invert = true; // Fallthrough
4209     case ISD::SETO:
4210       // Expand this to (OLT | OGE).
4211       TmpOp0 = Op0;
4212       TmpOp1 = Op1;
4213       Opc = ISD::OR;
4214       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4215       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4216       break;
4217     }
4218   } else {
4219     // Integer comparisons.
4220     switch (SetCCOpcode) {
4221     default: llvm_unreachable("Illegal integer comparison");
4222     case ISD::SETNE:  Invert = true;
4223     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4224     case ISD::SETLT:  Swap = true;
4225     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4226     case ISD::SETLE:  Swap = true;
4227     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4228     case ISD::SETULT: Swap = true;
4229     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4230     case ISD::SETULE: Swap = true;
4231     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4232     }
4233
4234     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4235     if (Opc == ARMISD::VCEQ) {
4236
4237       SDValue AndOp;
4238       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4239         AndOp = Op0;
4240       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4241         AndOp = Op1;
4242
4243       // Ignore bitconvert.
4244       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4245         AndOp = AndOp.getOperand(0);
4246
4247       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4248         Opc = ARMISD::VTST;
4249         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4250         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4251         Invert = !Invert;
4252       }
4253     }
4254   }
4255
4256   if (Swap)
4257     std::swap(Op0, Op1);
4258
4259   // If one of the operands is a constant vector zero, attempt to fold the
4260   // comparison to a specialized compare-against-zero form.
4261   SDValue SingleOp;
4262   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4263     SingleOp = Op0;
4264   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4265     if (Opc == ARMISD::VCGE)
4266       Opc = ARMISD::VCLEZ;
4267     else if (Opc == ARMISD::VCGT)
4268       Opc = ARMISD::VCLTZ;
4269     SingleOp = Op1;
4270   }
4271
4272   SDValue Result;
4273   if (SingleOp.getNode()) {
4274     switch (Opc) {
4275     case ARMISD::VCEQ:
4276       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4277     case ARMISD::VCGE:
4278       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4279     case ARMISD::VCLEZ:
4280       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4281     case ARMISD::VCGT:
4282       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4283     case ARMISD::VCLTZ:
4284       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4285     default:
4286       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4287     }
4288   } else {
4289      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4290   }
4291
4292   if (Invert)
4293     Result = DAG.getNOT(dl, Result, VT);
4294
4295   return Result;
4296 }
4297
4298 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4299 /// valid vector constant for a NEON instruction with a "modified immediate"
4300 /// operand (e.g., VMOV).  If so, return the encoded value.
4301 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4302                                  unsigned SplatBitSize, SelectionDAG &DAG,
4303                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4304   unsigned OpCmode, Imm;
4305
4306   // SplatBitSize is set to the smallest size that splats the vector, so a
4307   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4308   // immediate instructions others than VMOV do not support the 8-bit encoding
4309   // of a zero vector, and the default encoding of zero is supposed to be the
4310   // 32-bit version.
4311   if (SplatBits == 0)
4312     SplatBitSize = 32;
4313
4314   switch (SplatBitSize) {
4315   case 8:
4316     if (type != VMOVModImm)
4317       return SDValue();
4318     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4319     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4320     OpCmode = 0xe;
4321     Imm = SplatBits;
4322     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4323     break;
4324
4325   case 16:
4326     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4327     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4328     if ((SplatBits & ~0xff) == 0) {
4329       // Value = 0x00nn: Op=x, Cmode=100x.
4330       OpCmode = 0x8;
4331       Imm = SplatBits;
4332       break;
4333     }
4334     if ((SplatBits & ~0xff00) == 0) {
4335       // Value = 0xnn00: Op=x, Cmode=101x.
4336       OpCmode = 0xa;
4337       Imm = SplatBits >> 8;
4338       break;
4339     }
4340     return SDValue();
4341
4342   case 32:
4343     // NEON's 32-bit VMOV supports splat values where:
4344     // * only one byte is nonzero, or
4345     // * the least significant byte is 0xff and the second byte is nonzero, or
4346     // * the least significant 2 bytes are 0xff and the third is nonzero.
4347     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4348     if ((SplatBits & ~0xff) == 0) {
4349       // Value = 0x000000nn: Op=x, Cmode=000x.
4350       OpCmode = 0;
4351       Imm = SplatBits;
4352       break;
4353     }
4354     if ((SplatBits & ~0xff00) == 0) {
4355       // Value = 0x0000nn00: Op=x, Cmode=001x.
4356       OpCmode = 0x2;
4357       Imm = SplatBits >> 8;
4358       break;
4359     }
4360     if ((SplatBits & ~0xff0000) == 0) {
4361       // Value = 0x00nn0000: Op=x, Cmode=010x.
4362       OpCmode = 0x4;
4363       Imm = SplatBits >> 16;
4364       break;
4365     }
4366     if ((SplatBits & ~0xff000000) == 0) {
4367       // Value = 0xnn000000: Op=x, Cmode=011x.
4368       OpCmode = 0x6;
4369       Imm = SplatBits >> 24;
4370       break;
4371     }
4372
4373     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4374     if (type == OtherModImm) return SDValue();
4375
4376     if ((SplatBits & ~0xffff) == 0 &&
4377         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4378       // Value = 0x0000nnff: Op=x, Cmode=1100.
4379       OpCmode = 0xc;
4380       Imm = SplatBits >> 8;
4381       SplatBits |= 0xff;
4382       break;
4383     }
4384
4385     if ((SplatBits & ~0xffffff) == 0 &&
4386         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4387       // Value = 0x00nnffff: Op=x, Cmode=1101.
4388       OpCmode = 0xd;
4389       Imm = SplatBits >> 16;
4390       SplatBits |= 0xffff;
4391       break;
4392     }
4393
4394     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4395     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4396     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4397     // and fall through here to test for a valid 64-bit splat.  But, then the
4398     // caller would also need to check and handle the change in size.
4399     return SDValue();
4400
4401   case 64: {
4402     if (type != VMOVModImm)
4403       return SDValue();
4404     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4405     uint64_t BitMask = 0xff;
4406     uint64_t Val = 0;
4407     unsigned ImmMask = 1;
4408     Imm = 0;
4409     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4410       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4411         Val |= BitMask;
4412         Imm |= ImmMask;
4413       } else if ((SplatBits & BitMask) != 0) {
4414         return SDValue();
4415       }
4416       BitMask <<= 8;
4417       ImmMask <<= 1;
4418     }
4419     // Op=1, Cmode=1110.
4420     OpCmode = 0x1e;
4421     SplatBits = Val;
4422     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4423     break;
4424   }
4425
4426   default:
4427     llvm_unreachable("unexpected size for isNEONModifiedImm");
4428   }
4429
4430   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4431   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4432 }
4433
4434 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4435                                            const ARMSubtarget *ST) const {
4436   if (!ST->hasVFP3())
4437     return SDValue();
4438
4439   bool IsDouble = Op.getValueType() == MVT::f64;
4440   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4441
4442   // Try splatting with a VMOV.f32...
4443   APFloat FPVal = CFP->getValueAPF();
4444   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4445
4446   if (ImmVal != -1) {
4447     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4448       // We have code in place to select a valid ConstantFP already, no need to
4449       // do any mangling.
4450       return Op;
4451     }
4452
4453     // It's a float and we are trying to use NEON operations where
4454     // possible. Lower it to a splat followed by an extract.
4455     SDLoc DL(Op);
4456     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4457     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4458                                       NewVal);
4459     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4460                        DAG.getConstant(0, MVT::i32));
4461   }
4462
4463   // The rest of our options are NEON only, make sure that's allowed before
4464   // proceeding..
4465   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4466     return SDValue();
4467
4468   EVT VMovVT;
4469   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4470
4471   // It wouldn't really be worth bothering for doubles except for one very
4472   // important value, which does happen to match: 0.0. So make sure we don't do
4473   // anything stupid.
4474   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4475     return SDValue();
4476
4477   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4478   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4479                                      false, VMOVModImm);
4480   if (NewVal != SDValue()) {
4481     SDLoc DL(Op);
4482     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4483                                       NewVal);
4484     if (IsDouble)
4485       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4486
4487     // It's a float: cast and extract a vector element.
4488     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4489                                        VecConstant);
4490     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4491                        DAG.getConstant(0, MVT::i32));
4492   }
4493
4494   // Finally, try a VMVN.i32
4495   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4496                              false, VMVNModImm);
4497   if (NewVal != SDValue()) {
4498     SDLoc DL(Op);
4499     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4500
4501     if (IsDouble)
4502       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4503
4504     // It's a float: cast and extract a vector element.
4505     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4506                                        VecConstant);
4507     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4508                        DAG.getConstant(0, MVT::i32));
4509   }
4510
4511   return SDValue();
4512 }
4513
4514 // check if an VEXT instruction can handle the shuffle mask when the
4515 // vector sources of the shuffle are the same.
4516 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4517   unsigned NumElts = VT.getVectorNumElements();
4518
4519   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4520   if (M[0] < 0)
4521     return false;
4522
4523   Imm = M[0];
4524
4525   // If this is a VEXT shuffle, the immediate value is the index of the first
4526   // element.  The other shuffle indices must be the successive elements after
4527   // the first one.
4528   unsigned ExpectedElt = Imm;
4529   for (unsigned i = 1; i < NumElts; ++i) {
4530     // Increment the expected index.  If it wraps around, just follow it
4531     // back to index zero and keep going.
4532     ++ExpectedElt;
4533     if (ExpectedElt == NumElts)
4534       ExpectedElt = 0;
4535
4536     if (M[i] < 0) continue; // ignore UNDEF indices
4537     if (ExpectedElt != static_cast<unsigned>(M[i]))
4538       return false;
4539   }
4540
4541   return true;
4542 }
4543
4544
4545 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4546                        bool &ReverseVEXT, unsigned &Imm) {
4547   unsigned NumElts = VT.getVectorNumElements();
4548   ReverseVEXT = false;
4549
4550   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4551   if (M[0] < 0)
4552     return false;
4553
4554   Imm = M[0];
4555
4556   // If this is a VEXT shuffle, the immediate value is the index of the first
4557   // element.  The other shuffle indices must be the successive elements after
4558   // the first one.
4559   unsigned ExpectedElt = Imm;
4560   for (unsigned i = 1; i < NumElts; ++i) {
4561     // Increment the expected index.  If it wraps around, it may still be
4562     // a VEXT but the source vectors must be swapped.
4563     ExpectedElt += 1;
4564     if (ExpectedElt == NumElts * 2) {
4565       ExpectedElt = 0;
4566       ReverseVEXT = true;
4567     }
4568
4569     if (M[i] < 0) continue; // ignore UNDEF indices
4570     if (ExpectedElt != static_cast<unsigned>(M[i]))
4571       return false;
4572   }
4573
4574   // Adjust the index value if the source operands will be swapped.
4575   if (ReverseVEXT)
4576     Imm -= NumElts;
4577
4578   return true;
4579 }
4580
4581 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4582 /// instruction with the specified blocksize.  (The order of the elements
4583 /// within each block of the vector is reversed.)
4584 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4585   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4586          "Only possible block sizes for VREV are: 16, 32, 64");
4587
4588   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4589   if (EltSz == 64)
4590     return false;
4591
4592   unsigned NumElts = VT.getVectorNumElements();
4593   unsigned BlockElts = M[0] + 1;
4594   // If the first shuffle index is UNDEF, be optimistic.
4595   if (M[0] < 0)
4596     BlockElts = BlockSize / EltSz;
4597
4598   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4599     return false;
4600
4601   for (unsigned i = 0; i < NumElts; ++i) {
4602     if (M[i] < 0) continue; // ignore UNDEF indices
4603     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4604       return false;
4605   }
4606
4607   return true;
4608 }
4609
4610 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4611   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4612   // range, then 0 is placed into the resulting vector. So pretty much any mask
4613   // of 8 elements can work here.
4614   return VT == MVT::v8i8 && M.size() == 8;
4615 }
4616
4617 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4618   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4619   if (EltSz == 64)
4620     return false;
4621
4622   unsigned NumElts = VT.getVectorNumElements();
4623   WhichResult = (M[0] == 0 ? 0 : 1);
4624   for (unsigned i = 0; i < NumElts; i += 2) {
4625     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4626         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4627       return false;
4628   }
4629   return true;
4630 }
4631
4632 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4633 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4634 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4635 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4636   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4637   if (EltSz == 64)
4638     return false;
4639
4640   unsigned NumElts = VT.getVectorNumElements();
4641   WhichResult = (M[0] == 0 ? 0 : 1);
4642   for (unsigned i = 0; i < NumElts; i += 2) {
4643     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4644         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4645       return false;
4646   }
4647   return true;
4648 }
4649
4650 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4651   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4652   if (EltSz == 64)
4653     return false;
4654
4655   unsigned NumElts = VT.getVectorNumElements();
4656   WhichResult = (M[0] == 0 ? 0 : 1);
4657   for (unsigned i = 0; i != NumElts; ++i) {
4658     if (M[i] < 0) continue; // ignore UNDEF indices
4659     if ((unsigned) M[i] != 2 * i + WhichResult)
4660       return false;
4661   }
4662
4663   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4664   if (VT.is64BitVector() && EltSz == 32)
4665     return false;
4666
4667   return true;
4668 }
4669
4670 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4671 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4672 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4673 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4674   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4675   if (EltSz == 64)
4676     return false;
4677
4678   unsigned Half = VT.getVectorNumElements() / 2;
4679   WhichResult = (M[0] == 0 ? 0 : 1);
4680   for (unsigned j = 0; j != 2; ++j) {
4681     unsigned Idx = WhichResult;
4682     for (unsigned i = 0; i != Half; ++i) {
4683       int MIdx = M[i + j * Half];
4684       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4685         return false;
4686       Idx += 2;
4687     }
4688   }
4689
4690   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4691   if (VT.is64BitVector() && EltSz == 32)
4692     return false;
4693
4694   return true;
4695 }
4696
4697 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4698   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4699   if (EltSz == 64)
4700     return false;
4701
4702   unsigned NumElts = VT.getVectorNumElements();
4703   WhichResult = (M[0] == 0 ? 0 : 1);
4704   unsigned Idx = WhichResult * NumElts / 2;
4705   for (unsigned i = 0; i != NumElts; i += 2) {
4706     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4707         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4708       return false;
4709     Idx += 1;
4710   }
4711
4712   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4713   if (VT.is64BitVector() && EltSz == 32)
4714     return false;
4715
4716   return true;
4717 }
4718
4719 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4720 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4721 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4722 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4723   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4724   if (EltSz == 64)
4725     return false;
4726
4727   unsigned NumElts = VT.getVectorNumElements();
4728   WhichResult = (M[0] == 0 ? 0 : 1);
4729   unsigned Idx = WhichResult * NumElts / 2;
4730   for (unsigned i = 0; i != NumElts; i += 2) {
4731     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4732         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4733       return false;
4734     Idx += 1;
4735   }
4736
4737   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4738   if (VT.is64BitVector() && EltSz == 32)
4739     return false;
4740
4741   return true;
4742 }
4743
4744 /// \return true if this is a reverse operation on an vector.
4745 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4746   unsigned NumElts = VT.getVectorNumElements();
4747   // Make sure the mask has the right size.
4748   if (NumElts != M.size())
4749       return false;
4750
4751   // Look for <15, ..., 3, -1, 1, 0>.
4752   for (unsigned i = 0; i != NumElts; ++i)
4753     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4754       return false;
4755
4756   return true;
4757 }
4758
4759 // If N is an integer constant that can be moved into a register in one
4760 // instruction, return an SDValue of such a constant (will become a MOV
4761 // instruction).  Otherwise return null.
4762 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4763                                      const ARMSubtarget *ST, SDLoc dl) {
4764   uint64_t Val;
4765   if (!isa<ConstantSDNode>(N))
4766     return SDValue();
4767   Val = cast<ConstantSDNode>(N)->getZExtValue();
4768
4769   if (ST->isThumb1Only()) {
4770     if (Val <= 255 || ~Val <= 255)
4771       return DAG.getConstant(Val, MVT::i32);
4772   } else {
4773     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4774       return DAG.getConstant(Val, MVT::i32);
4775   }
4776   return SDValue();
4777 }
4778
4779 // If this is a case we can't handle, return null and let the default
4780 // expansion code take care of it.
4781 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4782                                              const ARMSubtarget *ST) const {
4783   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4784   SDLoc dl(Op);
4785   EVT VT = Op.getValueType();
4786
4787   APInt SplatBits, SplatUndef;
4788   unsigned SplatBitSize;
4789   bool HasAnyUndefs;
4790   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4791     if (SplatBitSize <= 64) {
4792       // Check if an immediate VMOV works.
4793       EVT VmovVT;
4794       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4795                                       SplatUndef.getZExtValue(), SplatBitSize,
4796                                       DAG, VmovVT, VT.is128BitVector(),
4797                                       VMOVModImm);
4798       if (Val.getNode()) {
4799         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4800         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4801       }
4802
4803       // Try an immediate VMVN.
4804       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4805       Val = isNEONModifiedImm(NegatedImm,
4806                                       SplatUndef.getZExtValue(), SplatBitSize,
4807                                       DAG, VmovVT, VT.is128BitVector(),
4808                                       VMVNModImm);
4809       if (Val.getNode()) {
4810         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4811         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4812       }
4813
4814       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4815       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4816         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4817         if (ImmVal != -1) {
4818           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4819           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4820         }
4821       }
4822     }
4823   }
4824
4825   // Scan through the operands to see if only one value is used.
4826   //
4827   // As an optimisation, even if more than one value is used it may be more
4828   // profitable to splat with one value then change some lanes.
4829   //
4830   // Heuristically we decide to do this if the vector has a "dominant" value,
4831   // defined as splatted to more than half of the lanes.
4832   unsigned NumElts = VT.getVectorNumElements();
4833   bool isOnlyLowElement = true;
4834   bool usesOnlyOneValue = true;
4835   bool hasDominantValue = false;
4836   bool isConstant = true;
4837
4838   // Map of the number of times a particular SDValue appears in the
4839   // element list.
4840   DenseMap<SDValue, unsigned> ValueCounts;
4841   SDValue Value;
4842   for (unsigned i = 0; i < NumElts; ++i) {
4843     SDValue V = Op.getOperand(i);
4844     if (V.getOpcode() == ISD::UNDEF)
4845       continue;
4846     if (i > 0)
4847       isOnlyLowElement = false;
4848     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4849       isConstant = false;
4850
4851     ValueCounts.insert(std::make_pair(V, 0));
4852     unsigned &Count = ValueCounts[V];
4853
4854     // Is this value dominant? (takes up more than half of the lanes)
4855     if (++Count > (NumElts / 2)) {
4856       hasDominantValue = true;
4857       Value = V;
4858     }
4859   }
4860   if (ValueCounts.size() != 1)
4861     usesOnlyOneValue = false;
4862   if (!Value.getNode() && ValueCounts.size() > 0)
4863     Value = ValueCounts.begin()->first;
4864
4865   if (ValueCounts.size() == 0)
4866     return DAG.getUNDEF(VT);
4867
4868   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
4869   // Keep going if we are hitting this case.
4870   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
4871     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4872
4873   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4874
4875   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4876   // i32 and try again.
4877   if (hasDominantValue && EltSize <= 32) {
4878     if (!isConstant) {
4879       SDValue N;
4880
4881       // If we are VDUPing a value that comes directly from a vector, that will
4882       // cause an unnecessary move to and from a GPR, where instead we could
4883       // just use VDUPLANE. We can only do this if the lane being extracted
4884       // is at a constant index, as the VDUP from lane instructions only have
4885       // constant-index forms.
4886       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4887           isa<ConstantSDNode>(Value->getOperand(1))) {
4888         // We need to create a new undef vector to use for the VDUPLANE if the
4889         // size of the vector from which we get the value is different than the
4890         // size of the vector that we need to create. We will insert the element
4891         // such that the register coalescer will remove unnecessary copies.
4892         if (VT != Value->getOperand(0).getValueType()) {
4893           ConstantSDNode *constIndex;
4894           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4895           assert(constIndex && "The index is not a constant!");
4896           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4897                              VT.getVectorNumElements();
4898           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4899                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4900                         Value, DAG.getConstant(index, MVT::i32)),
4901                            DAG.getConstant(index, MVT::i32));
4902         } else
4903           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4904                         Value->getOperand(0), Value->getOperand(1));
4905       } else
4906         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4907
4908       if (!usesOnlyOneValue) {
4909         // The dominant value was splatted as 'N', but we now have to insert
4910         // all differing elements.
4911         for (unsigned I = 0; I < NumElts; ++I) {
4912           if (Op.getOperand(I) == Value)
4913             continue;
4914           SmallVector<SDValue, 3> Ops;
4915           Ops.push_back(N);
4916           Ops.push_back(Op.getOperand(I));
4917           Ops.push_back(DAG.getConstant(I, MVT::i32));
4918           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4919         }
4920       }
4921       return N;
4922     }
4923     if (VT.getVectorElementType().isFloatingPoint()) {
4924       SmallVector<SDValue, 8> Ops;
4925       for (unsigned i = 0; i < NumElts; ++i)
4926         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4927                                   Op.getOperand(i)));
4928       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4929       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4930       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4931       if (Val.getNode())
4932         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4933     }
4934     if (usesOnlyOneValue) {
4935       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4936       if (isConstant && Val.getNode())
4937         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4938     }
4939   }
4940
4941   // If all elements are constants and the case above didn't get hit, fall back
4942   // to the default expansion, which will generate a load from the constant
4943   // pool.
4944   if (isConstant)
4945     return SDValue();
4946
4947   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4948   if (NumElts >= 4) {
4949     SDValue shuffle = ReconstructShuffle(Op, DAG);
4950     if (shuffle != SDValue())
4951       return shuffle;
4952   }
4953
4954   // Vectors with 32- or 64-bit elements can be built by directly assigning
4955   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4956   // will be legalized.
4957   if (EltSize >= 32) {
4958     // Do the expansion with floating-point types, since that is what the VFP
4959     // registers are defined to use, and since i64 is not legal.
4960     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4961     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4962     SmallVector<SDValue, 8> Ops;
4963     for (unsigned i = 0; i < NumElts; ++i)
4964       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4965     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4966     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4967   }
4968
4969   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
4970   // know the default expansion would otherwise fall back on something even
4971   // worse. For a vector with one or two non-undef values, that's
4972   // scalar_to_vector for the elements followed by a shuffle (provided the
4973   // shuffle is valid for the target) and materialization element by element
4974   // on the stack followed by a load for everything else.
4975   if (!isConstant && !usesOnlyOneValue) {
4976     SDValue Vec = DAG.getUNDEF(VT);
4977     for (unsigned i = 0 ; i < NumElts; ++i) {
4978       SDValue V = Op.getOperand(i);
4979       if (V.getOpcode() == ISD::UNDEF)
4980         continue;
4981       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
4982       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
4983     }
4984     return Vec;
4985   }
4986
4987   return SDValue();
4988 }
4989
4990 // Gather data to see if the operation can be modelled as a
4991 // shuffle in combination with VEXTs.
4992 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4993                                               SelectionDAG &DAG) const {
4994   SDLoc dl(Op);
4995   EVT VT = Op.getValueType();
4996   unsigned NumElts = VT.getVectorNumElements();
4997
4998   SmallVector<SDValue, 2> SourceVecs;
4999   SmallVector<unsigned, 2> MinElts;
5000   SmallVector<unsigned, 2> MaxElts;
5001
5002   for (unsigned i = 0; i < NumElts; ++i) {
5003     SDValue V = Op.getOperand(i);
5004     if (V.getOpcode() == ISD::UNDEF)
5005       continue;
5006     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5007       // A shuffle can only come from building a vector from various
5008       // elements of other vectors.
5009       return SDValue();
5010     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5011                VT.getVectorElementType()) {
5012       // This code doesn't know how to handle shuffles where the vector
5013       // element types do not match (this happens because type legalization
5014       // promotes the return type of EXTRACT_VECTOR_ELT).
5015       // FIXME: It might be appropriate to extend this code to handle
5016       // mismatched types.
5017       return SDValue();
5018     }
5019
5020     // Record this extraction against the appropriate vector if possible...
5021     SDValue SourceVec = V.getOperand(0);
5022     // If the element number isn't a constant, we can't effectively
5023     // analyze what's going on.
5024     if (!isa<ConstantSDNode>(V.getOperand(1)))
5025       return SDValue();
5026     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5027     bool FoundSource = false;
5028     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5029       if (SourceVecs[j] == SourceVec) {
5030         if (MinElts[j] > EltNo)
5031           MinElts[j] = EltNo;
5032         if (MaxElts[j] < EltNo)
5033           MaxElts[j] = EltNo;
5034         FoundSource = true;
5035         break;
5036       }
5037     }
5038
5039     // Or record a new source if not...
5040     if (!FoundSource) {
5041       SourceVecs.push_back(SourceVec);
5042       MinElts.push_back(EltNo);
5043       MaxElts.push_back(EltNo);
5044     }
5045   }
5046
5047   // Currently only do something sane when at most two source vectors
5048   // involved.
5049   if (SourceVecs.size() > 2)
5050     return SDValue();
5051
5052   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5053   int VEXTOffsets[2] = {0, 0};
5054
5055   // This loop extracts the usage patterns of the source vectors
5056   // and prepares appropriate SDValues for a shuffle if possible.
5057   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5058     if (SourceVecs[i].getValueType() == VT) {
5059       // No VEXT necessary
5060       ShuffleSrcs[i] = SourceVecs[i];
5061       VEXTOffsets[i] = 0;
5062       continue;
5063     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5064       // It probably isn't worth padding out a smaller vector just to
5065       // break it down again in a shuffle.
5066       return SDValue();
5067     }
5068
5069     // Since only 64-bit and 128-bit vectors are legal on ARM and
5070     // we've eliminated the other cases...
5071     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5072            "unexpected vector sizes in ReconstructShuffle");
5073
5074     if (MaxElts[i] - MinElts[i] >= NumElts) {
5075       // Span too large for a VEXT to cope
5076       return SDValue();
5077     }
5078
5079     if (MinElts[i] >= NumElts) {
5080       // The extraction can just take the second half
5081       VEXTOffsets[i] = NumElts;
5082       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5083                                    SourceVecs[i],
5084                                    DAG.getIntPtrConstant(NumElts));
5085     } else if (MaxElts[i] < NumElts) {
5086       // The extraction can just take the first half
5087       VEXTOffsets[i] = 0;
5088       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5089                                    SourceVecs[i],
5090                                    DAG.getIntPtrConstant(0));
5091     } else {
5092       // An actual VEXT is needed
5093       VEXTOffsets[i] = MinElts[i];
5094       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5095                                      SourceVecs[i],
5096                                      DAG.getIntPtrConstant(0));
5097       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5098                                      SourceVecs[i],
5099                                      DAG.getIntPtrConstant(NumElts));
5100       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5101                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5102     }
5103   }
5104
5105   SmallVector<int, 8> Mask;
5106
5107   for (unsigned i = 0; i < NumElts; ++i) {
5108     SDValue Entry = Op.getOperand(i);
5109     if (Entry.getOpcode() == ISD::UNDEF) {
5110       Mask.push_back(-1);
5111       continue;
5112     }
5113
5114     SDValue ExtractVec = Entry.getOperand(0);
5115     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5116                                           .getOperand(1))->getSExtValue();
5117     if (ExtractVec == SourceVecs[0]) {
5118       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5119     } else {
5120       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5121     }
5122   }
5123
5124   // Final check before we try to produce nonsense...
5125   if (isShuffleMaskLegal(Mask, VT))
5126     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5127                                 &Mask[0]);
5128
5129   return SDValue();
5130 }
5131
5132 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5133 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5134 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5135 /// are assumed to be legal.
5136 bool
5137 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5138                                       EVT VT) const {
5139   if (VT.getVectorNumElements() == 4 &&
5140       (VT.is128BitVector() || VT.is64BitVector())) {
5141     unsigned PFIndexes[4];
5142     for (unsigned i = 0; i != 4; ++i) {
5143       if (M[i] < 0)
5144         PFIndexes[i] = 8;
5145       else
5146         PFIndexes[i] = M[i];
5147     }
5148
5149     // Compute the index in the perfect shuffle table.
5150     unsigned PFTableIndex =
5151       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5152     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5153     unsigned Cost = (PFEntry >> 30);
5154
5155     if (Cost <= 4)
5156       return true;
5157   }
5158
5159   bool ReverseVEXT;
5160   unsigned Imm, WhichResult;
5161
5162   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5163   return (EltSize >= 32 ||
5164           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5165           isVREVMask(M, VT, 64) ||
5166           isVREVMask(M, VT, 32) ||
5167           isVREVMask(M, VT, 16) ||
5168           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5169           isVTBLMask(M, VT) ||
5170           isVTRNMask(M, VT, WhichResult) ||
5171           isVUZPMask(M, VT, WhichResult) ||
5172           isVZIPMask(M, VT, WhichResult) ||
5173           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5174           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5175           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5176           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5177 }
5178
5179 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5180 /// the specified operations to build the shuffle.
5181 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5182                                       SDValue RHS, SelectionDAG &DAG,
5183                                       SDLoc dl) {
5184   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5185   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5186   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5187
5188   enum {
5189     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5190     OP_VREV,
5191     OP_VDUP0,
5192     OP_VDUP1,
5193     OP_VDUP2,
5194     OP_VDUP3,
5195     OP_VEXT1,
5196     OP_VEXT2,
5197     OP_VEXT3,
5198     OP_VUZPL, // VUZP, left result
5199     OP_VUZPR, // VUZP, right result
5200     OP_VZIPL, // VZIP, left result
5201     OP_VZIPR, // VZIP, right result
5202     OP_VTRNL, // VTRN, left result
5203     OP_VTRNR  // VTRN, right result
5204   };
5205
5206   if (OpNum == OP_COPY) {
5207     if (LHSID == (1*9+2)*9+3) return LHS;
5208     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5209     return RHS;
5210   }
5211
5212   SDValue OpLHS, OpRHS;
5213   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5214   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5215   EVT VT = OpLHS.getValueType();
5216
5217   switch (OpNum) {
5218   default: llvm_unreachable("Unknown shuffle opcode!");
5219   case OP_VREV:
5220     // VREV divides the vector in half and swaps within the half.
5221     if (VT.getVectorElementType() == MVT::i32 ||
5222         VT.getVectorElementType() == MVT::f32)
5223       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5224     // vrev <4 x i16> -> VREV32
5225     if (VT.getVectorElementType() == MVT::i16)
5226       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5227     // vrev <4 x i8> -> VREV16
5228     assert(VT.getVectorElementType() == MVT::i8);
5229     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5230   case OP_VDUP0:
5231   case OP_VDUP1:
5232   case OP_VDUP2:
5233   case OP_VDUP3:
5234     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5235                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5236   case OP_VEXT1:
5237   case OP_VEXT2:
5238   case OP_VEXT3:
5239     return DAG.getNode(ARMISD::VEXT, dl, VT,
5240                        OpLHS, OpRHS,
5241                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5242   case OP_VUZPL:
5243   case OP_VUZPR:
5244     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5245                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5246   case OP_VZIPL:
5247   case OP_VZIPR:
5248     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5249                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5250   case OP_VTRNL:
5251   case OP_VTRNR:
5252     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5253                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5254   }
5255 }
5256
5257 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5258                                        ArrayRef<int> ShuffleMask,
5259                                        SelectionDAG &DAG) {
5260   // Check to see if we can use the VTBL instruction.
5261   SDValue V1 = Op.getOperand(0);
5262   SDValue V2 = Op.getOperand(1);
5263   SDLoc DL(Op);
5264
5265   SmallVector<SDValue, 8> VTBLMask;
5266   for (ArrayRef<int>::iterator
5267          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5268     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5269
5270   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5271     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5272                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5273                                    &VTBLMask[0], 8));
5274
5275   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5276                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5277                                  &VTBLMask[0], 8));
5278 }
5279
5280 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5281                                                       SelectionDAG &DAG) {
5282   SDLoc DL(Op);
5283   SDValue OpLHS = Op.getOperand(0);
5284   EVT VT = OpLHS.getValueType();
5285
5286   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5287          "Expect an v8i16/v16i8 type");
5288   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5289   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5290   // extract the first 8 bytes into the top double word and the last 8 bytes
5291   // into the bottom double word. The v8i16 case is similar.
5292   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5293   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5294                      DAG.getConstant(ExtractNum, MVT::i32));
5295 }
5296
5297 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5298   SDValue V1 = Op.getOperand(0);
5299   SDValue V2 = Op.getOperand(1);
5300   SDLoc dl(Op);
5301   EVT VT = Op.getValueType();
5302   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5303
5304   // Convert shuffles that are directly supported on NEON to target-specific
5305   // DAG nodes, instead of keeping them as shuffles and matching them again
5306   // during code selection.  This is more efficient and avoids the possibility
5307   // of inconsistencies between legalization and selection.
5308   // FIXME: floating-point vectors should be canonicalized to integer vectors
5309   // of the same time so that they get CSEd properly.
5310   ArrayRef<int> ShuffleMask = SVN->getMask();
5311
5312   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5313   if (EltSize <= 32) {
5314     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5315       int Lane = SVN->getSplatIndex();
5316       // If this is undef splat, generate it via "just" vdup, if possible.
5317       if (Lane == -1) Lane = 0;
5318
5319       // Test if V1 is a SCALAR_TO_VECTOR.
5320       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5321         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5322       }
5323       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5324       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5325       // reaches it).
5326       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5327           !isa<ConstantSDNode>(V1.getOperand(0))) {
5328         bool IsScalarToVector = true;
5329         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5330           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5331             IsScalarToVector = false;
5332             break;
5333           }
5334         if (IsScalarToVector)
5335           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5336       }
5337       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5338                          DAG.getConstant(Lane, MVT::i32));
5339     }
5340
5341     bool ReverseVEXT;
5342     unsigned Imm;
5343     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5344       if (ReverseVEXT)
5345         std::swap(V1, V2);
5346       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5347                          DAG.getConstant(Imm, MVT::i32));
5348     }
5349
5350     if (isVREVMask(ShuffleMask, VT, 64))
5351       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5352     if (isVREVMask(ShuffleMask, VT, 32))
5353       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5354     if (isVREVMask(ShuffleMask, VT, 16))
5355       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5356
5357     if (V2->getOpcode() == ISD::UNDEF &&
5358         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5359       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5360                          DAG.getConstant(Imm, MVT::i32));
5361     }
5362
5363     // Check for Neon shuffles that modify both input vectors in place.
5364     // If both results are used, i.e., if there are two shuffles with the same
5365     // source operands and with masks corresponding to both results of one of
5366     // these operations, DAG memoization will ensure that a single node is
5367     // used for both shuffles.
5368     unsigned WhichResult;
5369     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5370       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5371                          V1, V2).getValue(WhichResult);
5372     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5373       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5374                          V1, V2).getValue(WhichResult);
5375     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5376       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5377                          V1, V2).getValue(WhichResult);
5378
5379     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5380       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5381                          V1, V1).getValue(WhichResult);
5382     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5383       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5384                          V1, V1).getValue(WhichResult);
5385     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5386       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5387                          V1, V1).getValue(WhichResult);
5388   }
5389
5390   // If the shuffle is not directly supported and it has 4 elements, use
5391   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5392   unsigned NumElts = VT.getVectorNumElements();
5393   if (NumElts == 4) {
5394     unsigned PFIndexes[4];
5395     for (unsigned i = 0; i != 4; ++i) {
5396       if (ShuffleMask[i] < 0)
5397         PFIndexes[i] = 8;
5398       else
5399         PFIndexes[i] = ShuffleMask[i];
5400     }
5401
5402     // Compute the index in the perfect shuffle table.
5403     unsigned PFTableIndex =
5404       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5405     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5406     unsigned Cost = (PFEntry >> 30);
5407
5408     if (Cost <= 4)
5409       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5410   }
5411
5412   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5413   if (EltSize >= 32) {
5414     // Do the expansion with floating-point types, since that is what the VFP
5415     // registers are defined to use, and since i64 is not legal.
5416     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5417     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5418     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5419     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5420     SmallVector<SDValue, 8> Ops;
5421     for (unsigned i = 0; i < NumElts; ++i) {
5422       if (ShuffleMask[i] < 0)
5423         Ops.push_back(DAG.getUNDEF(EltVT));
5424       else
5425         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5426                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5427                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5428                                                   MVT::i32)));
5429     }
5430     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5431     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5432   }
5433
5434   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5435     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5436
5437   if (VT == MVT::v8i8) {
5438     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5439     if (NewOp.getNode())
5440       return NewOp;
5441   }
5442
5443   return SDValue();
5444 }
5445
5446 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5447   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5448   SDValue Lane = Op.getOperand(2);
5449   if (!isa<ConstantSDNode>(Lane))
5450     return SDValue();
5451
5452   return Op;
5453 }
5454
5455 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5456   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5457   SDValue Lane = Op.getOperand(1);
5458   if (!isa<ConstantSDNode>(Lane))
5459     return SDValue();
5460
5461   SDValue Vec = Op.getOperand(0);
5462   if (Op.getValueType() == MVT::i32 &&
5463       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5464     SDLoc dl(Op);
5465     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5466   }
5467
5468   return Op;
5469 }
5470
5471 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5472   // The only time a CONCAT_VECTORS operation can have legal types is when
5473   // two 64-bit vectors are concatenated to a 128-bit vector.
5474   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5475          "unexpected CONCAT_VECTORS");
5476   SDLoc dl(Op);
5477   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5478   SDValue Op0 = Op.getOperand(0);
5479   SDValue Op1 = Op.getOperand(1);
5480   if (Op0.getOpcode() != ISD::UNDEF)
5481     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5482                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5483                       DAG.getIntPtrConstant(0));
5484   if (Op1.getOpcode() != ISD::UNDEF)
5485     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5486                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5487                       DAG.getIntPtrConstant(1));
5488   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5489 }
5490
5491 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5492 /// element has been zero/sign-extended, depending on the isSigned parameter,
5493 /// from an integer type half its size.
5494 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5495                                    bool isSigned) {
5496   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5497   EVT VT = N->getValueType(0);
5498   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5499     SDNode *BVN = N->getOperand(0).getNode();
5500     if (BVN->getValueType(0) != MVT::v4i32 ||
5501         BVN->getOpcode() != ISD::BUILD_VECTOR)
5502       return false;
5503     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5504     unsigned HiElt = 1 - LoElt;
5505     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5506     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5507     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5508     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5509     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5510       return false;
5511     if (isSigned) {
5512       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5513           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5514         return true;
5515     } else {
5516       if (Hi0->isNullValue() && Hi1->isNullValue())
5517         return true;
5518     }
5519     return false;
5520   }
5521
5522   if (N->getOpcode() != ISD::BUILD_VECTOR)
5523     return false;
5524
5525   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5526     SDNode *Elt = N->getOperand(i).getNode();
5527     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5528       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5529       unsigned HalfSize = EltSize / 2;
5530       if (isSigned) {
5531         if (!isIntN(HalfSize, C->getSExtValue()))
5532           return false;
5533       } else {
5534         if (!isUIntN(HalfSize, C->getZExtValue()))
5535           return false;
5536       }
5537       continue;
5538     }
5539     return false;
5540   }
5541
5542   return true;
5543 }
5544
5545 /// isSignExtended - Check if a node is a vector value that is sign-extended
5546 /// or a constant BUILD_VECTOR with sign-extended elements.
5547 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5548   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5549     return true;
5550   if (isExtendedBUILD_VECTOR(N, DAG, true))
5551     return true;
5552   return false;
5553 }
5554
5555 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5556 /// or a constant BUILD_VECTOR with zero-extended elements.
5557 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5558   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5559     return true;
5560   if (isExtendedBUILD_VECTOR(N, DAG, false))
5561     return true;
5562   return false;
5563 }
5564
5565 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5566   if (OrigVT.getSizeInBits() >= 64)
5567     return OrigVT;
5568
5569   assert(OrigVT.isSimple() && "Expecting a simple value type");
5570
5571   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5572   switch (OrigSimpleTy) {
5573   default: llvm_unreachable("Unexpected Vector Type");
5574   case MVT::v2i8:
5575   case MVT::v2i16:
5576      return MVT::v2i32;
5577   case MVT::v4i8:
5578     return  MVT::v4i16;
5579   }
5580 }
5581
5582 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5583 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5584 /// We insert the required extension here to get the vector to fill a D register.
5585 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5586                                             const EVT &OrigTy,
5587                                             const EVT &ExtTy,
5588                                             unsigned ExtOpcode) {
5589   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5590   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5591   // 64-bits we need to insert a new extension so that it will be 64-bits.
5592   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5593   if (OrigTy.getSizeInBits() >= 64)
5594     return N;
5595
5596   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5597   EVT NewVT = getExtensionTo64Bits(OrigTy);
5598
5599   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5600 }
5601
5602 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5603 /// does not do any sign/zero extension. If the original vector is less
5604 /// than 64 bits, an appropriate extension will be added after the load to
5605 /// reach a total size of 64 bits. We have to add the extension separately
5606 /// because ARM does not have a sign/zero extending load for vectors.
5607 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5608   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5609
5610   // The load already has the right type.
5611   if (ExtendedTy == LD->getMemoryVT())
5612     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5613                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5614                 LD->isNonTemporal(), LD->isInvariant(),
5615                 LD->getAlignment());
5616
5617   // We need to create a zextload/sextload. We cannot just create a load
5618   // followed by a zext/zext node because LowerMUL is also run during normal
5619   // operation legalization where we can't create illegal types.
5620   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5621                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5622                         LD->getMemoryVT(), LD->isVolatile(),
5623                         LD->isNonTemporal(), LD->getAlignment());
5624 }
5625
5626 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5627 /// extending load, or BUILD_VECTOR with extended elements, return the
5628 /// unextended value. The unextended vector should be 64 bits so that it can
5629 /// be used as an operand to a VMULL instruction. If the original vector size
5630 /// before extension is less than 64 bits we add a an extension to resize
5631 /// the vector to 64 bits.
5632 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5633   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5634     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5635                                         N->getOperand(0)->getValueType(0),
5636                                         N->getValueType(0),
5637                                         N->getOpcode());
5638
5639   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5640     return SkipLoadExtensionForVMULL(LD, DAG);
5641
5642   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5643   // have been legalized as a BITCAST from v4i32.
5644   if (N->getOpcode() == ISD::BITCAST) {
5645     SDNode *BVN = N->getOperand(0).getNode();
5646     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5647            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5648     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5649     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5650                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5651   }
5652   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5653   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5654   EVT VT = N->getValueType(0);
5655   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5656   unsigned NumElts = VT.getVectorNumElements();
5657   MVT TruncVT = MVT::getIntegerVT(EltSize);
5658   SmallVector<SDValue, 8> Ops;
5659   for (unsigned i = 0; i != NumElts; ++i) {
5660     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5661     const APInt &CInt = C->getAPIntValue();
5662     // Element types smaller than 32 bits are not legal, so use i32 elements.
5663     // The values are implicitly truncated so sext vs. zext doesn't matter.
5664     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5665   }
5666   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5667                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5668 }
5669
5670 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5671   unsigned Opcode = N->getOpcode();
5672   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5673     SDNode *N0 = N->getOperand(0).getNode();
5674     SDNode *N1 = N->getOperand(1).getNode();
5675     return N0->hasOneUse() && N1->hasOneUse() &&
5676       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5677   }
5678   return false;
5679 }
5680
5681 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5682   unsigned Opcode = N->getOpcode();
5683   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5684     SDNode *N0 = N->getOperand(0).getNode();
5685     SDNode *N1 = N->getOperand(1).getNode();
5686     return N0->hasOneUse() && N1->hasOneUse() &&
5687       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5688   }
5689   return false;
5690 }
5691
5692 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5693   // Multiplications are only custom-lowered for 128-bit vectors so that
5694   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5695   EVT VT = Op.getValueType();
5696   assert(VT.is128BitVector() && VT.isInteger() &&
5697          "unexpected type for custom-lowering ISD::MUL");
5698   SDNode *N0 = Op.getOperand(0).getNode();
5699   SDNode *N1 = Op.getOperand(1).getNode();
5700   unsigned NewOpc = 0;
5701   bool isMLA = false;
5702   bool isN0SExt = isSignExtended(N0, DAG);
5703   bool isN1SExt = isSignExtended(N1, DAG);
5704   if (isN0SExt && isN1SExt)
5705     NewOpc = ARMISD::VMULLs;
5706   else {
5707     bool isN0ZExt = isZeroExtended(N0, DAG);
5708     bool isN1ZExt = isZeroExtended(N1, DAG);
5709     if (isN0ZExt && isN1ZExt)
5710       NewOpc = ARMISD::VMULLu;
5711     else if (isN1SExt || isN1ZExt) {
5712       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5713       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5714       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5715         NewOpc = ARMISD::VMULLs;
5716         isMLA = true;
5717       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5718         NewOpc = ARMISD::VMULLu;
5719         isMLA = true;
5720       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5721         std::swap(N0, N1);
5722         NewOpc = ARMISD::VMULLu;
5723         isMLA = true;
5724       }
5725     }
5726
5727     if (!NewOpc) {
5728       if (VT == MVT::v2i64)
5729         // Fall through to expand this.  It is not legal.
5730         return SDValue();
5731       else
5732         // Other vector multiplications are legal.
5733         return Op;
5734     }
5735   }
5736
5737   // Legalize to a VMULL instruction.
5738   SDLoc DL(Op);
5739   SDValue Op0;
5740   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5741   if (!isMLA) {
5742     Op0 = SkipExtensionForVMULL(N0, DAG);
5743     assert(Op0.getValueType().is64BitVector() &&
5744            Op1.getValueType().is64BitVector() &&
5745            "unexpected types for extended operands to VMULL");
5746     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5747   }
5748
5749   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5750   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5751   //   vmull q0, d4, d6
5752   //   vmlal q0, d5, d6
5753   // is faster than
5754   //   vaddl q0, d4, d5
5755   //   vmovl q1, d6
5756   //   vmul  q0, q0, q1
5757   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5758   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5759   EVT Op1VT = Op1.getValueType();
5760   return DAG.getNode(N0->getOpcode(), DL, VT,
5761                      DAG.getNode(NewOpc, DL, VT,
5762                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5763                      DAG.getNode(NewOpc, DL, VT,
5764                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5765 }
5766
5767 static SDValue
5768 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5769   // Convert to float
5770   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5771   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5772   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5773   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5774   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5775   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5776   // Get reciprocal estimate.
5777   // float4 recip = vrecpeq_f32(yf);
5778   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5779                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5780   // Because char has a smaller range than uchar, we can actually get away
5781   // without any newton steps.  This requires that we use a weird bias
5782   // of 0xb000, however (again, this has been exhaustively tested).
5783   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5784   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5785   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5786   Y = DAG.getConstant(0xb000, MVT::i32);
5787   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5788   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5789   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5790   // Convert back to short.
5791   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5792   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5793   return X;
5794 }
5795
5796 static SDValue
5797 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5798   SDValue N2;
5799   // Convert to float.
5800   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5801   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5802   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5803   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5804   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5805   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5806
5807   // Use reciprocal estimate and one refinement step.
5808   // float4 recip = vrecpeq_f32(yf);
5809   // recip *= vrecpsq_f32(yf, recip);
5810   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5811                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5812   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5813                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5814                    N1, N2);
5815   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5816   // Because short has a smaller range than ushort, we can actually get away
5817   // with only a single newton step.  This requires that we use a weird bias
5818   // of 89, however (again, this has been exhaustively tested).
5819   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5820   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5821   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5822   N1 = DAG.getConstant(0x89, MVT::i32);
5823   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5824   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5825   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5826   // Convert back to integer and return.
5827   // return vmovn_s32(vcvt_s32_f32(result));
5828   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5829   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5830   return N0;
5831 }
5832
5833 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5834   EVT VT = Op.getValueType();
5835   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5836          "unexpected type for custom-lowering ISD::SDIV");
5837
5838   SDLoc dl(Op);
5839   SDValue N0 = Op.getOperand(0);
5840   SDValue N1 = Op.getOperand(1);
5841   SDValue N2, N3;
5842
5843   if (VT == MVT::v8i8) {
5844     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5845     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5846
5847     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5848                      DAG.getIntPtrConstant(4));
5849     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5850                      DAG.getIntPtrConstant(4));
5851     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5852                      DAG.getIntPtrConstant(0));
5853     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5854                      DAG.getIntPtrConstant(0));
5855
5856     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5857     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5858
5859     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5860     N0 = LowerCONCAT_VECTORS(N0, DAG);
5861
5862     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5863     return N0;
5864   }
5865   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5866 }
5867
5868 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5869   EVT VT = Op.getValueType();
5870   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5871          "unexpected type for custom-lowering ISD::UDIV");
5872
5873   SDLoc dl(Op);
5874   SDValue N0 = Op.getOperand(0);
5875   SDValue N1 = Op.getOperand(1);
5876   SDValue N2, N3;
5877
5878   if (VT == MVT::v8i8) {
5879     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5880     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5881
5882     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5883                      DAG.getIntPtrConstant(4));
5884     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5885                      DAG.getIntPtrConstant(4));
5886     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5887                      DAG.getIntPtrConstant(0));
5888     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5889                      DAG.getIntPtrConstant(0));
5890
5891     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5892     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5893
5894     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5895     N0 = LowerCONCAT_VECTORS(N0, DAG);
5896
5897     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5898                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5899                      N0);
5900     return N0;
5901   }
5902
5903   // v4i16 sdiv ... Convert to float.
5904   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5905   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5906   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5907   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5908   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5909   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5910
5911   // Use reciprocal estimate and two refinement steps.
5912   // float4 recip = vrecpeq_f32(yf);
5913   // recip *= vrecpsq_f32(yf, recip);
5914   // recip *= vrecpsq_f32(yf, recip);
5915   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5916                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5917   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5918                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5919                    BN1, N2);
5920   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5921   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5922                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5923                    BN1, N2);
5924   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5925   // Simply multiplying by the reciprocal estimate can leave us a few ulps
5926   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5927   // and that it will never cause us to return an answer too large).
5928   // float4 result = as_float4(as_int4(xf*recip) + 2);
5929   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5930   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5931   N1 = DAG.getConstant(2, MVT::i32);
5932   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5933   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5934   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5935   // Convert back to integer and return.
5936   // return vmovn_u32(vcvt_s32_f32(result));
5937   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5938   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5939   return N0;
5940 }
5941
5942 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5943   EVT VT = Op.getNode()->getValueType(0);
5944   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5945
5946   unsigned Opc;
5947   bool ExtraOp = false;
5948   switch (Op.getOpcode()) {
5949   default: llvm_unreachable("Invalid code");
5950   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5951   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5952   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5953   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5954   }
5955
5956   if (!ExtraOp)
5957     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5958                        Op.getOperand(1));
5959   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5960                      Op.getOperand(1), Op.getOperand(2));
5961 }
5962
5963 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
5964   assert(Subtarget->isTargetDarwin());
5965
5966   // For iOS, we want to call an alternative entry point: __sincos_stret,
5967   // return values are passed via sret.
5968   SDLoc dl(Op);
5969   SDValue Arg = Op.getOperand(0);
5970   EVT ArgVT = Arg.getValueType();
5971   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
5972
5973   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
5974   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5975
5976   // Pair of floats / doubles used to pass the result.
5977   StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
5978
5979   // Create stack object for sret.
5980   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
5981   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
5982   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
5983   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
5984
5985   ArgListTy Args;
5986   ArgListEntry Entry;
5987
5988   Entry.Node = SRet;
5989   Entry.Ty = RetTy->getPointerTo();
5990   Entry.isSExt = false;
5991   Entry.isZExt = false;
5992   Entry.isSRet = true;
5993   Args.push_back(Entry);
5994
5995   Entry.Node = Arg;
5996   Entry.Ty = ArgTy;
5997   Entry.isSExt = false;
5998   Entry.isZExt = false;
5999   Args.push_back(Entry);
6000
6001   const char *LibcallName  = (ArgVT == MVT::f64)
6002   ? "__sincos_stret" : "__sincosf_stret";
6003   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6004
6005   TargetLowering::
6006   CallLoweringInfo CLI(DAG.getEntryNode(), Type::getVoidTy(*DAG.getContext()),
6007                        false, false, false, false, 0,
6008                        CallingConv::C, /*isTaillCall=*/false,
6009                        /*doesNotRet=*/false, /*isReturnValueUsed*/false,
6010                        Callee, Args, DAG, dl);
6011   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6012
6013   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6014                                 MachinePointerInfo(), false, false, false, 0);
6015
6016   // Address of cos field.
6017   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6018                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6019   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6020                                 MachinePointerInfo(), false, false, false, 0);
6021
6022   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6023   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6024                      LoadSin.getValue(0), LoadCos.getValue(0));
6025 }
6026
6027 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6028   // Monotonic load/store is legal for all targets
6029   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6030     return Op;
6031
6032   // Acquire/Release load/store is not legal for targets without a
6033   // dmb or equivalent available.
6034   return SDValue();
6035 }
6036
6037 static void
6038 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
6039                     SelectionDAG &DAG) {
6040   SDLoc dl(Node);
6041   assert (Node->getValueType(0) == MVT::i64 &&
6042           "Only know how to expand i64 atomics");
6043   AtomicSDNode *AN = cast<AtomicSDNode>(Node);
6044
6045   SmallVector<SDValue, 6> Ops;
6046   Ops.push_back(Node->getOperand(0)); // Chain
6047   Ops.push_back(Node->getOperand(1)); // Ptr
6048   for(unsigned i=2; i<Node->getNumOperands(); i++) {
6049     // Low part
6050     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6051                               Node->getOperand(i), DAG.getIntPtrConstant(0)));
6052     // High part
6053     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6054                               Node->getOperand(i), DAG.getIntPtrConstant(1)));
6055   }
6056   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6057   SDValue Result = DAG.getAtomic(
6058       Node->getOpcode(), dl, MVT::i64, Tys, Ops.data(), Ops.size(),
6059       cast<MemSDNode>(Node)->getMemOperand(), AN->getSuccessOrdering(),
6060       AN->getFailureOrdering(), AN->getSynchScope());
6061   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
6062   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6063   Results.push_back(Result.getValue(2));
6064 }
6065
6066 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6067                                     SmallVectorImpl<SDValue> &Results,
6068                                     SelectionDAG &DAG,
6069                                     const ARMSubtarget *Subtarget) {
6070   SDLoc DL(N);
6071   SDValue Cycles32, OutChain;
6072
6073   if (Subtarget->hasPerfMon()) {
6074     // Under Power Management extensions, the cycle-count is:
6075     //    mrc p15, #0, <Rt>, c9, c13, #0
6076     SDValue Ops[] = { N->getOperand(0), // Chain
6077                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6078                       DAG.getConstant(15, MVT::i32),
6079                       DAG.getConstant(0, MVT::i32),
6080                       DAG.getConstant(9, MVT::i32),
6081                       DAG.getConstant(13, MVT::i32),
6082                       DAG.getConstant(0, MVT::i32)
6083     };
6084
6085     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6086                            DAG.getVTList(MVT::i32, MVT::Other), &Ops[0],
6087                            array_lengthof(Ops));
6088     OutChain = Cycles32.getValue(1);
6089   } else {
6090     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6091     // there are older ARM CPUs that have implementation-specific ways of
6092     // obtaining this information (FIXME!).
6093     Cycles32 = DAG.getConstant(0, MVT::i32);
6094     OutChain = DAG.getEntryNode();
6095   }
6096
6097
6098   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6099                                  Cycles32, DAG.getConstant(0, MVT::i32));
6100   Results.push_back(Cycles64);
6101   Results.push_back(OutChain);
6102 }
6103
6104 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6105   switch (Op.getOpcode()) {
6106   default: llvm_unreachable("Don't know how to custom lower this!");
6107   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6108   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6109   case ISD::GlobalAddress:
6110     return Subtarget->isTargetMachO() ? LowerGlobalAddressDarwin(Op, DAG) :
6111       LowerGlobalAddressELF(Op, DAG);
6112   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6113   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6114   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6115   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6116   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6117   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6118   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6119   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6120   case ISD::SINT_TO_FP:
6121   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6122   case ISD::FP_TO_SINT:
6123   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6124   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6125   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6126   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6127   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6128   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6129   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6130   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6131                                                                Subtarget);
6132   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6133   case ISD::SHL:
6134   case ISD::SRL:
6135   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6136   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6137   case ISD::SRL_PARTS:
6138   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6139   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6140   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6141   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6142   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6143   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6144   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6145   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6146   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6147   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6148   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6149   case ISD::MUL:           return LowerMUL(Op, DAG);
6150   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6151   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6152   case ISD::ADDC:
6153   case ISD::ADDE:
6154   case ISD::SUBC:
6155   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6156   case ISD::ATOMIC_LOAD:
6157   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6158   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6159   case ISD::SDIVREM:
6160   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6161   }
6162 }
6163
6164 /// ReplaceNodeResults - Replace the results of node with an illegal result
6165 /// type with new values built out of custom code.
6166 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6167                                            SmallVectorImpl<SDValue>&Results,
6168                                            SelectionDAG &DAG) const {
6169   SDValue Res;
6170   switch (N->getOpcode()) {
6171   default:
6172     llvm_unreachable("Don't know how to custom expand this!");
6173   case ISD::BITCAST:
6174     Res = ExpandBITCAST(N, DAG);
6175     break;
6176   case ISD::SRL:
6177   case ISD::SRA:
6178     Res = Expand64BitShift(N, DAG, Subtarget);
6179     break;
6180   case ISD::READCYCLECOUNTER:
6181     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6182     return;
6183   case ISD::ATOMIC_STORE:
6184   case ISD::ATOMIC_LOAD:
6185   case ISD::ATOMIC_LOAD_ADD:
6186   case ISD::ATOMIC_LOAD_AND:
6187   case ISD::ATOMIC_LOAD_NAND:
6188   case ISD::ATOMIC_LOAD_OR:
6189   case ISD::ATOMIC_LOAD_SUB:
6190   case ISD::ATOMIC_LOAD_XOR:
6191   case ISD::ATOMIC_SWAP:
6192   case ISD::ATOMIC_CMP_SWAP:
6193   case ISD::ATOMIC_LOAD_MIN:
6194   case ISD::ATOMIC_LOAD_UMIN:
6195   case ISD::ATOMIC_LOAD_MAX:
6196   case ISD::ATOMIC_LOAD_UMAX:
6197     ReplaceATOMIC_OP_64(N, Results, DAG);
6198     return;
6199   }
6200   if (Res.getNode())
6201     Results.push_back(Res);
6202 }
6203
6204 //===----------------------------------------------------------------------===//
6205 //                           ARM Scheduler Hooks
6206 //===----------------------------------------------------------------------===//
6207
6208 MachineBasicBlock *
6209 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
6210                                      MachineBasicBlock *BB,
6211                                      unsigned Size) const {
6212   unsigned dest    = MI->getOperand(0).getReg();
6213   unsigned ptr     = MI->getOperand(1).getReg();
6214   unsigned oldval  = MI->getOperand(2).getReg();
6215   unsigned newval  = MI->getOperand(3).getReg();
6216   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6217   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(4).getImm());
6218   DebugLoc dl = MI->getDebugLoc();
6219   bool isThumb2 = Subtarget->isThumb2();
6220
6221   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6222   unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
6223     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6224     (const TargetRegisterClass*)&ARM::GPRRegClass);
6225
6226   if (isThumb2) {
6227     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6228     MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
6229     MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
6230   }
6231
6232   unsigned ldrOpc, strOpc;
6233   getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6234
6235   MachineFunction *MF = BB->getParent();
6236   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6237   MachineFunction::iterator It = BB;
6238   ++It; // insert the new blocks after the current block
6239
6240   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6241   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6242   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6243   MF->insert(It, loop1MBB);
6244   MF->insert(It, loop2MBB);
6245   MF->insert(It, exitMBB);
6246
6247   // Transfer the remainder of BB and its successor edges to exitMBB.
6248   exitMBB->splice(exitMBB->begin(), BB,
6249                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6250   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6251
6252   //  thisMBB:
6253   //   ...
6254   //   fallthrough --> loop1MBB
6255   BB->addSuccessor(loop1MBB);
6256
6257   // loop1MBB:
6258   //   ldrex dest, [ptr]
6259   //   cmp dest, oldval
6260   //   bne exitMBB
6261   BB = loop1MBB;
6262   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6263   if (ldrOpc == ARM::t2LDREX)
6264     MIB.addImm(0);
6265   AddDefaultPred(MIB);
6266   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6267                  .addReg(dest).addReg(oldval));
6268   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6269     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6270   BB->addSuccessor(loop2MBB);
6271   BB->addSuccessor(exitMBB);
6272
6273   // loop2MBB:
6274   //   strex scratch, newval, [ptr]
6275   //   cmp scratch, #0
6276   //   bne loop1MBB
6277   BB = loop2MBB;
6278   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
6279   if (strOpc == ARM::t2STREX)
6280     MIB.addImm(0);
6281   AddDefaultPred(MIB);
6282   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6283                  .addReg(scratch).addImm(0));
6284   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6285     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6286   BB->addSuccessor(loop1MBB);
6287   BB->addSuccessor(exitMBB);
6288
6289   //  exitMBB:
6290   //   ...
6291   BB = exitMBB;
6292
6293   MI->eraseFromParent();   // The instruction is gone now.
6294
6295   return BB;
6296 }
6297
6298 MachineBasicBlock *
6299 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6300                                     unsigned Size, unsigned BinOpcode) const {
6301   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6302   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6303
6304   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6305   MachineFunction *MF = BB->getParent();
6306   MachineFunction::iterator It = BB;
6307   ++It;
6308
6309   unsigned dest = MI->getOperand(0).getReg();
6310   unsigned ptr = MI->getOperand(1).getReg();
6311   unsigned incr = MI->getOperand(2).getReg();
6312   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6313   DebugLoc dl = MI->getDebugLoc();
6314   bool isThumb2 = Subtarget->isThumb2();
6315
6316   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6317   if (isThumb2) {
6318     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6319     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6320     MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6321   }
6322
6323   unsigned ldrOpc, strOpc;
6324   getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6325
6326   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6327   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6328   MF->insert(It, loopMBB);
6329   MF->insert(It, exitMBB);
6330
6331   // Transfer the remainder of BB and its successor edges to exitMBB.
6332   exitMBB->splice(exitMBB->begin(), BB,
6333                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6334   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6335
6336   const TargetRegisterClass *TRC = isThumb2 ?
6337     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6338     (const TargetRegisterClass*)&ARM::GPRRegClass;
6339   unsigned scratch = MRI.createVirtualRegister(TRC);
6340   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
6341
6342   //  thisMBB:
6343   //   ...
6344   //   fallthrough --> loopMBB
6345   BB->addSuccessor(loopMBB);
6346
6347   //  loopMBB:
6348   //   ldrex dest, ptr
6349   //   <binop> scratch2, dest, incr
6350   //   strex scratch, scratch2, ptr
6351   //   cmp scratch, #0
6352   //   bne- loopMBB
6353   //   fallthrough --> exitMBB
6354   BB = loopMBB;
6355   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6356   if (ldrOpc == ARM::t2LDREX)
6357     MIB.addImm(0);
6358   AddDefaultPred(MIB);
6359   if (BinOpcode) {
6360     // operand order needs to go the other way for NAND
6361     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
6362       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6363                      addReg(incr).addReg(dest)).addReg(0);
6364     else
6365       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6366                      addReg(dest).addReg(incr)).addReg(0);
6367   }
6368
6369   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6370   if (strOpc == ARM::t2STREX)
6371     MIB.addImm(0);
6372   AddDefaultPred(MIB);
6373   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6374                  .addReg(scratch).addImm(0));
6375   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6376     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6377
6378   BB->addSuccessor(loopMBB);
6379   BB->addSuccessor(exitMBB);
6380
6381   //  exitMBB:
6382   //   ...
6383   BB = exitMBB;
6384
6385   MI->eraseFromParent();   // The instruction is gone now.
6386
6387   return BB;
6388 }
6389
6390 MachineBasicBlock *
6391 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
6392                                           MachineBasicBlock *BB,
6393                                           unsigned Size,
6394                                           bool signExtend,
6395                                           ARMCC::CondCodes Cond) const {
6396   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6397
6398   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6399   MachineFunction *MF = BB->getParent();
6400   MachineFunction::iterator It = BB;
6401   ++It;
6402
6403   unsigned dest = MI->getOperand(0).getReg();
6404   unsigned ptr = MI->getOperand(1).getReg();
6405   unsigned incr = MI->getOperand(2).getReg();
6406   unsigned oldval = dest;
6407   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6408   DebugLoc dl = MI->getDebugLoc();
6409   bool isThumb2 = Subtarget->isThumb2();
6410
6411   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6412   if (isThumb2) {
6413     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6414     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6415     MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6416   }
6417
6418   unsigned ldrOpc, strOpc, extendOpc;
6419   getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6420   switch (Size) {
6421   default: llvm_unreachable("unsupported size for AtomicBinaryMinMax!");
6422   case 1:
6423     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
6424     break;
6425   case 2:
6426     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
6427     break;
6428   case 4:
6429     extendOpc = 0;
6430     break;
6431   }
6432
6433   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6434   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6435   MF->insert(It, loopMBB);
6436   MF->insert(It, exitMBB);
6437
6438   // Transfer the remainder of BB and its successor edges to exitMBB.
6439   exitMBB->splice(exitMBB->begin(), BB,
6440                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6441   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6442
6443   const TargetRegisterClass *TRC = isThumb2 ?
6444     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6445     (const TargetRegisterClass*)&ARM::GPRRegClass;
6446   unsigned scratch = MRI.createVirtualRegister(TRC);
6447   unsigned scratch2 = MRI.createVirtualRegister(TRC);
6448
6449   //  thisMBB:
6450   //   ...
6451   //   fallthrough --> loopMBB
6452   BB->addSuccessor(loopMBB);
6453
6454   //  loopMBB:
6455   //   ldrex dest, ptr
6456   //   (sign extend dest, if required)
6457   //   cmp dest, incr
6458   //   cmov.cond scratch2, incr, dest
6459   //   strex scratch, scratch2, ptr
6460   //   cmp scratch, #0
6461   //   bne- loopMBB
6462   //   fallthrough --> exitMBB
6463   BB = loopMBB;
6464   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6465   if (ldrOpc == ARM::t2LDREX)
6466     MIB.addImm(0);
6467   AddDefaultPred(MIB);
6468
6469   // Sign extend the value, if necessary.
6470   if (signExtend && extendOpc) {
6471     oldval = MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass
6472                                                 : &ARM::GPRnopcRegClass);
6473     if (!isThumb2)
6474       MRI.constrainRegClass(dest, &ARM::GPRnopcRegClass);
6475     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
6476                      .addReg(dest)
6477                      .addImm(0));
6478   }
6479
6480   // Build compare and cmov instructions.
6481   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6482                  .addReg(oldval).addReg(incr));
6483   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
6484          .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
6485
6486   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6487   if (strOpc == ARM::t2STREX)
6488     MIB.addImm(0);
6489   AddDefaultPred(MIB);
6490   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6491                  .addReg(scratch).addImm(0));
6492   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6493     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6494
6495   BB->addSuccessor(loopMBB);
6496   BB->addSuccessor(exitMBB);
6497
6498   //  exitMBB:
6499   //   ...
6500   BB = exitMBB;
6501
6502   MI->eraseFromParent();   // The instruction is gone now.
6503
6504   return BB;
6505 }
6506
6507 MachineBasicBlock *
6508 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
6509                                       unsigned Op1, unsigned Op2,
6510                                       bool NeedsCarry, bool IsCmpxchg,
6511                                       bool IsMinMax, ARMCC::CondCodes CC) const {
6512   // This also handles ATOMIC_SWAP and ATOMIC_STORE, indicated by Op1==0.
6513   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6514
6515   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6516   MachineFunction *MF = BB->getParent();
6517   MachineFunction::iterator It = BB;
6518   ++It;
6519
6520   bool isStore = (MI->getOpcode() == ARM::ATOMIC_STORE_I64);
6521   unsigned offset = (isStore ? -2 : 0);
6522   unsigned destlo = MI->getOperand(0).getReg();
6523   unsigned desthi = MI->getOperand(1).getReg();
6524   unsigned ptr = MI->getOperand(offset+2).getReg();
6525   unsigned vallo = MI->getOperand(offset+3).getReg();
6526   unsigned valhi = MI->getOperand(offset+4).getReg();
6527   unsigned OrdIdx = offset + (IsCmpxchg ? 7 : 5);
6528   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(OrdIdx).getImm());
6529   DebugLoc dl = MI->getDebugLoc();
6530   bool isThumb2 = Subtarget->isThumb2();
6531
6532   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6533   if (isThumb2) {
6534     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6535     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6536     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6537     MRI.constrainRegClass(vallo, &ARM::rGPRRegClass);
6538     MRI.constrainRegClass(valhi, &ARM::rGPRRegClass);
6539   }
6540
6541   unsigned ldrOpc, strOpc;
6542   getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6543
6544   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6545   MachineBasicBlock *contBB = 0, *cont2BB = 0;
6546   if (IsCmpxchg || IsMinMax)
6547     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
6548   if (IsCmpxchg)
6549     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
6550   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6551
6552   MF->insert(It, loopMBB);
6553   if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6554   if (IsCmpxchg) MF->insert(It, cont2BB);
6555   MF->insert(It, exitMBB);
6556
6557   // Transfer the remainder of BB and its successor edges to exitMBB.
6558   exitMBB->splice(exitMBB->begin(), BB,
6559                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6560   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6561
6562   const TargetRegisterClass *TRC = isThumb2 ?
6563     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6564     (const TargetRegisterClass*)&ARM::GPRRegClass;
6565   unsigned storesuccess = MRI.createVirtualRegister(TRC);
6566
6567   //  thisMBB:
6568   //   ...
6569   //   fallthrough --> loopMBB
6570   BB->addSuccessor(loopMBB);
6571
6572   //  loopMBB:
6573   //   ldrexd r2, r3, ptr
6574   //   <binopa> r0, r2, incr
6575   //   <binopb> r1, r3, incr
6576   //   strexd storesuccess, r0, r1, ptr
6577   //   cmp storesuccess, #0
6578   //   bne- loopMBB
6579   //   fallthrough --> exitMBB
6580   BB = loopMBB;
6581
6582   if (!isStore) {
6583     // Load
6584     if (isThumb2) {
6585       AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6586                      .addReg(destlo, RegState::Define)
6587                      .addReg(desthi, RegState::Define)
6588                      .addReg(ptr));
6589     } else {
6590       unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6591       AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6592                      .addReg(GPRPair0, RegState::Define).addReg(ptr));
6593       // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
6594       BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6595         .addReg(GPRPair0, 0, ARM::gsub_0);
6596       BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6597         .addReg(GPRPair0, 0, ARM::gsub_1);
6598     }
6599   }
6600
6601   unsigned StoreLo, StoreHi;
6602   if (IsCmpxchg) {
6603     // Add early exit
6604     for (unsigned i = 0; i < 2; i++) {
6605       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6606                                                          ARM::CMPrr))
6607                      .addReg(i == 0 ? destlo : desthi)
6608                      .addReg(i == 0 ? vallo : valhi));
6609       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6610         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6611       BB->addSuccessor(exitMBB);
6612       BB->addSuccessor(i == 0 ? contBB : cont2BB);
6613       BB = (i == 0 ? contBB : cont2BB);
6614     }
6615
6616     // Copy to physregs for strexd
6617     StoreLo = MI->getOperand(5).getReg();
6618     StoreHi = MI->getOperand(6).getReg();
6619   } else if (Op1) {
6620     // Perform binary operation
6621     unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6622     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6623                    .addReg(destlo).addReg(vallo))
6624         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6625     unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6626     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6627                    .addReg(desthi).addReg(valhi))
6628         .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6629
6630     StoreLo = tmpRegLo;
6631     StoreHi = tmpRegHi;
6632   } else {
6633     // Copy to physregs for strexd
6634     StoreLo = vallo;
6635     StoreHi = valhi;
6636   }
6637   if (IsMinMax) {
6638     // Compare and branch to exit block.
6639     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6640       .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6641     BB->addSuccessor(exitMBB);
6642     BB->addSuccessor(contBB);
6643     BB = contBB;
6644     StoreLo = vallo;
6645     StoreHi = valhi;
6646   }
6647
6648   // Store
6649   if (isThumb2) {
6650     MRI.constrainRegClass(StoreLo, &ARM::rGPRRegClass);
6651     MRI.constrainRegClass(StoreHi, &ARM::rGPRRegClass);
6652     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6653                    .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6654   } else {
6655     // Marshal a pair...
6656     unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6657     unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6658     unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6659     BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6660     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6661       .addReg(UndefPair)
6662       .addReg(StoreLo)
6663       .addImm(ARM::gsub_0);
6664     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6665       .addReg(r1)
6666       .addReg(StoreHi)
6667       .addImm(ARM::gsub_1);
6668
6669     // ...and store it
6670     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6671                    .addReg(StorePair).addReg(ptr));
6672   }
6673   // Cmp+jump
6674   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6675                  .addReg(storesuccess).addImm(0));
6676   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6677     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6678
6679   BB->addSuccessor(loopMBB);
6680   BB->addSuccessor(exitMBB);
6681
6682   //  exitMBB:
6683   //   ...
6684   BB = exitMBB;
6685
6686   MI->eraseFromParent();   // The instruction is gone now.
6687
6688   return BB;
6689 }
6690
6691 MachineBasicBlock *
6692 ARMTargetLowering::EmitAtomicLoad64(MachineInstr *MI, MachineBasicBlock *BB) const {
6693
6694   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6695
6696   unsigned destlo = MI->getOperand(0).getReg();
6697   unsigned desthi = MI->getOperand(1).getReg();
6698   unsigned ptr = MI->getOperand(2).getReg();
6699   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6700   DebugLoc dl = MI->getDebugLoc();
6701   bool isThumb2 = Subtarget->isThumb2();
6702
6703   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6704   if (isThumb2) {
6705     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6706     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6707     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6708   }
6709   unsigned ldrOpc, strOpc;
6710   getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6711
6712   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(ldrOpc));
6713
6714   if (isThumb2) {
6715     MIB.addReg(destlo, RegState::Define)
6716        .addReg(desthi, RegState::Define)
6717        .addReg(ptr);
6718
6719   } else {
6720     unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6721     MIB.addReg(GPRPair0, RegState::Define).addReg(ptr);
6722
6723     // Copy GPRPair0 into dest.  (This copy will normally be coalesced.)
6724     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), destlo)
6725       .addReg(GPRPair0, 0, ARM::gsub_0);
6726     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), desthi)
6727       .addReg(GPRPair0, 0, ARM::gsub_1);
6728   }
6729   AddDefaultPred(MIB);
6730
6731   MI->eraseFromParent();   // The instruction is gone now.
6732
6733   return BB;
6734 }
6735
6736 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6737 /// registers the function context.
6738 void ARMTargetLowering::
6739 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6740                        MachineBasicBlock *DispatchBB, int FI) const {
6741   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6742   DebugLoc dl = MI->getDebugLoc();
6743   MachineFunction *MF = MBB->getParent();
6744   MachineRegisterInfo *MRI = &MF->getRegInfo();
6745   MachineConstantPool *MCP = MF->getConstantPool();
6746   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6747   const Function *F = MF->getFunction();
6748
6749   bool isThumb = Subtarget->isThumb();
6750   bool isThumb2 = Subtarget->isThumb2();
6751
6752   unsigned PCLabelId = AFI->createPICLabelUId();
6753   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6754   ARMConstantPoolValue *CPV =
6755     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6756   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6757
6758   const TargetRegisterClass *TRC = isThumb ?
6759     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6760     (const TargetRegisterClass*)&ARM::GPRRegClass;
6761
6762   // Grab constant pool and fixed stack memory operands.
6763   MachineMemOperand *CPMMO =
6764     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6765                              MachineMemOperand::MOLoad, 4, 4);
6766
6767   MachineMemOperand *FIMMOSt =
6768     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6769                              MachineMemOperand::MOStore, 4, 4);
6770
6771   // Load the address of the dispatch MBB into the jump buffer.
6772   if (isThumb2) {
6773     // Incoming value: jbuf
6774     //   ldr.n  r5, LCPI1_1
6775     //   orr    r5, r5, #1
6776     //   add    r5, pc
6777     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6778     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6779     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6780                    .addConstantPoolIndex(CPI)
6781                    .addMemOperand(CPMMO));
6782     // Set the low bit because of thumb mode.
6783     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6784     AddDefaultCC(
6785       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6786                      .addReg(NewVReg1, RegState::Kill)
6787                      .addImm(0x01)));
6788     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6789     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6790       .addReg(NewVReg2, RegState::Kill)
6791       .addImm(PCLabelId);
6792     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6793                    .addReg(NewVReg3, RegState::Kill)
6794                    .addFrameIndex(FI)
6795                    .addImm(36)  // &jbuf[1] :: pc
6796                    .addMemOperand(FIMMOSt));
6797   } else if (isThumb) {
6798     // Incoming value: jbuf
6799     //   ldr.n  r1, LCPI1_4
6800     //   add    r1, pc
6801     //   mov    r2, #1
6802     //   orrs   r1, r2
6803     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6804     //   str    r1, [r2]
6805     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6806     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6807                    .addConstantPoolIndex(CPI)
6808                    .addMemOperand(CPMMO));
6809     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6810     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6811       .addReg(NewVReg1, RegState::Kill)
6812       .addImm(PCLabelId);
6813     // Set the low bit because of thumb mode.
6814     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6815     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6816                    .addReg(ARM::CPSR, RegState::Define)
6817                    .addImm(1));
6818     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6819     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6820                    .addReg(ARM::CPSR, RegState::Define)
6821                    .addReg(NewVReg2, RegState::Kill)
6822                    .addReg(NewVReg3, RegState::Kill));
6823     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6824     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6825                    .addFrameIndex(FI)
6826                    .addImm(36)); // &jbuf[1] :: pc
6827     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6828                    .addReg(NewVReg4, RegState::Kill)
6829                    .addReg(NewVReg5, RegState::Kill)
6830                    .addImm(0)
6831                    .addMemOperand(FIMMOSt));
6832   } else {
6833     // Incoming value: jbuf
6834     //   ldr  r1, LCPI1_1
6835     //   add  r1, pc, r1
6836     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6837     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6838     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6839                    .addConstantPoolIndex(CPI)
6840                    .addImm(0)
6841                    .addMemOperand(CPMMO));
6842     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6843     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6844                    .addReg(NewVReg1, RegState::Kill)
6845                    .addImm(PCLabelId));
6846     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6847                    .addReg(NewVReg2, RegState::Kill)
6848                    .addFrameIndex(FI)
6849                    .addImm(36)  // &jbuf[1] :: pc
6850                    .addMemOperand(FIMMOSt));
6851   }
6852 }
6853
6854 MachineBasicBlock *ARMTargetLowering::
6855 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6856   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6857   DebugLoc dl = MI->getDebugLoc();
6858   MachineFunction *MF = MBB->getParent();
6859   MachineRegisterInfo *MRI = &MF->getRegInfo();
6860   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6861   MachineFrameInfo *MFI = MF->getFrameInfo();
6862   int FI = MFI->getFunctionContextIndex();
6863
6864   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6865     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6866     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6867
6868   // Get a mapping of the call site numbers to all of the landing pads they're
6869   // associated with.
6870   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6871   unsigned MaxCSNum = 0;
6872   MachineModuleInfo &MMI = MF->getMMI();
6873   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6874        ++BB) {
6875     if (!BB->isLandingPad()) continue;
6876
6877     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6878     // pad.
6879     for (MachineBasicBlock::iterator
6880            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6881       if (!II->isEHLabel()) continue;
6882
6883       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6884       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6885
6886       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6887       for (SmallVectorImpl<unsigned>::iterator
6888              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6889            CSI != CSE; ++CSI) {
6890         CallSiteNumToLPad[*CSI].push_back(BB);
6891         MaxCSNum = std::max(MaxCSNum, *CSI);
6892       }
6893       break;
6894     }
6895   }
6896
6897   // Get an ordered list of the machine basic blocks for the jump table.
6898   std::vector<MachineBasicBlock*> LPadList;
6899   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6900   LPadList.reserve(CallSiteNumToLPad.size());
6901   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6902     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6903     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6904            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6905       LPadList.push_back(*II);
6906       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6907     }
6908   }
6909
6910   assert(!LPadList.empty() &&
6911          "No landing pad destinations for the dispatch jump table!");
6912
6913   // Create the jump table and associated information.
6914   MachineJumpTableInfo *JTI =
6915     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6916   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6917   unsigned UId = AFI->createJumpTableUId();
6918   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6919
6920   // Create the MBBs for the dispatch code.
6921
6922   // Shove the dispatch's address into the return slot in the function context.
6923   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6924   DispatchBB->setIsLandingPad();
6925
6926   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6927   unsigned trap_opcode;
6928   if (Subtarget->isThumb())
6929     trap_opcode = ARM::tTRAP;
6930   else
6931     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6932
6933   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6934   DispatchBB->addSuccessor(TrapBB);
6935
6936   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6937   DispatchBB->addSuccessor(DispContBB);
6938
6939   // Insert and MBBs.
6940   MF->insert(MF->end(), DispatchBB);
6941   MF->insert(MF->end(), DispContBB);
6942   MF->insert(MF->end(), TrapBB);
6943
6944   // Insert code into the entry block that creates and registers the function
6945   // context.
6946   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6947
6948   MachineMemOperand *FIMMOLd =
6949     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6950                              MachineMemOperand::MOLoad |
6951                              MachineMemOperand::MOVolatile, 4, 4);
6952
6953   MachineInstrBuilder MIB;
6954   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6955
6956   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6957   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6958
6959   // Add a register mask with no preserved registers.  This results in all
6960   // registers being marked as clobbered.
6961   MIB.addRegMask(RI.getNoPreservedMask());
6962
6963   unsigned NumLPads = LPadList.size();
6964   if (Subtarget->isThumb2()) {
6965     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6966     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6967                    .addFrameIndex(FI)
6968                    .addImm(4)
6969                    .addMemOperand(FIMMOLd));
6970
6971     if (NumLPads < 256) {
6972       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6973                      .addReg(NewVReg1)
6974                      .addImm(LPadList.size()));
6975     } else {
6976       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6977       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6978                      .addImm(NumLPads & 0xFFFF));
6979
6980       unsigned VReg2 = VReg1;
6981       if ((NumLPads & 0xFFFF0000) != 0) {
6982         VReg2 = MRI->createVirtualRegister(TRC);
6983         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6984                        .addReg(VReg1)
6985                        .addImm(NumLPads >> 16));
6986       }
6987
6988       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6989                      .addReg(NewVReg1)
6990                      .addReg(VReg2));
6991     }
6992
6993     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6994       .addMBB(TrapBB)
6995       .addImm(ARMCC::HI)
6996       .addReg(ARM::CPSR);
6997
6998     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6999     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7000                    .addJumpTableIndex(MJTI)
7001                    .addImm(UId));
7002
7003     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7004     AddDefaultCC(
7005       AddDefaultPred(
7006         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7007         .addReg(NewVReg3, RegState::Kill)
7008         .addReg(NewVReg1)
7009         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7010
7011     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7012       .addReg(NewVReg4, RegState::Kill)
7013       .addReg(NewVReg1)
7014       .addJumpTableIndex(MJTI)
7015       .addImm(UId);
7016   } else if (Subtarget->isThumb()) {
7017     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7018     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7019                    .addFrameIndex(FI)
7020                    .addImm(1)
7021                    .addMemOperand(FIMMOLd));
7022
7023     if (NumLPads < 256) {
7024       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7025                      .addReg(NewVReg1)
7026                      .addImm(NumLPads));
7027     } else {
7028       MachineConstantPool *ConstantPool = MF->getConstantPool();
7029       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7030       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7031
7032       // MachineConstantPool wants an explicit alignment.
7033       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7034       if (Align == 0)
7035         Align = getDataLayout()->getTypeAllocSize(C->getType());
7036       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7037
7038       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7039       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7040                      .addReg(VReg1, RegState::Define)
7041                      .addConstantPoolIndex(Idx));
7042       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7043                      .addReg(NewVReg1)
7044                      .addReg(VReg1));
7045     }
7046
7047     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7048       .addMBB(TrapBB)
7049       .addImm(ARMCC::HI)
7050       .addReg(ARM::CPSR);
7051
7052     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7053     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7054                    .addReg(ARM::CPSR, RegState::Define)
7055                    .addReg(NewVReg1)
7056                    .addImm(2));
7057
7058     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7059     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7060                    .addJumpTableIndex(MJTI)
7061                    .addImm(UId));
7062
7063     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7064     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7065                    .addReg(ARM::CPSR, RegState::Define)
7066                    .addReg(NewVReg2, RegState::Kill)
7067                    .addReg(NewVReg3));
7068
7069     MachineMemOperand *JTMMOLd =
7070       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7071                                MachineMemOperand::MOLoad, 4, 4);
7072
7073     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7074     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7075                    .addReg(NewVReg4, RegState::Kill)
7076                    .addImm(0)
7077                    .addMemOperand(JTMMOLd));
7078
7079     unsigned NewVReg6 = NewVReg5;
7080     if (RelocM == Reloc::PIC_) {
7081       NewVReg6 = MRI->createVirtualRegister(TRC);
7082       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7083                      .addReg(ARM::CPSR, RegState::Define)
7084                      .addReg(NewVReg5, RegState::Kill)
7085                      .addReg(NewVReg3));
7086     }
7087
7088     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7089       .addReg(NewVReg6, RegState::Kill)
7090       .addJumpTableIndex(MJTI)
7091       .addImm(UId);
7092   } else {
7093     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7094     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7095                    .addFrameIndex(FI)
7096                    .addImm(4)
7097                    .addMemOperand(FIMMOLd));
7098
7099     if (NumLPads < 256) {
7100       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7101                      .addReg(NewVReg1)
7102                      .addImm(NumLPads));
7103     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7104       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7105       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7106                      .addImm(NumLPads & 0xFFFF));
7107
7108       unsigned VReg2 = VReg1;
7109       if ((NumLPads & 0xFFFF0000) != 0) {
7110         VReg2 = MRI->createVirtualRegister(TRC);
7111         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7112                        .addReg(VReg1)
7113                        .addImm(NumLPads >> 16));
7114       }
7115
7116       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7117                      .addReg(NewVReg1)
7118                      .addReg(VReg2));
7119     } else {
7120       MachineConstantPool *ConstantPool = MF->getConstantPool();
7121       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7122       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7123
7124       // MachineConstantPool wants an explicit alignment.
7125       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7126       if (Align == 0)
7127         Align = getDataLayout()->getTypeAllocSize(C->getType());
7128       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7129
7130       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7131       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7132                      .addReg(VReg1, RegState::Define)
7133                      .addConstantPoolIndex(Idx)
7134                      .addImm(0));
7135       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7136                      .addReg(NewVReg1)
7137                      .addReg(VReg1, RegState::Kill));
7138     }
7139
7140     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7141       .addMBB(TrapBB)
7142       .addImm(ARMCC::HI)
7143       .addReg(ARM::CPSR);
7144
7145     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7146     AddDefaultCC(
7147       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7148                      .addReg(NewVReg1)
7149                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7150     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7151     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7152                    .addJumpTableIndex(MJTI)
7153                    .addImm(UId));
7154
7155     MachineMemOperand *JTMMOLd =
7156       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7157                                MachineMemOperand::MOLoad, 4, 4);
7158     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7159     AddDefaultPred(
7160       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7161       .addReg(NewVReg3, RegState::Kill)
7162       .addReg(NewVReg4)
7163       .addImm(0)
7164       .addMemOperand(JTMMOLd));
7165
7166     if (RelocM == Reloc::PIC_) {
7167       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7168         .addReg(NewVReg5, RegState::Kill)
7169         .addReg(NewVReg4)
7170         .addJumpTableIndex(MJTI)
7171         .addImm(UId);
7172     } else {
7173       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7174         .addReg(NewVReg5, RegState::Kill)
7175         .addJumpTableIndex(MJTI)
7176         .addImm(UId);
7177     }
7178   }
7179
7180   // Add the jump table entries as successors to the MBB.
7181   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7182   for (std::vector<MachineBasicBlock*>::iterator
7183          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7184     MachineBasicBlock *CurMBB = *I;
7185     if (SeenMBBs.insert(CurMBB))
7186       DispContBB->addSuccessor(CurMBB);
7187   }
7188
7189   // N.B. the order the invoke BBs are processed in doesn't matter here.
7190   const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
7191   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7192   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
7193          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
7194     MachineBasicBlock *BB = *I;
7195
7196     // Remove the landing pad successor from the invoke block and replace it
7197     // with the new dispatch block.
7198     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7199                                                   BB->succ_end());
7200     while (!Successors.empty()) {
7201       MachineBasicBlock *SMBB = Successors.pop_back_val();
7202       if (SMBB->isLandingPad()) {
7203         BB->removeSuccessor(SMBB);
7204         MBBLPads.push_back(SMBB);
7205       }
7206     }
7207
7208     BB->addSuccessor(DispatchBB);
7209
7210     // Find the invoke call and mark all of the callee-saved registers as
7211     // 'implicit defined' so that they're spilled. This prevents code from
7212     // moving instructions to before the EH block, where they will never be
7213     // executed.
7214     for (MachineBasicBlock::reverse_iterator
7215            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7216       if (!II->isCall()) continue;
7217
7218       DenseMap<unsigned, bool> DefRegs;
7219       for (MachineInstr::mop_iterator
7220              OI = II->operands_begin(), OE = II->operands_end();
7221            OI != OE; ++OI) {
7222         if (!OI->isReg()) continue;
7223         DefRegs[OI->getReg()] = true;
7224       }
7225
7226       MachineInstrBuilder MIB(*MF, &*II);
7227
7228       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7229         unsigned Reg = SavedRegs[i];
7230         if (Subtarget->isThumb2() &&
7231             !ARM::tGPRRegClass.contains(Reg) &&
7232             !ARM::hGPRRegClass.contains(Reg))
7233           continue;
7234         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7235           continue;
7236         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7237           continue;
7238         if (!DefRegs[Reg])
7239           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7240       }
7241
7242       break;
7243     }
7244   }
7245
7246   // Mark all former landing pads as non-landing pads. The dispatch is the only
7247   // landing pad now.
7248   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7249          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7250     (*I)->setIsLandingPad(false);
7251
7252   // The instruction is gone now.
7253   MI->eraseFromParent();
7254
7255   return MBB;
7256 }
7257
7258 static
7259 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7260   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7261        E = MBB->succ_end(); I != E; ++I)
7262     if (*I != Succ)
7263       return *I;
7264   llvm_unreachable("Expecting a BB with two successors!");
7265 }
7266
7267 /// Return the load opcode for a given load size. If load size >= 8,
7268 /// neon opcode will be returned.
7269 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7270   if (LdSize >= 8)
7271     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7272                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7273   if (IsThumb1)
7274     return LdSize == 4 ? ARM::tLDRi
7275                        : LdSize == 2 ? ARM::tLDRHi
7276                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7277   if (IsThumb2)
7278     return LdSize == 4 ? ARM::t2LDR_POST
7279                        : LdSize == 2 ? ARM::t2LDRH_POST
7280                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7281   return LdSize == 4 ? ARM::LDR_POST_IMM
7282                      : LdSize == 2 ? ARM::LDRH_POST
7283                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7284 }
7285
7286 /// Return the store opcode for a given store size. If store size >= 8,
7287 /// neon opcode will be returned.
7288 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7289   if (StSize >= 8)
7290     return StSize == 16 ? ARM::VST1q32wb_fixed
7291                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7292   if (IsThumb1)
7293     return StSize == 4 ? ARM::tSTRi
7294                        : StSize == 2 ? ARM::tSTRHi
7295                                      : StSize == 1 ? ARM::tSTRBi : 0;
7296   if (IsThumb2)
7297     return StSize == 4 ? ARM::t2STR_POST
7298                        : StSize == 2 ? ARM::t2STRH_POST
7299                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7300   return StSize == 4 ? ARM::STR_POST_IMM
7301                      : StSize == 2 ? ARM::STRH_POST
7302                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7303 }
7304
7305 /// Emit a post-increment load operation with given size. The instructions
7306 /// will be added to BB at Pos.
7307 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7308                        const TargetInstrInfo *TII, DebugLoc dl,
7309                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7310                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7311   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7312   assert(LdOpc != 0 && "Should have a load opcode");
7313   if (LdSize >= 8) {
7314     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7315                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7316                        .addImm(0));
7317   } else if (IsThumb1) {
7318     // load + update AddrIn
7319     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7320                        .addReg(AddrIn).addImm(0));
7321     MachineInstrBuilder MIB =
7322         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7323     MIB = AddDefaultT1CC(MIB);
7324     MIB.addReg(AddrIn).addImm(LdSize);
7325     AddDefaultPred(MIB);
7326   } else if (IsThumb2) {
7327     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7328                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7329                        .addImm(LdSize));
7330   } else { // arm
7331     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7332                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7333                        .addReg(0).addImm(LdSize));
7334   }
7335 }
7336
7337 /// Emit a post-increment store operation with given size. The instructions
7338 /// will be added to BB at Pos.
7339 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7340                        const TargetInstrInfo *TII, DebugLoc dl,
7341                        unsigned StSize, unsigned Data, unsigned AddrIn,
7342                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7343   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7344   assert(StOpc != 0 && "Should have a store opcode");
7345   if (StSize >= 8) {
7346     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7347                        .addReg(AddrIn).addImm(0).addReg(Data));
7348   } else if (IsThumb1) {
7349     // store + update AddrIn
7350     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7351                        .addReg(AddrIn).addImm(0));
7352     MachineInstrBuilder MIB =
7353         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7354     MIB = AddDefaultT1CC(MIB);
7355     MIB.addReg(AddrIn).addImm(StSize);
7356     AddDefaultPred(MIB);
7357   } else if (IsThumb2) {
7358     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7359                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7360   } else { // arm
7361     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7362                        .addReg(Data).addReg(AddrIn).addReg(0)
7363                        .addImm(StSize));
7364   }
7365 }
7366
7367 MachineBasicBlock *
7368 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7369                                    MachineBasicBlock *BB) const {
7370   // This pseudo instruction has 3 operands: dst, src, size
7371   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7372   // Otherwise, we will generate unrolled scalar copies.
7373   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7374   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7375   MachineFunction::iterator It = BB;
7376   ++It;
7377
7378   unsigned dest = MI->getOperand(0).getReg();
7379   unsigned src = MI->getOperand(1).getReg();
7380   unsigned SizeVal = MI->getOperand(2).getImm();
7381   unsigned Align = MI->getOperand(3).getImm();
7382   DebugLoc dl = MI->getDebugLoc();
7383
7384   MachineFunction *MF = BB->getParent();
7385   MachineRegisterInfo &MRI = MF->getRegInfo();
7386   unsigned UnitSize = 0;
7387   const TargetRegisterClass *TRC = 0;
7388   const TargetRegisterClass *VecTRC = 0;
7389
7390   bool IsThumb1 = Subtarget->isThumb1Only();
7391   bool IsThumb2 = Subtarget->isThumb2();
7392
7393   if (Align & 1) {
7394     UnitSize = 1;
7395   } else if (Align & 2) {
7396     UnitSize = 2;
7397   } else {
7398     // Check whether we can use NEON instructions.
7399     if (!MF->getFunction()->getAttributes().
7400           hasAttribute(AttributeSet::FunctionIndex,
7401                        Attribute::NoImplicitFloat) &&
7402         Subtarget->hasNEON()) {
7403       if ((Align % 16 == 0) && SizeVal >= 16)
7404         UnitSize = 16;
7405       else if ((Align % 8 == 0) && SizeVal >= 8)
7406         UnitSize = 8;
7407     }
7408     // Can't use NEON instructions.
7409     if (UnitSize == 0)
7410       UnitSize = 4;
7411   }
7412
7413   // Select the correct opcode and register class for unit size load/store
7414   bool IsNeon = UnitSize >= 8;
7415   TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
7416                                : (const TargetRegisterClass *)&ARM::GPRRegClass;
7417   if (IsNeon)
7418     VecTRC = UnitSize == 16
7419                  ? (const TargetRegisterClass *)&ARM::DPairRegClass
7420                  : UnitSize == 8
7421                        ? (const TargetRegisterClass *)&ARM::DPRRegClass
7422                        : 0;
7423
7424   unsigned BytesLeft = SizeVal % UnitSize;
7425   unsigned LoopSize = SizeVal - BytesLeft;
7426
7427   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7428     // Use LDR and STR to copy.
7429     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7430     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7431     unsigned srcIn = src;
7432     unsigned destIn = dest;
7433     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7434       unsigned srcOut = MRI.createVirtualRegister(TRC);
7435       unsigned destOut = MRI.createVirtualRegister(TRC);
7436       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7437       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7438                  IsThumb1, IsThumb2);
7439       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7440                  IsThumb1, IsThumb2);
7441       srcIn = srcOut;
7442       destIn = destOut;
7443     }
7444
7445     // Handle the leftover bytes with LDRB and STRB.
7446     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7447     // [destOut] = STRB_POST(scratch, destIn, 1)
7448     for (unsigned i = 0; i < BytesLeft; i++) {
7449       unsigned srcOut = MRI.createVirtualRegister(TRC);
7450       unsigned destOut = MRI.createVirtualRegister(TRC);
7451       unsigned scratch = MRI.createVirtualRegister(TRC);
7452       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7453                  IsThumb1, IsThumb2);
7454       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7455                  IsThumb1, IsThumb2);
7456       srcIn = srcOut;
7457       destIn = destOut;
7458     }
7459     MI->eraseFromParent();   // The instruction is gone now.
7460     return BB;
7461   }
7462
7463   // Expand the pseudo op to a loop.
7464   // thisMBB:
7465   //   ...
7466   //   movw varEnd, # --> with thumb2
7467   //   movt varEnd, #
7468   //   ldrcp varEnd, idx --> without thumb2
7469   //   fallthrough --> loopMBB
7470   // loopMBB:
7471   //   PHI varPhi, varEnd, varLoop
7472   //   PHI srcPhi, src, srcLoop
7473   //   PHI destPhi, dst, destLoop
7474   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7475   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7476   //   subs varLoop, varPhi, #UnitSize
7477   //   bne loopMBB
7478   //   fallthrough --> exitMBB
7479   // exitMBB:
7480   //   epilogue to handle left-over bytes
7481   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7482   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7483   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7484   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7485   MF->insert(It, loopMBB);
7486   MF->insert(It, exitMBB);
7487
7488   // Transfer the remainder of BB and its successor edges to exitMBB.
7489   exitMBB->splice(exitMBB->begin(), BB,
7490                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7491   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7492
7493   // Load an immediate to varEnd.
7494   unsigned varEnd = MRI.createVirtualRegister(TRC);
7495   if (IsThumb2) {
7496     unsigned Vtmp = varEnd;
7497     if ((LoopSize & 0xFFFF0000) != 0)
7498       Vtmp = MRI.createVirtualRegister(TRC);
7499     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7500                        .addImm(LoopSize & 0xFFFF));
7501
7502     if ((LoopSize & 0xFFFF0000) != 0)
7503       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7504                          .addReg(Vtmp).addImm(LoopSize >> 16));
7505   } else {
7506     MachineConstantPool *ConstantPool = MF->getConstantPool();
7507     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7508     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7509
7510     // MachineConstantPool wants an explicit alignment.
7511     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7512     if (Align == 0)
7513       Align = getDataLayout()->getTypeAllocSize(C->getType());
7514     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7515
7516     if (IsThumb1)
7517       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7518           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7519     else
7520       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7521           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7522   }
7523   BB->addSuccessor(loopMBB);
7524
7525   // Generate the loop body:
7526   //   varPhi = PHI(varLoop, varEnd)
7527   //   srcPhi = PHI(srcLoop, src)
7528   //   destPhi = PHI(destLoop, dst)
7529   MachineBasicBlock *entryBB = BB;
7530   BB = loopMBB;
7531   unsigned varLoop = MRI.createVirtualRegister(TRC);
7532   unsigned varPhi = MRI.createVirtualRegister(TRC);
7533   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7534   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7535   unsigned destLoop = MRI.createVirtualRegister(TRC);
7536   unsigned destPhi = MRI.createVirtualRegister(TRC);
7537
7538   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7539     .addReg(varLoop).addMBB(loopMBB)
7540     .addReg(varEnd).addMBB(entryBB);
7541   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7542     .addReg(srcLoop).addMBB(loopMBB)
7543     .addReg(src).addMBB(entryBB);
7544   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7545     .addReg(destLoop).addMBB(loopMBB)
7546     .addReg(dest).addMBB(entryBB);
7547
7548   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7549   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7550   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7551   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7552              IsThumb1, IsThumb2);
7553   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7554              IsThumb1, IsThumb2);
7555
7556   // Decrement loop variable by UnitSize.
7557   if (IsThumb1) {
7558     MachineInstrBuilder MIB =
7559         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7560     MIB = AddDefaultT1CC(MIB);
7561     MIB.addReg(varPhi).addImm(UnitSize);
7562     AddDefaultPred(MIB);
7563   } else {
7564     MachineInstrBuilder MIB =
7565         BuildMI(*BB, BB->end(), dl,
7566                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7567     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7568     MIB->getOperand(5).setReg(ARM::CPSR);
7569     MIB->getOperand(5).setIsDef(true);
7570   }
7571   BuildMI(*BB, BB->end(), dl,
7572           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7573       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7574
7575   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7576   BB->addSuccessor(loopMBB);
7577   BB->addSuccessor(exitMBB);
7578
7579   // Add epilogue to handle BytesLeft.
7580   BB = exitMBB;
7581   MachineInstr *StartOfExit = exitMBB->begin();
7582
7583   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7584   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7585   unsigned srcIn = srcLoop;
7586   unsigned destIn = destLoop;
7587   for (unsigned i = 0; i < BytesLeft; i++) {
7588     unsigned srcOut = MRI.createVirtualRegister(TRC);
7589     unsigned destOut = MRI.createVirtualRegister(TRC);
7590     unsigned scratch = MRI.createVirtualRegister(TRC);
7591     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7592                IsThumb1, IsThumb2);
7593     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7594                IsThumb1, IsThumb2);
7595     srcIn = srcOut;
7596     destIn = destOut;
7597   }
7598
7599   MI->eraseFromParent();   // The instruction is gone now.
7600   return BB;
7601 }
7602
7603 MachineBasicBlock *
7604 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7605                                                MachineBasicBlock *BB) const {
7606   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7607   DebugLoc dl = MI->getDebugLoc();
7608   bool isThumb2 = Subtarget->isThumb2();
7609   switch (MI->getOpcode()) {
7610   default: {
7611     MI->dump();
7612     llvm_unreachable("Unexpected instr type to insert");
7613   }
7614   // The Thumb2 pre-indexed stores have the same MI operands, they just
7615   // define them differently in the .td files from the isel patterns, so
7616   // they need pseudos.
7617   case ARM::t2STR_preidx:
7618     MI->setDesc(TII->get(ARM::t2STR_PRE));
7619     return BB;
7620   case ARM::t2STRB_preidx:
7621     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7622     return BB;
7623   case ARM::t2STRH_preidx:
7624     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7625     return BB;
7626
7627   case ARM::STRi_preidx:
7628   case ARM::STRBi_preidx: {
7629     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7630       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7631     // Decode the offset.
7632     unsigned Offset = MI->getOperand(4).getImm();
7633     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7634     Offset = ARM_AM::getAM2Offset(Offset);
7635     if (isSub)
7636       Offset = -Offset;
7637
7638     MachineMemOperand *MMO = *MI->memoperands_begin();
7639     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7640       .addOperand(MI->getOperand(0))  // Rn_wb
7641       .addOperand(MI->getOperand(1))  // Rt
7642       .addOperand(MI->getOperand(2))  // Rn
7643       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7644       .addOperand(MI->getOperand(5))  // pred
7645       .addOperand(MI->getOperand(6))
7646       .addMemOperand(MMO);
7647     MI->eraseFromParent();
7648     return BB;
7649   }
7650   case ARM::STRr_preidx:
7651   case ARM::STRBr_preidx:
7652   case ARM::STRH_preidx: {
7653     unsigned NewOpc;
7654     switch (MI->getOpcode()) {
7655     default: llvm_unreachable("unexpected opcode!");
7656     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7657     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7658     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7659     }
7660     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7661     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7662       MIB.addOperand(MI->getOperand(i));
7663     MI->eraseFromParent();
7664     return BB;
7665   }
7666   case ARM::ATOMIC_LOAD_ADD_I8:
7667      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7668   case ARM::ATOMIC_LOAD_ADD_I16:
7669      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7670   case ARM::ATOMIC_LOAD_ADD_I32:
7671      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7672
7673   case ARM::ATOMIC_LOAD_AND_I8:
7674      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7675   case ARM::ATOMIC_LOAD_AND_I16:
7676      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7677   case ARM::ATOMIC_LOAD_AND_I32:
7678      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7679
7680   case ARM::ATOMIC_LOAD_OR_I8:
7681      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7682   case ARM::ATOMIC_LOAD_OR_I16:
7683      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7684   case ARM::ATOMIC_LOAD_OR_I32:
7685      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7686
7687   case ARM::ATOMIC_LOAD_XOR_I8:
7688      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7689   case ARM::ATOMIC_LOAD_XOR_I16:
7690      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7691   case ARM::ATOMIC_LOAD_XOR_I32:
7692      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7693
7694   case ARM::ATOMIC_LOAD_NAND_I8:
7695      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7696   case ARM::ATOMIC_LOAD_NAND_I16:
7697      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7698   case ARM::ATOMIC_LOAD_NAND_I32:
7699      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7700
7701   case ARM::ATOMIC_LOAD_SUB_I8:
7702      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7703   case ARM::ATOMIC_LOAD_SUB_I16:
7704      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7705   case ARM::ATOMIC_LOAD_SUB_I32:
7706      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7707
7708   case ARM::ATOMIC_LOAD_MIN_I8:
7709      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7710   case ARM::ATOMIC_LOAD_MIN_I16:
7711      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7712   case ARM::ATOMIC_LOAD_MIN_I32:
7713      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7714
7715   case ARM::ATOMIC_LOAD_MAX_I8:
7716      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7717   case ARM::ATOMIC_LOAD_MAX_I16:
7718      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7719   case ARM::ATOMIC_LOAD_MAX_I32:
7720      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7721
7722   case ARM::ATOMIC_LOAD_UMIN_I8:
7723      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7724   case ARM::ATOMIC_LOAD_UMIN_I16:
7725      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7726   case ARM::ATOMIC_LOAD_UMIN_I32:
7727      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7728
7729   case ARM::ATOMIC_LOAD_UMAX_I8:
7730      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7731   case ARM::ATOMIC_LOAD_UMAX_I16:
7732      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7733   case ARM::ATOMIC_LOAD_UMAX_I32:
7734      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7735
7736   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
7737   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7738   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7739
7740   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
7741   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7742   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7743
7744   case ARM::ATOMIC_LOAD_I64:
7745     return EmitAtomicLoad64(MI, BB);
7746
7747   case ARM::ATOMIC_LOAD_ADD_I64:
7748     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7749                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7750                               /*NeedsCarry*/ true);
7751   case ARM::ATOMIC_LOAD_SUB_I64:
7752     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7753                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7754                               /*NeedsCarry*/ true);
7755   case ARM::ATOMIC_LOAD_OR_I64:
7756     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7757                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7758   case ARM::ATOMIC_LOAD_XOR_I64:
7759     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7760                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7761   case ARM::ATOMIC_LOAD_AND_I64:
7762     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7763                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7764   case ARM::ATOMIC_STORE_I64:
7765   case ARM::ATOMIC_SWAP_I64:
7766     return EmitAtomicBinary64(MI, BB, 0, 0, false);
7767   case ARM::ATOMIC_CMP_SWAP_I64:
7768     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7769                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7770                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7771   case ARM::ATOMIC_LOAD_MIN_I64:
7772     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7773                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7774                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7775                               /*IsMinMax*/ true, ARMCC::LT);
7776   case ARM::ATOMIC_LOAD_MAX_I64:
7777     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7778                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7779                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7780                               /*IsMinMax*/ true, ARMCC::GE);
7781   case ARM::ATOMIC_LOAD_UMIN_I64:
7782     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7783                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7784                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7785                               /*IsMinMax*/ true, ARMCC::LO);
7786   case ARM::ATOMIC_LOAD_UMAX_I64:
7787     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7788                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7789                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7790                               /*IsMinMax*/ true, ARMCC::HS);
7791
7792   case ARM::tMOVCCr_pseudo: {
7793     // To "insert" a SELECT_CC instruction, we actually have to insert the
7794     // diamond control-flow pattern.  The incoming instruction knows the
7795     // destination vreg to set, the condition code register to branch on, the
7796     // true/false values to select between, and a branch opcode to use.
7797     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7798     MachineFunction::iterator It = BB;
7799     ++It;
7800
7801     //  thisMBB:
7802     //  ...
7803     //   TrueVal = ...
7804     //   cmpTY ccX, r1, r2
7805     //   bCC copy1MBB
7806     //   fallthrough --> copy0MBB
7807     MachineBasicBlock *thisMBB  = BB;
7808     MachineFunction *F = BB->getParent();
7809     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7810     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7811     F->insert(It, copy0MBB);
7812     F->insert(It, sinkMBB);
7813
7814     // Transfer the remainder of BB and its successor edges to sinkMBB.
7815     sinkMBB->splice(sinkMBB->begin(), BB,
7816                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7817     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7818
7819     BB->addSuccessor(copy0MBB);
7820     BB->addSuccessor(sinkMBB);
7821
7822     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7823       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7824
7825     //  copy0MBB:
7826     //   %FalseValue = ...
7827     //   # fallthrough to sinkMBB
7828     BB = copy0MBB;
7829
7830     // Update machine-CFG edges
7831     BB->addSuccessor(sinkMBB);
7832
7833     //  sinkMBB:
7834     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7835     //  ...
7836     BB = sinkMBB;
7837     BuildMI(*BB, BB->begin(), dl,
7838             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7839       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7840       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7841
7842     MI->eraseFromParent();   // The pseudo instruction is gone now.
7843     return BB;
7844   }
7845
7846   case ARM::BCCi64:
7847   case ARM::BCCZi64: {
7848     // If there is an unconditional branch to the other successor, remove it.
7849     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7850
7851     // Compare both parts that make up the double comparison separately for
7852     // equality.
7853     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7854
7855     unsigned LHS1 = MI->getOperand(1).getReg();
7856     unsigned LHS2 = MI->getOperand(2).getReg();
7857     if (RHSisZero) {
7858       AddDefaultPred(BuildMI(BB, dl,
7859                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7860                      .addReg(LHS1).addImm(0));
7861       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7862         .addReg(LHS2).addImm(0)
7863         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7864     } else {
7865       unsigned RHS1 = MI->getOperand(3).getReg();
7866       unsigned RHS2 = MI->getOperand(4).getReg();
7867       AddDefaultPred(BuildMI(BB, dl,
7868                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7869                      .addReg(LHS1).addReg(RHS1));
7870       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7871         .addReg(LHS2).addReg(RHS2)
7872         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7873     }
7874
7875     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7876     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7877     if (MI->getOperand(0).getImm() == ARMCC::NE)
7878       std::swap(destMBB, exitMBB);
7879
7880     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7881       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7882     if (isThumb2)
7883       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7884     else
7885       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7886
7887     MI->eraseFromParent();   // The pseudo instruction is gone now.
7888     return BB;
7889   }
7890
7891   case ARM::Int_eh_sjlj_setjmp:
7892   case ARM::Int_eh_sjlj_setjmp_nofp:
7893   case ARM::tInt_eh_sjlj_setjmp:
7894   case ARM::t2Int_eh_sjlj_setjmp:
7895   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7896     EmitSjLjDispatchBlock(MI, BB);
7897     return BB;
7898
7899   case ARM::ABS:
7900   case ARM::t2ABS: {
7901     // To insert an ABS instruction, we have to insert the
7902     // diamond control-flow pattern.  The incoming instruction knows the
7903     // source vreg to test against 0, the destination vreg to set,
7904     // the condition code register to branch on, the
7905     // true/false values to select between, and a branch opcode to use.
7906     // It transforms
7907     //     V1 = ABS V0
7908     // into
7909     //     V2 = MOVS V0
7910     //     BCC                      (branch to SinkBB if V0 >= 0)
7911     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7912     //     SinkBB: V1 = PHI(V2, V3)
7913     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7914     MachineFunction::iterator BBI = BB;
7915     ++BBI;
7916     MachineFunction *Fn = BB->getParent();
7917     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7918     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7919     Fn->insert(BBI, RSBBB);
7920     Fn->insert(BBI, SinkBB);
7921
7922     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7923     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7924     bool isThumb2 = Subtarget->isThumb2();
7925     MachineRegisterInfo &MRI = Fn->getRegInfo();
7926     // In Thumb mode S must not be specified if source register is the SP or
7927     // PC and if destination register is the SP, so restrict register class
7928     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7929       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7930       (const TargetRegisterClass*)&ARM::GPRRegClass);
7931
7932     // Transfer the remainder of BB and its successor edges to sinkMBB.
7933     SinkBB->splice(SinkBB->begin(), BB,
7934                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7935     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7936
7937     BB->addSuccessor(RSBBB);
7938     BB->addSuccessor(SinkBB);
7939
7940     // fall through to SinkMBB
7941     RSBBB->addSuccessor(SinkBB);
7942
7943     // insert a cmp at the end of BB
7944     AddDefaultPred(BuildMI(BB, dl,
7945                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7946                    .addReg(ABSSrcReg).addImm(0));
7947
7948     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7949     BuildMI(BB, dl,
7950       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7951       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7952
7953     // insert rsbri in RSBBB
7954     // Note: BCC and rsbri will be converted into predicated rsbmi
7955     // by if-conversion pass
7956     BuildMI(*RSBBB, RSBBB->begin(), dl,
7957       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7958       .addReg(ABSSrcReg, RegState::Kill)
7959       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7960
7961     // insert PHI in SinkBB,
7962     // reuse ABSDstReg to not change uses of ABS instruction
7963     BuildMI(*SinkBB, SinkBB->begin(), dl,
7964       TII->get(ARM::PHI), ABSDstReg)
7965       .addReg(NewRsbDstReg).addMBB(RSBBB)
7966       .addReg(ABSSrcReg).addMBB(BB);
7967
7968     // remove ABS instruction
7969     MI->eraseFromParent();
7970
7971     // return last added BB
7972     return SinkBB;
7973   }
7974   case ARM::COPY_STRUCT_BYVAL_I32:
7975     ++NumLoopByVals;
7976     return EmitStructByval(MI, BB);
7977   }
7978 }
7979
7980 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7981                                                       SDNode *Node) const {
7982   if (!MI->hasPostISelHook()) {
7983     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7984            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7985     return;
7986   }
7987
7988   const MCInstrDesc *MCID = &MI->getDesc();
7989   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7990   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7991   // operand is still set to noreg. If needed, set the optional operand's
7992   // register to CPSR, and remove the redundant implicit def.
7993   //
7994   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7995
7996   // Rename pseudo opcodes.
7997   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7998   if (NewOpc) {
7999     const ARMBaseInstrInfo *TII =
8000       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
8001     MCID = &TII->get(NewOpc);
8002
8003     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
8004            "converted opcode should be the same except for cc_out");
8005
8006     MI->setDesc(*MCID);
8007
8008     // Add the optional cc_out operand
8009     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
8010   }
8011   unsigned ccOutIdx = MCID->getNumOperands() - 1;
8012
8013   // Any ARM instruction that sets the 's' bit should specify an optional
8014   // "cc_out" operand in the last operand position.
8015   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
8016     assert(!NewOpc && "Optional cc_out operand required");
8017     return;
8018   }
8019   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8020   // since we already have an optional CPSR def.
8021   bool definesCPSR = false;
8022   bool deadCPSR = false;
8023   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
8024        i != e; ++i) {
8025     const MachineOperand &MO = MI->getOperand(i);
8026     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8027       definesCPSR = true;
8028       if (MO.isDead())
8029         deadCPSR = true;
8030       MI->RemoveOperand(i);
8031       break;
8032     }
8033   }
8034   if (!definesCPSR) {
8035     assert(!NewOpc && "Optional cc_out operand required");
8036     return;
8037   }
8038   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8039   if (deadCPSR) {
8040     assert(!MI->getOperand(ccOutIdx).getReg() &&
8041            "expect uninitialized optional cc_out operand");
8042     return;
8043   }
8044
8045   // If this instruction was defined with an optional CPSR def and its dag node
8046   // had a live implicit CPSR def, then activate the optional CPSR def.
8047   MachineOperand &MO = MI->getOperand(ccOutIdx);
8048   MO.setReg(ARM::CPSR);
8049   MO.setIsDef(true);
8050 }
8051
8052 //===----------------------------------------------------------------------===//
8053 //                           ARM Optimization Hooks
8054 //===----------------------------------------------------------------------===//
8055
8056 // Helper function that checks if N is a null or all ones constant.
8057 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8058   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8059   if (!C)
8060     return false;
8061   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8062 }
8063
8064 // Return true if N is conditionally 0 or all ones.
8065 // Detects these expressions where cc is an i1 value:
8066 //
8067 //   (select cc 0, y)   [AllOnes=0]
8068 //   (select cc y, 0)   [AllOnes=0]
8069 //   (zext cc)          [AllOnes=0]
8070 //   (sext cc)          [AllOnes=0/1]
8071 //   (select cc -1, y)  [AllOnes=1]
8072 //   (select cc y, -1)  [AllOnes=1]
8073 //
8074 // Invert is set when N is the null/all ones constant when CC is false.
8075 // OtherOp is set to the alternative value of N.
8076 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8077                                        SDValue &CC, bool &Invert,
8078                                        SDValue &OtherOp,
8079                                        SelectionDAG &DAG) {
8080   switch (N->getOpcode()) {
8081   default: return false;
8082   case ISD::SELECT: {
8083     CC = N->getOperand(0);
8084     SDValue N1 = N->getOperand(1);
8085     SDValue N2 = N->getOperand(2);
8086     if (isZeroOrAllOnes(N1, AllOnes)) {
8087       Invert = false;
8088       OtherOp = N2;
8089       return true;
8090     }
8091     if (isZeroOrAllOnes(N2, AllOnes)) {
8092       Invert = true;
8093       OtherOp = N1;
8094       return true;
8095     }
8096     return false;
8097   }
8098   case ISD::ZERO_EXTEND:
8099     // (zext cc) can never be the all ones value.
8100     if (AllOnes)
8101       return false;
8102     // Fall through.
8103   case ISD::SIGN_EXTEND: {
8104     EVT VT = N->getValueType(0);
8105     CC = N->getOperand(0);
8106     if (CC.getValueType() != MVT::i1)
8107       return false;
8108     Invert = !AllOnes;
8109     if (AllOnes)
8110       // When looking for an AllOnes constant, N is an sext, and the 'other'
8111       // value is 0.
8112       OtherOp = DAG.getConstant(0, VT);
8113     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8114       // When looking for a 0 constant, N can be zext or sext.
8115       OtherOp = DAG.getConstant(1, VT);
8116     else
8117       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
8118     return true;
8119   }
8120   }
8121 }
8122
8123 // Combine a constant select operand into its use:
8124 //
8125 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
8126 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
8127 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
8128 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
8129 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
8130 //
8131 // The transform is rejected if the select doesn't have a constant operand that
8132 // is null, or all ones when AllOnes is set.
8133 //
8134 // Also recognize sext/zext from i1:
8135 //
8136 //   (add (zext cc), x) -> (select cc (add x, 1), x)
8137 //   (add (sext cc), x) -> (select cc (add x, -1), x)
8138 //
8139 // These transformations eventually create predicated instructions.
8140 //
8141 // @param N       The node to transform.
8142 // @param Slct    The N operand that is a select.
8143 // @param OtherOp The other N operand (x above).
8144 // @param DCI     Context.
8145 // @param AllOnes Require the select constant to be all ones instead of null.
8146 // @returns The new node, or SDValue() on failure.
8147 static
8148 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8149                             TargetLowering::DAGCombinerInfo &DCI,
8150                             bool AllOnes = false) {
8151   SelectionDAG &DAG = DCI.DAG;
8152   EVT VT = N->getValueType(0);
8153   SDValue NonConstantVal;
8154   SDValue CCOp;
8155   bool SwapSelectOps;
8156   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8157                                   NonConstantVal, DAG))
8158     return SDValue();
8159
8160   // Slct is now know to be the desired identity constant when CC is true.
8161   SDValue TrueVal = OtherOp;
8162   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8163                                  OtherOp, NonConstantVal);
8164   // Unless SwapSelectOps says CC should be false.
8165   if (SwapSelectOps)
8166     std::swap(TrueVal, FalseVal);
8167
8168   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8169                      CCOp, TrueVal, FalseVal);
8170 }
8171
8172 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8173 static
8174 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8175                                        TargetLowering::DAGCombinerInfo &DCI) {
8176   SDValue N0 = N->getOperand(0);
8177   SDValue N1 = N->getOperand(1);
8178   if (N0.getNode()->hasOneUse()) {
8179     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8180     if (Result.getNode())
8181       return Result;
8182   }
8183   if (N1.getNode()->hasOneUse()) {
8184     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8185     if (Result.getNode())
8186       return Result;
8187   }
8188   return SDValue();
8189 }
8190
8191 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8192 // (only after legalization).
8193 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8194                                  TargetLowering::DAGCombinerInfo &DCI,
8195                                  const ARMSubtarget *Subtarget) {
8196
8197   // Only perform optimization if after legalize, and if NEON is available. We
8198   // also expected both operands to be BUILD_VECTORs.
8199   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8200       || N0.getOpcode() != ISD::BUILD_VECTOR
8201       || N1.getOpcode() != ISD::BUILD_VECTOR)
8202     return SDValue();
8203
8204   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8205   EVT VT = N->getValueType(0);
8206   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8207     return SDValue();
8208
8209   // Check that the vector operands are of the right form.
8210   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8211   // operands, where N is the size of the formed vector.
8212   // Each EXTRACT_VECTOR should have the same input vector and odd or even
8213   // index such that we have a pair wise add pattern.
8214
8215   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8216   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8217     return SDValue();
8218   SDValue Vec = N0->getOperand(0)->getOperand(0);
8219   SDNode *V = Vec.getNode();
8220   unsigned nextIndex = 0;
8221
8222   // For each operands to the ADD which are BUILD_VECTORs,
8223   // check to see if each of their operands are an EXTRACT_VECTOR with
8224   // the same vector and appropriate index.
8225   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8226     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8227         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8228
8229       SDValue ExtVec0 = N0->getOperand(i);
8230       SDValue ExtVec1 = N1->getOperand(i);
8231
8232       // First operand is the vector, verify its the same.
8233       if (V != ExtVec0->getOperand(0).getNode() ||
8234           V != ExtVec1->getOperand(0).getNode())
8235         return SDValue();
8236
8237       // Second is the constant, verify its correct.
8238       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8239       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8240
8241       // For the constant, we want to see all the even or all the odd.
8242       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8243           || C1->getZExtValue() != nextIndex+1)
8244         return SDValue();
8245
8246       // Increment index.
8247       nextIndex+=2;
8248     } else
8249       return SDValue();
8250   }
8251
8252   // Create VPADDL node.
8253   SelectionDAG &DAG = DCI.DAG;
8254   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8255
8256   // Build operand list.
8257   SmallVector<SDValue, 8> Ops;
8258   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
8259                                 TLI.getPointerTy()));
8260
8261   // Input is the vector.
8262   Ops.push_back(Vec);
8263
8264   // Get widened type and narrowed type.
8265   MVT widenType;
8266   unsigned numElem = VT.getVectorNumElements();
8267   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8268     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8269     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8270     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8271     default:
8272       llvm_unreachable("Invalid vector element type for padd optimization.");
8273   }
8274
8275   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
8276                             widenType, &Ops[0], Ops.size());
8277   return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, tmp);
8278 }
8279
8280 static SDValue findMUL_LOHI(SDValue V) {
8281   if (V->getOpcode() == ISD::UMUL_LOHI ||
8282       V->getOpcode() == ISD::SMUL_LOHI)
8283     return V;
8284   return SDValue();
8285 }
8286
8287 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8288                                      TargetLowering::DAGCombinerInfo &DCI,
8289                                      const ARMSubtarget *Subtarget) {
8290
8291   if (Subtarget->isThumb1Only()) return SDValue();
8292
8293   // Only perform the checks after legalize when the pattern is available.
8294   if (DCI.isBeforeLegalize()) return SDValue();
8295
8296   // Look for multiply add opportunities.
8297   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8298   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8299   // a glue link from the first add to the second add.
8300   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8301   // a S/UMLAL instruction.
8302   //          loAdd   UMUL_LOHI
8303   //            \    / :lo    \ :hi
8304   //             \  /          \          [no multiline comment]
8305   //              ADDC         |  hiAdd
8306   //                 \ :glue  /  /
8307   //                  \      /  /
8308   //                    ADDE
8309   //
8310   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8311   SDValue AddcOp0 = AddcNode->getOperand(0);
8312   SDValue AddcOp1 = AddcNode->getOperand(1);
8313
8314   // Check if the two operands are from the same mul_lohi node.
8315   if (AddcOp0.getNode() == AddcOp1.getNode())
8316     return SDValue();
8317
8318   assert(AddcNode->getNumValues() == 2 &&
8319          AddcNode->getValueType(0) == MVT::i32 &&
8320          "Expect ADDC with two result values. First: i32");
8321
8322   // Check that we have a glued ADDC node.
8323   if (AddcNode->getValueType(1) != MVT::Glue)
8324     return SDValue();
8325
8326   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8327   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8328       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8329       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8330       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8331     return SDValue();
8332
8333   // Look for the glued ADDE.
8334   SDNode* AddeNode = AddcNode->getGluedUser();
8335   if (AddeNode == NULL)
8336     return SDValue();
8337
8338   // Make sure it is really an ADDE.
8339   if (AddeNode->getOpcode() != ISD::ADDE)
8340     return SDValue();
8341
8342   assert(AddeNode->getNumOperands() == 3 &&
8343          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8344          "ADDE node has the wrong inputs");
8345
8346   // Check for the triangle shape.
8347   SDValue AddeOp0 = AddeNode->getOperand(0);
8348   SDValue AddeOp1 = AddeNode->getOperand(1);
8349
8350   // Make sure that the ADDE operands are not coming from the same node.
8351   if (AddeOp0.getNode() == AddeOp1.getNode())
8352     return SDValue();
8353
8354   // Find the MUL_LOHI node walking up ADDE's operands.
8355   bool IsLeftOperandMUL = false;
8356   SDValue MULOp = findMUL_LOHI(AddeOp0);
8357   if (MULOp == SDValue())
8358    MULOp = findMUL_LOHI(AddeOp1);
8359   else
8360     IsLeftOperandMUL = true;
8361   if (MULOp == SDValue())
8362      return SDValue();
8363
8364   // Figure out the right opcode.
8365   unsigned Opc = MULOp->getOpcode();
8366   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8367
8368   // Figure out the high and low input values to the MLAL node.
8369   SDValue* HiMul = &MULOp;
8370   SDValue* HiAdd = NULL;
8371   SDValue* LoMul = NULL;
8372   SDValue* LowAdd = NULL;
8373
8374   if (IsLeftOperandMUL)
8375     HiAdd = &AddeOp1;
8376   else
8377     HiAdd = &AddeOp0;
8378
8379
8380   if (AddcOp0->getOpcode() == Opc) {
8381     LoMul = &AddcOp0;
8382     LowAdd = &AddcOp1;
8383   }
8384   if (AddcOp1->getOpcode() == Opc) {
8385     LoMul = &AddcOp1;
8386     LowAdd = &AddcOp0;
8387   }
8388
8389   if (LoMul == NULL)
8390     return SDValue();
8391
8392   if (LoMul->getNode() != HiMul->getNode())
8393     return SDValue();
8394
8395   // Create the merged node.
8396   SelectionDAG &DAG = DCI.DAG;
8397
8398   // Build operand list.
8399   SmallVector<SDValue, 8> Ops;
8400   Ops.push_back(LoMul->getOperand(0));
8401   Ops.push_back(LoMul->getOperand(1));
8402   Ops.push_back(*LowAdd);
8403   Ops.push_back(*HiAdd);
8404
8405   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8406                                  DAG.getVTList(MVT::i32, MVT::i32),
8407                                  &Ops[0], Ops.size());
8408
8409   // Replace the ADDs' nodes uses by the MLA node's values.
8410   SDValue HiMLALResult(MLALNode.getNode(), 1);
8411   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8412
8413   SDValue LoMLALResult(MLALNode.getNode(), 0);
8414   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8415
8416   // Return original node to notify the driver to stop replacing.
8417   SDValue resNode(AddcNode, 0);
8418   return resNode;
8419 }
8420
8421 /// PerformADDCCombine - Target-specific dag combine transform from
8422 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8423 static SDValue PerformADDCCombine(SDNode *N,
8424                                  TargetLowering::DAGCombinerInfo &DCI,
8425                                  const ARMSubtarget *Subtarget) {
8426
8427   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8428
8429 }
8430
8431 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8432 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8433 /// called with the default operands, and if that fails, with commuted
8434 /// operands.
8435 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8436                                           TargetLowering::DAGCombinerInfo &DCI,
8437                                           const ARMSubtarget *Subtarget){
8438
8439   // Attempt to create vpaddl for this add.
8440   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8441   if (Result.getNode())
8442     return Result;
8443
8444   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8445   if (N0.getNode()->hasOneUse()) {
8446     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8447     if (Result.getNode()) return Result;
8448   }
8449   return SDValue();
8450 }
8451
8452 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8453 ///
8454 static SDValue PerformADDCombine(SDNode *N,
8455                                  TargetLowering::DAGCombinerInfo &DCI,
8456                                  const ARMSubtarget *Subtarget) {
8457   SDValue N0 = N->getOperand(0);
8458   SDValue N1 = N->getOperand(1);
8459
8460   // First try with the default operand order.
8461   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8462   if (Result.getNode())
8463     return Result;
8464
8465   // If that didn't work, try again with the operands commuted.
8466   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8467 }
8468
8469 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8470 ///
8471 static SDValue PerformSUBCombine(SDNode *N,
8472                                  TargetLowering::DAGCombinerInfo &DCI) {
8473   SDValue N0 = N->getOperand(0);
8474   SDValue N1 = N->getOperand(1);
8475
8476   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8477   if (N1.getNode()->hasOneUse()) {
8478     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8479     if (Result.getNode()) return Result;
8480   }
8481
8482   return SDValue();
8483 }
8484
8485 /// PerformVMULCombine
8486 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8487 /// special multiplier accumulator forwarding.
8488 ///   vmul d3, d0, d2
8489 ///   vmla d3, d1, d2
8490 /// is faster than
8491 ///   vadd d3, d0, d1
8492 ///   vmul d3, d3, d2
8493 //  However, for (A + B) * (A + B),
8494 //    vadd d2, d0, d1
8495 //    vmul d3, d0, d2
8496 //    vmla d3, d1, d2
8497 //  is slower than
8498 //    vadd d2, d0, d1
8499 //    vmul d3, d2, d2
8500 static SDValue PerformVMULCombine(SDNode *N,
8501                                   TargetLowering::DAGCombinerInfo &DCI,
8502                                   const ARMSubtarget *Subtarget) {
8503   if (!Subtarget->hasVMLxForwarding())
8504     return SDValue();
8505
8506   SelectionDAG &DAG = DCI.DAG;
8507   SDValue N0 = N->getOperand(0);
8508   SDValue N1 = N->getOperand(1);
8509   unsigned Opcode = N0.getOpcode();
8510   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8511       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8512     Opcode = N1.getOpcode();
8513     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8514         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8515       return SDValue();
8516     std::swap(N0, N1);
8517   }
8518
8519   if (N0 == N1)
8520     return SDValue();
8521
8522   EVT VT = N->getValueType(0);
8523   SDLoc DL(N);
8524   SDValue N00 = N0->getOperand(0);
8525   SDValue N01 = N0->getOperand(1);
8526   return DAG.getNode(Opcode, DL, VT,
8527                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8528                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8529 }
8530
8531 static SDValue PerformMULCombine(SDNode *N,
8532                                  TargetLowering::DAGCombinerInfo &DCI,
8533                                  const ARMSubtarget *Subtarget) {
8534   SelectionDAG &DAG = DCI.DAG;
8535
8536   if (Subtarget->isThumb1Only())
8537     return SDValue();
8538
8539   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8540     return SDValue();
8541
8542   EVT VT = N->getValueType(0);
8543   if (VT.is64BitVector() || VT.is128BitVector())
8544     return PerformVMULCombine(N, DCI, Subtarget);
8545   if (VT != MVT::i32)
8546     return SDValue();
8547
8548   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8549   if (!C)
8550     return SDValue();
8551
8552   int64_t MulAmt = C->getSExtValue();
8553   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8554
8555   ShiftAmt = ShiftAmt & (32 - 1);
8556   SDValue V = N->getOperand(0);
8557   SDLoc DL(N);
8558
8559   SDValue Res;
8560   MulAmt >>= ShiftAmt;
8561
8562   if (MulAmt >= 0) {
8563     if (isPowerOf2_32(MulAmt - 1)) {
8564       // (mul x, 2^N + 1) => (add (shl x, N), x)
8565       Res = DAG.getNode(ISD::ADD, DL, VT,
8566                         V,
8567                         DAG.getNode(ISD::SHL, DL, VT,
8568                                     V,
8569                                     DAG.getConstant(Log2_32(MulAmt - 1),
8570                                                     MVT::i32)));
8571     } else if (isPowerOf2_32(MulAmt + 1)) {
8572       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8573       Res = DAG.getNode(ISD::SUB, DL, VT,
8574                         DAG.getNode(ISD::SHL, DL, VT,
8575                                     V,
8576                                     DAG.getConstant(Log2_32(MulAmt + 1),
8577                                                     MVT::i32)),
8578                         V);
8579     } else
8580       return SDValue();
8581   } else {
8582     uint64_t MulAmtAbs = -MulAmt;
8583     if (isPowerOf2_32(MulAmtAbs + 1)) {
8584       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8585       Res = DAG.getNode(ISD::SUB, DL, VT,
8586                         V,
8587                         DAG.getNode(ISD::SHL, DL, VT,
8588                                     V,
8589                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8590                                                     MVT::i32)));
8591     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8592       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8593       Res = DAG.getNode(ISD::ADD, DL, VT,
8594                         V,
8595                         DAG.getNode(ISD::SHL, DL, VT,
8596                                     V,
8597                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8598                                                     MVT::i32)));
8599       Res = DAG.getNode(ISD::SUB, DL, VT,
8600                         DAG.getConstant(0, MVT::i32),Res);
8601
8602     } else
8603       return SDValue();
8604   }
8605
8606   if (ShiftAmt != 0)
8607     Res = DAG.getNode(ISD::SHL, DL, VT,
8608                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8609
8610   // Do not add new nodes to DAG combiner worklist.
8611   DCI.CombineTo(N, Res, false);
8612   return SDValue();
8613 }
8614
8615 static SDValue PerformANDCombine(SDNode *N,
8616                                  TargetLowering::DAGCombinerInfo &DCI,
8617                                  const ARMSubtarget *Subtarget) {
8618
8619   // Attempt to use immediate-form VBIC
8620   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8621   SDLoc dl(N);
8622   EVT VT = N->getValueType(0);
8623   SelectionDAG &DAG = DCI.DAG;
8624
8625   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8626     return SDValue();
8627
8628   APInt SplatBits, SplatUndef;
8629   unsigned SplatBitSize;
8630   bool HasAnyUndefs;
8631   if (BVN &&
8632       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8633     if (SplatBitSize <= 64) {
8634       EVT VbicVT;
8635       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8636                                       SplatUndef.getZExtValue(), SplatBitSize,
8637                                       DAG, VbicVT, VT.is128BitVector(),
8638                                       OtherModImm);
8639       if (Val.getNode()) {
8640         SDValue Input =
8641           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8642         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8643         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8644       }
8645     }
8646   }
8647
8648   if (!Subtarget->isThumb1Only()) {
8649     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8650     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8651     if (Result.getNode())
8652       return Result;
8653   }
8654
8655   return SDValue();
8656 }
8657
8658 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8659 static SDValue PerformORCombine(SDNode *N,
8660                                 TargetLowering::DAGCombinerInfo &DCI,
8661                                 const ARMSubtarget *Subtarget) {
8662   // Attempt to use immediate-form VORR
8663   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8664   SDLoc dl(N);
8665   EVT VT = N->getValueType(0);
8666   SelectionDAG &DAG = DCI.DAG;
8667
8668   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8669     return SDValue();
8670
8671   APInt SplatBits, SplatUndef;
8672   unsigned SplatBitSize;
8673   bool HasAnyUndefs;
8674   if (BVN && Subtarget->hasNEON() &&
8675       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8676     if (SplatBitSize <= 64) {
8677       EVT VorrVT;
8678       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8679                                       SplatUndef.getZExtValue(), SplatBitSize,
8680                                       DAG, VorrVT, VT.is128BitVector(),
8681                                       OtherModImm);
8682       if (Val.getNode()) {
8683         SDValue Input =
8684           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8685         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8686         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8687       }
8688     }
8689   }
8690
8691   if (!Subtarget->isThumb1Only()) {
8692     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8693     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8694     if (Result.getNode())
8695       return Result;
8696   }
8697
8698   // The code below optimizes (or (and X, Y), Z).
8699   // The AND operand needs to have a single user to make these optimizations
8700   // profitable.
8701   SDValue N0 = N->getOperand(0);
8702   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8703     return SDValue();
8704   SDValue N1 = N->getOperand(1);
8705
8706   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8707   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8708       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8709     APInt SplatUndef;
8710     unsigned SplatBitSize;
8711     bool HasAnyUndefs;
8712
8713     APInt SplatBits0, SplatBits1;
8714     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8715     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8716     // Ensure that the second operand of both ands are constants
8717     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8718                                       HasAnyUndefs) && !HasAnyUndefs) {
8719         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8720                                           HasAnyUndefs) && !HasAnyUndefs) {
8721             // Ensure that the bit width of the constants are the same and that
8722             // the splat arguments are logical inverses as per the pattern we
8723             // are trying to simplify.
8724             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8725                 SplatBits0 == ~SplatBits1) {
8726                 // Canonicalize the vector type to make instruction selection
8727                 // simpler.
8728                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8729                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8730                                              N0->getOperand(1),
8731                                              N0->getOperand(0),
8732                                              N1->getOperand(0));
8733                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8734             }
8735         }
8736     }
8737   }
8738
8739   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8740   // reasonable.
8741
8742   // BFI is only available on V6T2+
8743   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8744     return SDValue();
8745
8746   SDLoc DL(N);
8747   // 1) or (and A, mask), val => ARMbfi A, val, mask
8748   //      iff (val & mask) == val
8749   //
8750   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8751   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8752   //          && mask == ~mask2
8753   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8754   //          && ~mask == mask2
8755   //  (i.e., copy a bitfield value into another bitfield of the same width)
8756
8757   if (VT != MVT::i32)
8758     return SDValue();
8759
8760   SDValue N00 = N0.getOperand(0);
8761
8762   // The value and the mask need to be constants so we can verify this is
8763   // actually a bitfield set. If the mask is 0xffff, we can do better
8764   // via a movt instruction, so don't use BFI in that case.
8765   SDValue MaskOp = N0.getOperand(1);
8766   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8767   if (!MaskC)
8768     return SDValue();
8769   unsigned Mask = MaskC->getZExtValue();
8770   if (Mask == 0xffff)
8771     return SDValue();
8772   SDValue Res;
8773   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8774   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8775   if (N1C) {
8776     unsigned Val = N1C->getZExtValue();
8777     if ((Val & ~Mask) != Val)
8778       return SDValue();
8779
8780     if (ARM::isBitFieldInvertedMask(Mask)) {
8781       Val >>= countTrailingZeros(~Mask);
8782
8783       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8784                         DAG.getConstant(Val, MVT::i32),
8785                         DAG.getConstant(Mask, MVT::i32));
8786
8787       // Do not add new nodes to DAG combiner worklist.
8788       DCI.CombineTo(N, Res, false);
8789       return SDValue();
8790     }
8791   } else if (N1.getOpcode() == ISD::AND) {
8792     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8793     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8794     if (!N11C)
8795       return SDValue();
8796     unsigned Mask2 = N11C->getZExtValue();
8797
8798     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8799     // as is to match.
8800     if (ARM::isBitFieldInvertedMask(Mask) &&
8801         (Mask == ~Mask2)) {
8802       // The pack halfword instruction works better for masks that fit it,
8803       // so use that when it's available.
8804       if (Subtarget->hasT2ExtractPack() &&
8805           (Mask == 0xffff || Mask == 0xffff0000))
8806         return SDValue();
8807       // 2a
8808       unsigned amt = countTrailingZeros(Mask2);
8809       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8810                         DAG.getConstant(amt, MVT::i32));
8811       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8812                         DAG.getConstant(Mask, MVT::i32));
8813       // Do not add new nodes to DAG combiner worklist.
8814       DCI.CombineTo(N, Res, false);
8815       return SDValue();
8816     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8817                (~Mask == Mask2)) {
8818       // The pack halfword instruction works better for masks that fit it,
8819       // so use that when it's available.
8820       if (Subtarget->hasT2ExtractPack() &&
8821           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8822         return SDValue();
8823       // 2b
8824       unsigned lsb = countTrailingZeros(Mask);
8825       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8826                         DAG.getConstant(lsb, MVT::i32));
8827       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8828                         DAG.getConstant(Mask2, MVT::i32));
8829       // Do not add new nodes to DAG combiner worklist.
8830       DCI.CombineTo(N, Res, false);
8831       return SDValue();
8832     }
8833   }
8834
8835   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8836       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8837       ARM::isBitFieldInvertedMask(~Mask)) {
8838     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8839     // where lsb(mask) == #shamt and masked bits of B are known zero.
8840     SDValue ShAmt = N00.getOperand(1);
8841     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8842     unsigned LSB = countTrailingZeros(Mask);
8843     if (ShAmtC != LSB)
8844       return SDValue();
8845
8846     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8847                       DAG.getConstant(~Mask, MVT::i32));
8848
8849     // Do not add new nodes to DAG combiner worklist.
8850     DCI.CombineTo(N, Res, false);
8851   }
8852
8853   return SDValue();
8854 }
8855
8856 static SDValue PerformXORCombine(SDNode *N,
8857                                  TargetLowering::DAGCombinerInfo &DCI,
8858                                  const ARMSubtarget *Subtarget) {
8859   EVT VT = N->getValueType(0);
8860   SelectionDAG &DAG = DCI.DAG;
8861
8862   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8863     return SDValue();
8864
8865   if (!Subtarget->isThumb1Only()) {
8866     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8867     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8868     if (Result.getNode())
8869       return Result;
8870   }
8871
8872   return SDValue();
8873 }
8874
8875 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8876 /// the bits being cleared by the AND are not demanded by the BFI.
8877 static SDValue PerformBFICombine(SDNode *N,
8878                                  TargetLowering::DAGCombinerInfo &DCI) {
8879   SDValue N1 = N->getOperand(1);
8880   if (N1.getOpcode() == ISD::AND) {
8881     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8882     if (!N11C)
8883       return SDValue();
8884     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8885     unsigned LSB = countTrailingZeros(~InvMask);
8886     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8887     unsigned Mask = (1 << Width)-1;
8888     unsigned Mask2 = N11C->getZExtValue();
8889     if ((Mask & (~Mask2)) == 0)
8890       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8891                              N->getOperand(0), N1.getOperand(0),
8892                              N->getOperand(2));
8893   }
8894   return SDValue();
8895 }
8896
8897 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8898 /// ARMISD::VMOVRRD.
8899 static SDValue PerformVMOVRRDCombine(SDNode *N,
8900                                      TargetLowering::DAGCombinerInfo &DCI) {
8901   // vmovrrd(vmovdrr x, y) -> x,y
8902   SDValue InDouble = N->getOperand(0);
8903   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8904     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8905
8906   // vmovrrd(load f64) -> (load i32), (load i32)
8907   SDNode *InNode = InDouble.getNode();
8908   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8909       InNode->getValueType(0) == MVT::f64 &&
8910       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8911       !cast<LoadSDNode>(InNode)->isVolatile()) {
8912     // TODO: Should this be done for non-FrameIndex operands?
8913     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8914
8915     SelectionDAG &DAG = DCI.DAG;
8916     SDLoc DL(LD);
8917     SDValue BasePtr = LD->getBasePtr();
8918     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8919                                  LD->getPointerInfo(), LD->isVolatile(),
8920                                  LD->isNonTemporal(), LD->isInvariant(),
8921                                  LD->getAlignment());
8922
8923     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8924                                     DAG.getConstant(4, MVT::i32));
8925     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8926                                  LD->getPointerInfo(), LD->isVolatile(),
8927                                  LD->isNonTemporal(), LD->isInvariant(),
8928                                  std::min(4U, LD->getAlignment() / 2));
8929
8930     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8931     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8932     DCI.RemoveFromWorklist(LD);
8933     DAG.DeleteNode(LD);
8934     return Result;
8935   }
8936
8937   return SDValue();
8938 }
8939
8940 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8941 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8942 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8943   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8944   SDValue Op0 = N->getOperand(0);
8945   SDValue Op1 = N->getOperand(1);
8946   if (Op0.getOpcode() == ISD::BITCAST)
8947     Op0 = Op0.getOperand(0);
8948   if (Op1.getOpcode() == ISD::BITCAST)
8949     Op1 = Op1.getOperand(0);
8950   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8951       Op0.getNode() == Op1.getNode() &&
8952       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8953     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8954                        N->getValueType(0), Op0.getOperand(0));
8955   return SDValue();
8956 }
8957
8958 /// PerformSTORECombine - Target-specific dag combine xforms for
8959 /// ISD::STORE.
8960 static SDValue PerformSTORECombine(SDNode *N,
8961                                    TargetLowering::DAGCombinerInfo &DCI) {
8962   StoreSDNode *St = cast<StoreSDNode>(N);
8963   if (St->isVolatile())
8964     return SDValue();
8965
8966   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8967   // pack all of the elements in one place.  Next, store to memory in fewer
8968   // chunks.
8969   SDValue StVal = St->getValue();
8970   EVT VT = StVal.getValueType();
8971   if (St->isTruncatingStore() && VT.isVector()) {
8972     SelectionDAG &DAG = DCI.DAG;
8973     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8974     EVT StVT = St->getMemoryVT();
8975     unsigned NumElems = VT.getVectorNumElements();
8976     assert(StVT != VT && "Cannot truncate to the same type");
8977     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8978     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8979
8980     // From, To sizes and ElemCount must be pow of two
8981     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8982
8983     // We are going to use the original vector elt for storing.
8984     // Accumulated smaller vector elements must be a multiple of the store size.
8985     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8986
8987     unsigned SizeRatio  = FromEltSz / ToEltSz;
8988     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8989
8990     // Create a type on which we perform the shuffle.
8991     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8992                                      NumElems*SizeRatio);
8993     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8994
8995     SDLoc DL(St);
8996     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8997     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8998     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8999
9000     // Can't shuffle using an illegal type.
9001     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9002
9003     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9004                                 DAG.getUNDEF(WideVec.getValueType()),
9005                                 ShuffleVec.data());
9006     // At this point all of the data is stored at the bottom of the
9007     // register. We now need to save it to mem.
9008
9009     // Find the largest store unit
9010     MVT StoreType = MVT::i8;
9011     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
9012          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
9013       MVT Tp = (MVT::SimpleValueType)tp;
9014       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9015         StoreType = Tp;
9016     }
9017     // Didn't find a legal store type.
9018     if (!TLI.isTypeLegal(StoreType))
9019       return SDValue();
9020
9021     // Bitcast the original vector into a vector of store-size units
9022     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9023             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9024     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9025     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9026     SmallVector<SDValue, 8> Chains;
9027     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
9028                                         TLI.getPointerTy());
9029     SDValue BasePtr = St->getBasePtr();
9030
9031     // Perform one or more big stores into memory.
9032     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9033     for (unsigned I = 0; I < E; I++) {
9034       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9035                                    StoreType, ShuffWide,
9036                                    DAG.getIntPtrConstant(I));
9037       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9038                                 St->getPointerInfo(), St->isVolatile(),
9039                                 St->isNonTemporal(), St->getAlignment());
9040       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9041                             Increment);
9042       Chains.push_back(Ch);
9043     }
9044     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
9045                        Chains.size());
9046   }
9047
9048   if (!ISD::isNormalStore(St))
9049     return SDValue();
9050
9051   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9052   // ARM stores of arguments in the same cache line.
9053   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9054       StVal.getNode()->hasOneUse()) {
9055     SelectionDAG  &DAG = DCI.DAG;
9056     SDLoc DL(St);
9057     SDValue BasePtr = St->getBasePtr();
9058     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9059                                   StVal.getNode()->getOperand(0), BasePtr,
9060                                   St->getPointerInfo(), St->isVolatile(),
9061                                   St->isNonTemporal(), St->getAlignment());
9062
9063     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9064                                     DAG.getConstant(4, MVT::i32));
9065     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
9066                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9067                         St->isNonTemporal(),
9068                         std::min(4U, St->getAlignment() / 2));
9069   }
9070
9071   if (StVal.getValueType() != MVT::i64 ||
9072       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9073     return SDValue();
9074
9075   // Bitcast an i64 store extracted from a vector to f64.
9076   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9077   SelectionDAG &DAG = DCI.DAG;
9078   SDLoc dl(StVal);
9079   SDValue IntVec = StVal.getOperand(0);
9080   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9081                                  IntVec.getValueType().getVectorNumElements());
9082   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9083   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9084                                Vec, StVal.getOperand(1));
9085   dl = SDLoc(N);
9086   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9087   // Make the DAGCombiner fold the bitcasts.
9088   DCI.AddToWorklist(Vec.getNode());
9089   DCI.AddToWorklist(ExtElt.getNode());
9090   DCI.AddToWorklist(V.getNode());
9091   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9092                       St->getPointerInfo(), St->isVolatile(),
9093                       St->isNonTemporal(), St->getAlignment(),
9094                       St->getTBAAInfo());
9095 }
9096
9097 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9098 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
9099 /// i64 vector to have f64 elements, since the value can then be loaded
9100 /// directly into a VFP register.
9101 static bool hasNormalLoadOperand(SDNode *N) {
9102   unsigned NumElts = N->getValueType(0).getVectorNumElements();
9103   for (unsigned i = 0; i < NumElts; ++i) {
9104     SDNode *Elt = N->getOperand(i).getNode();
9105     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9106       return true;
9107   }
9108   return false;
9109 }
9110
9111 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9112 /// ISD::BUILD_VECTOR.
9113 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9114                                           TargetLowering::DAGCombinerInfo &DCI){
9115   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9116   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
9117   // into a pair of GPRs, which is fine when the value is used as a scalar,
9118   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9119   SelectionDAG &DAG = DCI.DAG;
9120   if (N->getNumOperands() == 2) {
9121     SDValue RV = PerformVMOVDRRCombine(N, DAG);
9122     if (RV.getNode())
9123       return RV;
9124   }
9125
9126   // Load i64 elements as f64 values so that type legalization does not split
9127   // them up into i32 values.
9128   EVT VT = N->getValueType(0);
9129   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9130     return SDValue();
9131   SDLoc dl(N);
9132   SmallVector<SDValue, 8> Ops;
9133   unsigned NumElts = VT.getVectorNumElements();
9134   for (unsigned i = 0; i < NumElts; ++i) {
9135     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9136     Ops.push_back(V);
9137     // Make the DAGCombiner fold the bitcast.
9138     DCI.AddToWorklist(V.getNode());
9139   }
9140   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9141   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
9142   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9143 }
9144
9145 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9146 static SDValue
9147 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9148   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9149   // At that time, we may have inserted bitcasts from integer to float.
9150   // If these bitcasts have survived DAGCombine, change the lowering of this
9151   // BUILD_VECTOR in something more vector friendly, i.e., that does not
9152   // force to use floating point types.
9153
9154   // Make sure we can change the type of the vector.
9155   // This is possible iff:
9156   // 1. The vector is only used in a bitcast to a integer type. I.e.,
9157   //    1.1. Vector is used only once.
9158   //    1.2. Use is a bit convert to an integer type.
9159   // 2. The size of its operands are 32-bits (64-bits are not legal).
9160   EVT VT = N->getValueType(0);
9161   EVT EltVT = VT.getVectorElementType();
9162
9163   // Check 1.1. and 2.
9164   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9165     return SDValue();
9166
9167   // By construction, the input type must be float.
9168   assert(EltVT == MVT::f32 && "Unexpected type!");
9169
9170   // Check 1.2.
9171   SDNode *Use = *N->use_begin();
9172   if (Use->getOpcode() != ISD::BITCAST ||
9173       Use->getValueType(0).isFloatingPoint())
9174     return SDValue();
9175
9176   // Check profitability.
9177   // Model is, if more than half of the relevant operands are bitcast from
9178   // i32, turn the build_vector into a sequence of insert_vector_elt.
9179   // Relevant operands are everything that is not statically
9180   // (i.e., at compile time) bitcasted.
9181   unsigned NumOfBitCastedElts = 0;
9182   unsigned NumElts = VT.getVectorNumElements();
9183   unsigned NumOfRelevantElts = NumElts;
9184   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9185     SDValue Elt = N->getOperand(Idx);
9186     if (Elt->getOpcode() == ISD::BITCAST) {
9187       // Assume only bit cast to i32 will go away.
9188       if (Elt->getOperand(0).getValueType() == MVT::i32)
9189         ++NumOfBitCastedElts;
9190     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9191       // Constants are statically casted, thus do not count them as
9192       // relevant operands.
9193       --NumOfRelevantElts;
9194   }
9195
9196   // Check if more than half of the elements require a non-free bitcast.
9197   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9198     return SDValue();
9199
9200   SelectionDAG &DAG = DCI.DAG;
9201   // Create the new vector type.
9202   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9203   // Check if the type is legal.
9204   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9205   if (!TLI.isTypeLegal(VecVT))
9206     return SDValue();
9207
9208   // Combine:
9209   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9210   // => BITCAST INSERT_VECTOR_ELT
9211   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9212   //                      (BITCAST EN), N.
9213   SDValue Vec = DAG.getUNDEF(VecVT);
9214   SDLoc dl(N);
9215   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9216     SDValue V = N->getOperand(Idx);
9217     if (V.getOpcode() == ISD::UNDEF)
9218       continue;
9219     if (V.getOpcode() == ISD::BITCAST &&
9220         V->getOperand(0).getValueType() == MVT::i32)
9221       // Fold obvious case.
9222       V = V.getOperand(0);
9223     else {
9224       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 
9225       // Make the DAGCombiner fold the bitcasts.
9226       DCI.AddToWorklist(V.getNode());
9227     }
9228     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
9229     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9230   }
9231   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9232   // Make the DAGCombiner fold the bitcasts.
9233   DCI.AddToWorklist(Vec.getNode());
9234   return Vec;
9235 }
9236
9237 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9238 /// ISD::INSERT_VECTOR_ELT.
9239 static SDValue PerformInsertEltCombine(SDNode *N,
9240                                        TargetLowering::DAGCombinerInfo &DCI) {
9241   // Bitcast an i64 load inserted into a vector to f64.
9242   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9243   EVT VT = N->getValueType(0);
9244   SDNode *Elt = N->getOperand(1).getNode();
9245   if (VT.getVectorElementType() != MVT::i64 ||
9246       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9247     return SDValue();
9248
9249   SelectionDAG &DAG = DCI.DAG;
9250   SDLoc dl(N);
9251   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9252                                  VT.getVectorNumElements());
9253   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9254   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9255   // Make the DAGCombiner fold the bitcasts.
9256   DCI.AddToWorklist(Vec.getNode());
9257   DCI.AddToWorklist(V.getNode());
9258   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9259                                Vec, V, N->getOperand(2));
9260   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9261 }
9262
9263 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9264 /// ISD::VECTOR_SHUFFLE.
9265 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9266   // The LLVM shufflevector instruction does not require the shuffle mask
9267   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9268   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
9269   // operands do not match the mask length, they are extended by concatenating
9270   // them with undef vectors.  That is probably the right thing for other
9271   // targets, but for NEON it is better to concatenate two double-register
9272   // size vector operands into a single quad-register size vector.  Do that
9273   // transformation here:
9274   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
9275   //   shuffle(concat(v1, v2), undef)
9276   SDValue Op0 = N->getOperand(0);
9277   SDValue Op1 = N->getOperand(1);
9278   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9279       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9280       Op0.getNumOperands() != 2 ||
9281       Op1.getNumOperands() != 2)
9282     return SDValue();
9283   SDValue Concat0Op1 = Op0.getOperand(1);
9284   SDValue Concat1Op1 = Op1.getOperand(1);
9285   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9286       Concat1Op1.getOpcode() != ISD::UNDEF)
9287     return SDValue();
9288   // Skip the transformation if any of the types are illegal.
9289   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9290   EVT VT = N->getValueType(0);
9291   if (!TLI.isTypeLegal(VT) ||
9292       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9293       !TLI.isTypeLegal(Concat1Op1.getValueType()))
9294     return SDValue();
9295
9296   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9297                                   Op0.getOperand(0), Op1.getOperand(0));
9298   // Translate the shuffle mask.
9299   SmallVector<int, 16> NewMask;
9300   unsigned NumElts = VT.getVectorNumElements();
9301   unsigned HalfElts = NumElts/2;
9302   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9303   for (unsigned n = 0; n < NumElts; ++n) {
9304     int MaskElt = SVN->getMaskElt(n);
9305     int NewElt = -1;
9306     if (MaskElt < (int)HalfElts)
9307       NewElt = MaskElt;
9308     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9309       NewElt = HalfElts + MaskElt - NumElts;
9310     NewMask.push_back(NewElt);
9311   }
9312   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9313                               DAG.getUNDEF(VT), NewMask.data());
9314 }
9315
9316 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
9317 /// NEON load/store intrinsics to merge base address updates.
9318 static SDValue CombineBaseUpdate(SDNode *N,
9319                                  TargetLowering::DAGCombinerInfo &DCI) {
9320   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9321     return SDValue();
9322
9323   SelectionDAG &DAG = DCI.DAG;
9324   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9325                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9326   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
9327   SDValue Addr = N->getOperand(AddrOpIdx);
9328
9329   // Search for a use of the address operand that is an increment.
9330   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9331          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9332     SDNode *User = *UI;
9333     if (User->getOpcode() != ISD::ADD ||
9334         UI.getUse().getResNo() != Addr.getResNo())
9335       continue;
9336
9337     // Check that the add is independent of the load/store.  Otherwise, folding
9338     // it would create a cycle.
9339     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9340       continue;
9341
9342     // Find the new opcode for the updating load/store.
9343     bool isLoad = true;
9344     bool isLaneOp = false;
9345     unsigned NewOpc = 0;
9346     unsigned NumVecs = 0;
9347     if (isIntrinsic) {
9348       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9349       switch (IntNo) {
9350       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9351       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9352         NumVecs = 1; break;
9353       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9354         NumVecs = 2; break;
9355       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9356         NumVecs = 3; break;
9357       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9358         NumVecs = 4; break;
9359       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9360         NumVecs = 2; isLaneOp = true; break;
9361       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9362         NumVecs = 3; isLaneOp = true; break;
9363       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9364         NumVecs = 4; isLaneOp = true; break;
9365       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9366         NumVecs = 1; isLoad = false; break;
9367       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9368         NumVecs = 2; isLoad = false; break;
9369       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9370         NumVecs = 3; isLoad = false; break;
9371       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9372         NumVecs = 4; isLoad = false; break;
9373       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9374         NumVecs = 2; isLoad = false; isLaneOp = true; break;
9375       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9376         NumVecs = 3; isLoad = false; isLaneOp = true; break;
9377       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9378         NumVecs = 4; isLoad = false; isLaneOp = true; break;
9379       }
9380     } else {
9381       isLaneOp = true;
9382       switch (N->getOpcode()) {
9383       default: llvm_unreachable("unexpected opcode for Neon base update");
9384       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9385       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9386       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9387       }
9388     }
9389
9390     // Find the size of memory referenced by the load/store.
9391     EVT VecTy;
9392     if (isLoad)
9393       VecTy = N->getValueType(0);
9394     else
9395       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9396     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9397     if (isLaneOp)
9398       NumBytes /= VecTy.getVectorNumElements();
9399
9400     // If the increment is a constant, it must match the memory ref size.
9401     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9402     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9403       uint64_t IncVal = CInc->getZExtValue();
9404       if (IncVal != NumBytes)
9405         continue;
9406     } else if (NumBytes >= 3 * 16) {
9407       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9408       // separate instructions that make it harder to use a non-constant update.
9409       continue;
9410     }
9411
9412     // Create the new updating load/store node.
9413     EVT Tys[6];
9414     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
9415     unsigned n;
9416     for (n = 0; n < NumResultVecs; ++n)
9417       Tys[n] = VecTy;
9418     Tys[n++] = MVT::i32;
9419     Tys[n] = MVT::Other;
9420     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
9421     SmallVector<SDValue, 8> Ops;
9422     Ops.push_back(N->getOperand(0)); // incoming chain
9423     Ops.push_back(N->getOperand(AddrOpIdx));
9424     Ops.push_back(Inc);
9425     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
9426       Ops.push_back(N->getOperand(i));
9427     }
9428     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9429     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9430                                            Ops.data(), Ops.size(),
9431                                            MemInt->getMemoryVT(),
9432                                            MemInt->getMemOperand());
9433
9434     // Update the uses.
9435     std::vector<SDValue> NewResults;
9436     for (unsigned i = 0; i < NumResultVecs; ++i) {
9437       NewResults.push_back(SDValue(UpdN.getNode(), i));
9438     }
9439     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9440     DCI.CombineTo(N, NewResults);
9441     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9442
9443     break;
9444   }
9445   return SDValue();
9446 }
9447
9448 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9449 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9450 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9451 /// return true.
9452 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9453   SelectionDAG &DAG = DCI.DAG;
9454   EVT VT = N->getValueType(0);
9455   // vldN-dup instructions only support 64-bit vectors for N > 1.
9456   if (!VT.is64BitVector())
9457     return false;
9458
9459   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9460   SDNode *VLD = N->getOperand(0).getNode();
9461   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9462     return false;
9463   unsigned NumVecs = 0;
9464   unsigned NewOpc = 0;
9465   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9466   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9467     NumVecs = 2;
9468     NewOpc = ARMISD::VLD2DUP;
9469   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9470     NumVecs = 3;
9471     NewOpc = ARMISD::VLD3DUP;
9472   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9473     NumVecs = 4;
9474     NewOpc = ARMISD::VLD4DUP;
9475   } else {
9476     return false;
9477   }
9478
9479   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9480   // numbers match the load.
9481   unsigned VLDLaneNo =
9482     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9483   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9484        UI != UE; ++UI) {
9485     // Ignore uses of the chain result.
9486     if (UI.getUse().getResNo() == NumVecs)
9487       continue;
9488     SDNode *User = *UI;
9489     if (User->getOpcode() != ARMISD::VDUPLANE ||
9490         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9491       return false;
9492   }
9493
9494   // Create the vldN-dup node.
9495   EVT Tys[5];
9496   unsigned n;
9497   for (n = 0; n < NumVecs; ++n)
9498     Tys[n] = VT;
9499   Tys[n] = MVT::Other;
9500   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
9501   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9502   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9503   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9504                                            Ops, 2, VLDMemInt->getMemoryVT(),
9505                                            VLDMemInt->getMemOperand());
9506
9507   // Update the uses.
9508   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9509        UI != UE; ++UI) {
9510     unsigned ResNo = UI.getUse().getResNo();
9511     // Ignore uses of the chain result.
9512     if (ResNo == NumVecs)
9513       continue;
9514     SDNode *User = *UI;
9515     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9516   }
9517
9518   // Now the vldN-lane intrinsic is dead except for its chain result.
9519   // Update uses of the chain.
9520   std::vector<SDValue> VLDDupResults;
9521   for (unsigned n = 0; n < NumVecs; ++n)
9522     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9523   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9524   DCI.CombineTo(VLD, VLDDupResults);
9525
9526   return true;
9527 }
9528
9529 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9530 /// ARMISD::VDUPLANE.
9531 static SDValue PerformVDUPLANECombine(SDNode *N,
9532                                       TargetLowering::DAGCombinerInfo &DCI) {
9533   SDValue Op = N->getOperand(0);
9534
9535   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9536   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9537   if (CombineVLDDUP(N, DCI))
9538     return SDValue(N, 0);
9539
9540   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9541   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9542   while (Op.getOpcode() == ISD::BITCAST)
9543     Op = Op.getOperand(0);
9544   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9545     return SDValue();
9546
9547   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9548   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9549   // The canonical VMOV for a zero vector uses a 32-bit element size.
9550   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9551   unsigned EltBits;
9552   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9553     EltSize = 8;
9554   EVT VT = N->getValueType(0);
9555   if (EltSize > VT.getVectorElementType().getSizeInBits())
9556     return SDValue();
9557
9558   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9559 }
9560
9561 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9562 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9563 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9564 {
9565   integerPart cN;
9566   integerPart c0 = 0;
9567   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9568        I != E; I++) {
9569     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9570     if (!C)
9571       return false;
9572
9573     bool isExact;
9574     APFloat APF = C->getValueAPF();
9575     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9576         != APFloat::opOK || !isExact)
9577       return false;
9578
9579     c0 = (I == 0) ? cN : c0;
9580     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9581       return false;
9582   }
9583   C = c0;
9584   return true;
9585 }
9586
9587 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9588 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9589 /// when the VMUL has a constant operand that is a power of 2.
9590 ///
9591 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9592 ///  vmul.f32        d16, d17, d16
9593 ///  vcvt.s32.f32    d16, d16
9594 /// becomes:
9595 ///  vcvt.s32.f32    d16, d16, #3
9596 static SDValue PerformVCVTCombine(SDNode *N,
9597                                   TargetLowering::DAGCombinerInfo &DCI,
9598                                   const ARMSubtarget *Subtarget) {
9599   SelectionDAG &DAG = DCI.DAG;
9600   SDValue Op = N->getOperand(0);
9601
9602   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9603       Op.getOpcode() != ISD::FMUL)
9604     return SDValue();
9605
9606   uint64_t C;
9607   SDValue N0 = Op->getOperand(0);
9608   SDValue ConstVec = Op->getOperand(1);
9609   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9610
9611   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9612       !isConstVecPow2(ConstVec, isSigned, C))
9613     return SDValue();
9614
9615   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9616   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9617   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9618     // These instructions only exist converting from f32 to i32. We can handle
9619     // smaller integers by generating an extra truncate, but larger ones would
9620     // be lossy.
9621     return SDValue();
9622   }
9623
9624   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9625     Intrinsic::arm_neon_vcvtfp2fxu;
9626   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9627   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9628                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9629                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9630                                  DAG.getConstant(Log2_64(C), MVT::i32));
9631
9632   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9633     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9634
9635   return FixConv;
9636 }
9637
9638 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9639 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9640 /// when the VDIV has a constant operand that is a power of 2.
9641 ///
9642 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9643 ///  vcvt.f32.s32    d16, d16
9644 ///  vdiv.f32        d16, d17, d16
9645 /// becomes:
9646 ///  vcvt.f32.s32    d16, d16, #3
9647 static SDValue PerformVDIVCombine(SDNode *N,
9648                                   TargetLowering::DAGCombinerInfo &DCI,
9649                                   const ARMSubtarget *Subtarget) {
9650   SelectionDAG &DAG = DCI.DAG;
9651   SDValue Op = N->getOperand(0);
9652   unsigned OpOpcode = Op.getNode()->getOpcode();
9653
9654   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9655       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9656     return SDValue();
9657
9658   uint64_t C;
9659   SDValue ConstVec = N->getOperand(1);
9660   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9661
9662   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9663       !isConstVecPow2(ConstVec, isSigned, C))
9664     return SDValue();
9665
9666   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9667   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9668   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9669     // These instructions only exist converting from i32 to f32. We can handle
9670     // smaller integers by generating an extra extend, but larger ones would
9671     // be lossy.
9672     return SDValue();
9673   }
9674
9675   SDValue ConvInput = Op.getOperand(0);
9676   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9677   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9678     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9679                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9680                             ConvInput);
9681
9682   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9683     Intrinsic::arm_neon_vcvtfxu2fp;
9684   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9685                      Op.getValueType(),
9686                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9687                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9688 }
9689
9690 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9691 /// operand of a vector shift operation, where all the elements of the
9692 /// build_vector must have the same constant integer value.
9693 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9694   // Ignore bit_converts.
9695   while (Op.getOpcode() == ISD::BITCAST)
9696     Op = Op.getOperand(0);
9697   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9698   APInt SplatBits, SplatUndef;
9699   unsigned SplatBitSize;
9700   bool HasAnyUndefs;
9701   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9702                                       HasAnyUndefs, ElementBits) ||
9703       SplatBitSize > ElementBits)
9704     return false;
9705   Cnt = SplatBits.getSExtValue();
9706   return true;
9707 }
9708
9709 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9710 /// operand of a vector shift left operation.  That value must be in the range:
9711 ///   0 <= Value < ElementBits for a left shift; or
9712 ///   0 <= Value <= ElementBits for a long left shift.
9713 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9714   assert(VT.isVector() && "vector shift count is not a vector type");
9715   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9716   if (! getVShiftImm(Op, ElementBits, Cnt))
9717     return false;
9718   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9719 }
9720
9721 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9722 /// operand of a vector shift right operation.  For a shift opcode, the value
9723 /// is positive, but for an intrinsic the value count must be negative. The
9724 /// absolute value must be in the range:
9725 ///   1 <= |Value| <= ElementBits for a right shift; or
9726 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9727 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9728                          int64_t &Cnt) {
9729   assert(VT.isVector() && "vector shift count is not a vector type");
9730   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9731   if (! getVShiftImm(Op, ElementBits, Cnt))
9732     return false;
9733   if (isIntrinsic)
9734     Cnt = -Cnt;
9735   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9736 }
9737
9738 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9739 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9740   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9741   switch (IntNo) {
9742   default:
9743     // Don't do anything for most intrinsics.
9744     break;
9745
9746   // Vector shifts: check for immediate versions and lower them.
9747   // Note: This is done during DAG combining instead of DAG legalizing because
9748   // the build_vectors for 64-bit vector element shift counts are generally
9749   // not legal, and it is hard to see their values after they get legalized to
9750   // loads from a constant pool.
9751   case Intrinsic::arm_neon_vshifts:
9752   case Intrinsic::arm_neon_vshiftu:
9753   case Intrinsic::arm_neon_vrshifts:
9754   case Intrinsic::arm_neon_vrshiftu:
9755   case Intrinsic::arm_neon_vrshiftn:
9756   case Intrinsic::arm_neon_vqshifts:
9757   case Intrinsic::arm_neon_vqshiftu:
9758   case Intrinsic::arm_neon_vqshiftsu:
9759   case Intrinsic::arm_neon_vqshiftns:
9760   case Intrinsic::arm_neon_vqshiftnu:
9761   case Intrinsic::arm_neon_vqshiftnsu:
9762   case Intrinsic::arm_neon_vqrshiftns:
9763   case Intrinsic::arm_neon_vqrshiftnu:
9764   case Intrinsic::arm_neon_vqrshiftnsu: {
9765     EVT VT = N->getOperand(1).getValueType();
9766     int64_t Cnt;
9767     unsigned VShiftOpc = 0;
9768
9769     switch (IntNo) {
9770     case Intrinsic::arm_neon_vshifts:
9771     case Intrinsic::arm_neon_vshiftu:
9772       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9773         VShiftOpc = ARMISD::VSHL;
9774         break;
9775       }
9776       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9777         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9778                      ARMISD::VSHRs : ARMISD::VSHRu);
9779         break;
9780       }
9781       return SDValue();
9782
9783     case Intrinsic::arm_neon_vrshifts:
9784     case Intrinsic::arm_neon_vrshiftu:
9785       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9786         break;
9787       return SDValue();
9788
9789     case Intrinsic::arm_neon_vqshifts:
9790     case Intrinsic::arm_neon_vqshiftu:
9791       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9792         break;
9793       return SDValue();
9794
9795     case Intrinsic::arm_neon_vqshiftsu:
9796       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9797         break;
9798       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9799
9800     case Intrinsic::arm_neon_vrshiftn:
9801     case Intrinsic::arm_neon_vqshiftns:
9802     case Intrinsic::arm_neon_vqshiftnu:
9803     case Intrinsic::arm_neon_vqshiftnsu:
9804     case Intrinsic::arm_neon_vqrshiftns:
9805     case Intrinsic::arm_neon_vqrshiftnu:
9806     case Intrinsic::arm_neon_vqrshiftnsu:
9807       // Narrowing shifts require an immediate right shift.
9808       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9809         break;
9810       llvm_unreachable("invalid shift count for narrowing vector shift "
9811                        "intrinsic");
9812
9813     default:
9814       llvm_unreachable("unhandled vector shift");
9815     }
9816
9817     switch (IntNo) {
9818     case Intrinsic::arm_neon_vshifts:
9819     case Intrinsic::arm_neon_vshiftu:
9820       // Opcode already set above.
9821       break;
9822     case Intrinsic::arm_neon_vrshifts:
9823       VShiftOpc = ARMISD::VRSHRs; break;
9824     case Intrinsic::arm_neon_vrshiftu:
9825       VShiftOpc = ARMISD::VRSHRu; break;
9826     case Intrinsic::arm_neon_vrshiftn:
9827       VShiftOpc = ARMISD::VRSHRN; break;
9828     case Intrinsic::arm_neon_vqshifts:
9829       VShiftOpc = ARMISD::VQSHLs; break;
9830     case Intrinsic::arm_neon_vqshiftu:
9831       VShiftOpc = ARMISD::VQSHLu; break;
9832     case Intrinsic::arm_neon_vqshiftsu:
9833       VShiftOpc = ARMISD::VQSHLsu; break;
9834     case Intrinsic::arm_neon_vqshiftns:
9835       VShiftOpc = ARMISD::VQSHRNs; break;
9836     case Intrinsic::arm_neon_vqshiftnu:
9837       VShiftOpc = ARMISD::VQSHRNu; break;
9838     case Intrinsic::arm_neon_vqshiftnsu:
9839       VShiftOpc = ARMISD::VQSHRNsu; break;
9840     case Intrinsic::arm_neon_vqrshiftns:
9841       VShiftOpc = ARMISD::VQRSHRNs; break;
9842     case Intrinsic::arm_neon_vqrshiftnu:
9843       VShiftOpc = ARMISD::VQRSHRNu; break;
9844     case Intrinsic::arm_neon_vqrshiftnsu:
9845       VShiftOpc = ARMISD::VQRSHRNsu; break;
9846     }
9847
9848     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9849                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9850   }
9851
9852   case Intrinsic::arm_neon_vshiftins: {
9853     EVT VT = N->getOperand(1).getValueType();
9854     int64_t Cnt;
9855     unsigned VShiftOpc = 0;
9856
9857     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9858       VShiftOpc = ARMISD::VSLI;
9859     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9860       VShiftOpc = ARMISD::VSRI;
9861     else {
9862       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9863     }
9864
9865     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9866                        N->getOperand(1), N->getOperand(2),
9867                        DAG.getConstant(Cnt, MVT::i32));
9868   }
9869
9870   case Intrinsic::arm_neon_vqrshifts:
9871   case Intrinsic::arm_neon_vqrshiftu:
9872     // No immediate versions of these to check for.
9873     break;
9874   }
9875
9876   return SDValue();
9877 }
9878
9879 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9880 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9881 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9882 /// vector element shift counts are generally not legal, and it is hard to see
9883 /// their values after they get legalized to loads from a constant pool.
9884 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9885                                    const ARMSubtarget *ST) {
9886   EVT VT = N->getValueType(0);
9887   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9888     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9889     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9890     SDValue N1 = N->getOperand(1);
9891     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9892       SDValue N0 = N->getOperand(0);
9893       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9894           DAG.MaskedValueIsZero(N0.getOperand(0),
9895                                 APInt::getHighBitsSet(32, 16)))
9896         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9897     }
9898   }
9899
9900   // Nothing to be done for scalar shifts.
9901   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9902   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9903     return SDValue();
9904
9905   assert(ST->hasNEON() && "unexpected vector shift");
9906   int64_t Cnt;
9907
9908   switch (N->getOpcode()) {
9909   default: llvm_unreachable("unexpected shift opcode");
9910
9911   case ISD::SHL:
9912     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9913       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9914                          DAG.getConstant(Cnt, MVT::i32));
9915     break;
9916
9917   case ISD::SRA:
9918   case ISD::SRL:
9919     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9920       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9921                             ARMISD::VSHRs : ARMISD::VSHRu);
9922       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9923                          DAG.getConstant(Cnt, MVT::i32));
9924     }
9925   }
9926   return SDValue();
9927 }
9928
9929 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9930 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9931 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9932                                     const ARMSubtarget *ST) {
9933   SDValue N0 = N->getOperand(0);
9934
9935   // Check for sign- and zero-extensions of vector extract operations of 8-
9936   // and 16-bit vector elements.  NEON supports these directly.  They are
9937   // handled during DAG combining because type legalization will promote them
9938   // to 32-bit types and it is messy to recognize the operations after that.
9939   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9940     SDValue Vec = N0.getOperand(0);
9941     SDValue Lane = N0.getOperand(1);
9942     EVT VT = N->getValueType(0);
9943     EVT EltVT = N0.getValueType();
9944     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9945
9946     if (VT == MVT::i32 &&
9947         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9948         TLI.isTypeLegal(Vec.getValueType()) &&
9949         isa<ConstantSDNode>(Lane)) {
9950
9951       unsigned Opc = 0;
9952       switch (N->getOpcode()) {
9953       default: llvm_unreachable("unexpected opcode");
9954       case ISD::SIGN_EXTEND:
9955         Opc = ARMISD::VGETLANEs;
9956         break;
9957       case ISD::ZERO_EXTEND:
9958       case ISD::ANY_EXTEND:
9959         Opc = ARMISD::VGETLANEu;
9960         break;
9961       }
9962       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9963     }
9964   }
9965
9966   return SDValue();
9967 }
9968
9969 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9970 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9971 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9972                                        const ARMSubtarget *ST) {
9973   // If the target supports NEON, try to use vmax/vmin instructions for f32
9974   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9975   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9976   // a NaN; only do the transformation when it matches that behavior.
9977
9978   // For now only do this when using NEON for FP operations; if using VFP, it
9979   // is not obvious that the benefit outweighs the cost of switching to the
9980   // NEON pipeline.
9981   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9982       N->getValueType(0) != MVT::f32)
9983     return SDValue();
9984
9985   SDValue CondLHS = N->getOperand(0);
9986   SDValue CondRHS = N->getOperand(1);
9987   SDValue LHS = N->getOperand(2);
9988   SDValue RHS = N->getOperand(3);
9989   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9990
9991   unsigned Opcode = 0;
9992   bool IsReversed;
9993   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9994     IsReversed = false; // x CC y ? x : y
9995   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9996     IsReversed = true ; // x CC y ? y : x
9997   } else {
9998     return SDValue();
9999   }
10000
10001   bool IsUnordered;
10002   switch (CC) {
10003   default: break;
10004   case ISD::SETOLT:
10005   case ISD::SETOLE:
10006   case ISD::SETLT:
10007   case ISD::SETLE:
10008   case ISD::SETULT:
10009   case ISD::SETULE:
10010     // If LHS is NaN, an ordered comparison will be false and the result will
10011     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
10012     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
10013     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
10014     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10015       break;
10016     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
10017     // will return -0, so vmin can only be used for unsafe math or if one of
10018     // the operands is known to be nonzero.
10019     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
10020         !DAG.getTarget().Options.UnsafeFPMath &&
10021         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10022       break;
10023     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
10024     break;
10025
10026   case ISD::SETOGT:
10027   case ISD::SETOGE:
10028   case ISD::SETGT:
10029   case ISD::SETGE:
10030   case ISD::SETUGT:
10031   case ISD::SETUGE:
10032     // If LHS is NaN, an ordered comparison will be false and the result will
10033     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
10034     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
10035     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
10036     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10037       break;
10038     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
10039     // will return +0, so vmax can only be used for unsafe math or if one of
10040     // the operands is known to be nonzero.
10041     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
10042         !DAG.getTarget().Options.UnsafeFPMath &&
10043         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10044       break;
10045     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
10046     break;
10047   }
10048
10049   if (!Opcode)
10050     return SDValue();
10051   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
10052 }
10053
10054 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10055 SDValue
10056 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10057   SDValue Cmp = N->getOperand(4);
10058   if (Cmp.getOpcode() != ARMISD::CMPZ)
10059     // Only looking at EQ and NE cases.
10060     return SDValue();
10061
10062   EVT VT = N->getValueType(0);
10063   SDLoc dl(N);
10064   SDValue LHS = Cmp.getOperand(0);
10065   SDValue RHS = Cmp.getOperand(1);
10066   SDValue FalseVal = N->getOperand(0);
10067   SDValue TrueVal = N->getOperand(1);
10068   SDValue ARMcc = N->getOperand(2);
10069   ARMCC::CondCodes CC =
10070     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10071
10072   // Simplify
10073   //   mov     r1, r0
10074   //   cmp     r1, x
10075   //   mov     r0, y
10076   //   moveq   r0, x
10077   // to
10078   //   cmp     r0, x
10079   //   movne   r0, y
10080   //
10081   //   mov     r1, r0
10082   //   cmp     r1, x
10083   //   mov     r0, x
10084   //   movne   r0, y
10085   // to
10086   //   cmp     r0, x
10087   //   movne   r0, y
10088   /// FIXME: Turn this into a target neutral optimization?
10089   SDValue Res;
10090   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10091     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10092                       N->getOperand(3), Cmp);
10093   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10094     SDValue ARMcc;
10095     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10096     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10097                       N->getOperand(3), NewCmp);
10098   }
10099
10100   if (Res.getNode()) {
10101     APInt KnownZero, KnownOne;
10102     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
10103     // Capture demanded bits information that would be otherwise lost.
10104     if (KnownZero == 0xfffffffe)
10105       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10106                         DAG.getValueType(MVT::i1));
10107     else if (KnownZero == 0xffffff00)
10108       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10109                         DAG.getValueType(MVT::i8));
10110     else if (KnownZero == 0xffff0000)
10111       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10112                         DAG.getValueType(MVT::i16));
10113   }
10114
10115   return Res;
10116 }
10117
10118 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10119                                              DAGCombinerInfo &DCI) const {
10120   switch (N->getOpcode()) {
10121   default: break;
10122   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
10123   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
10124   case ISD::SUB:        return PerformSUBCombine(N, DCI);
10125   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
10126   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
10127   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
10128   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
10129   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
10130   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
10131   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10132   case ISD::STORE:      return PerformSTORECombine(N, DCI);
10133   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
10134   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10135   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10136   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10137   case ISD::FP_TO_SINT:
10138   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10139   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
10140   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10141   case ISD::SHL:
10142   case ISD::SRA:
10143   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10144   case ISD::SIGN_EXTEND:
10145   case ISD::ZERO_EXTEND:
10146   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10147   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
10148   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10149   case ARMISD::VLD2DUP:
10150   case ARMISD::VLD3DUP:
10151   case ARMISD::VLD4DUP:
10152     return CombineBaseUpdate(N, DCI);
10153   case ARMISD::BUILD_VECTOR:
10154     return PerformARMBUILD_VECTORCombine(N, DCI);
10155   case ISD::INTRINSIC_VOID:
10156   case ISD::INTRINSIC_W_CHAIN:
10157     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10158     case Intrinsic::arm_neon_vld1:
10159     case Intrinsic::arm_neon_vld2:
10160     case Intrinsic::arm_neon_vld3:
10161     case Intrinsic::arm_neon_vld4:
10162     case Intrinsic::arm_neon_vld2lane:
10163     case Intrinsic::arm_neon_vld3lane:
10164     case Intrinsic::arm_neon_vld4lane:
10165     case Intrinsic::arm_neon_vst1:
10166     case Intrinsic::arm_neon_vst2:
10167     case Intrinsic::arm_neon_vst3:
10168     case Intrinsic::arm_neon_vst4:
10169     case Intrinsic::arm_neon_vst2lane:
10170     case Intrinsic::arm_neon_vst3lane:
10171     case Intrinsic::arm_neon_vst4lane:
10172       return CombineBaseUpdate(N, DCI);
10173     default: break;
10174     }
10175     break;
10176   }
10177   return SDValue();
10178 }
10179
10180 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10181                                                           EVT VT) const {
10182   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10183 }
10184
10185 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, unsigned,
10186                                                       bool *Fast) const {
10187   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10188   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10189
10190   switch (VT.getSimpleVT().SimpleTy) {
10191   default:
10192     return false;
10193   case MVT::i8:
10194   case MVT::i16:
10195   case MVT::i32: {
10196     // Unaligned access can use (for example) LRDB, LRDH, LDR
10197     if (AllowsUnaligned) {
10198       if (Fast)
10199         *Fast = Subtarget->hasV7Ops();
10200       return true;
10201     }
10202     return false;
10203   }
10204   case MVT::f64:
10205   case MVT::v2f64: {
10206     // For any little-endian targets with neon, we can support unaligned ld/st
10207     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10208     // A big-endian target may also explicitly support unaligned accesses
10209     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
10210       if (Fast)
10211         *Fast = true;
10212       return true;
10213     }
10214     return false;
10215   }
10216   }
10217 }
10218
10219 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10220                        unsigned AlignCheck) {
10221   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10222           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10223 }
10224
10225 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10226                                            unsigned DstAlign, unsigned SrcAlign,
10227                                            bool IsMemset, bool ZeroMemset,
10228                                            bool MemcpyStrSrc,
10229                                            MachineFunction &MF) const {
10230   const Function *F = MF.getFunction();
10231
10232   // See if we can use NEON instructions for this...
10233   if ((!IsMemset || ZeroMemset) &&
10234       Subtarget->hasNEON() &&
10235       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
10236                                        Attribute::NoImplicitFloat)) {
10237     bool Fast;
10238     if (Size >= 16 &&
10239         (memOpAlign(SrcAlign, DstAlign, 16) ||
10240          (allowsUnalignedMemoryAccesses(MVT::v2f64, 0, &Fast) && Fast))) {
10241       return MVT::v2f64;
10242     } else if (Size >= 8 &&
10243                (memOpAlign(SrcAlign, DstAlign, 8) ||
10244                 (allowsUnalignedMemoryAccesses(MVT::f64, 0, &Fast) && Fast))) {
10245       return MVT::f64;
10246     }
10247   }
10248
10249   // Lowering to i32/i16 if the size permits.
10250   if (Size >= 4)
10251     return MVT::i32;
10252   else if (Size >= 2)
10253     return MVT::i16;
10254
10255   // Let the target-independent logic figure it out.
10256   return MVT::Other;
10257 }
10258
10259 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10260   if (Val.getOpcode() != ISD::LOAD)
10261     return false;
10262
10263   EVT VT1 = Val.getValueType();
10264   if (!VT1.isSimple() || !VT1.isInteger() ||
10265       !VT2.isSimple() || !VT2.isInteger())
10266     return false;
10267
10268   switch (VT1.getSimpleVT().SimpleTy) {
10269   default: break;
10270   case MVT::i1:
10271   case MVT::i8:
10272   case MVT::i16:
10273     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10274     return true;
10275   }
10276
10277   return false;
10278 }
10279
10280 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10281   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10282     return false;
10283
10284   if (!isTypeLegal(EVT::getEVT(Ty1)))
10285     return false;
10286
10287   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10288
10289   // Assuming the caller doesn't have a zeroext or signext return parameter,
10290   // truncation all the way down to i1 is valid.
10291   return true;
10292 }
10293
10294
10295 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10296   if (V < 0)
10297     return false;
10298
10299   unsigned Scale = 1;
10300   switch (VT.getSimpleVT().SimpleTy) {
10301   default: return false;
10302   case MVT::i1:
10303   case MVT::i8:
10304     // Scale == 1;
10305     break;
10306   case MVT::i16:
10307     // Scale == 2;
10308     Scale = 2;
10309     break;
10310   case MVT::i32:
10311     // Scale == 4;
10312     Scale = 4;
10313     break;
10314   }
10315
10316   if ((V & (Scale - 1)) != 0)
10317     return false;
10318   V /= Scale;
10319   return V == (V & ((1LL << 5) - 1));
10320 }
10321
10322 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10323                                       const ARMSubtarget *Subtarget) {
10324   bool isNeg = false;
10325   if (V < 0) {
10326     isNeg = true;
10327     V = - V;
10328   }
10329
10330   switch (VT.getSimpleVT().SimpleTy) {
10331   default: return false;
10332   case MVT::i1:
10333   case MVT::i8:
10334   case MVT::i16:
10335   case MVT::i32:
10336     // + imm12 or - imm8
10337     if (isNeg)
10338       return V == (V & ((1LL << 8) - 1));
10339     return V == (V & ((1LL << 12) - 1));
10340   case MVT::f32:
10341   case MVT::f64:
10342     // Same as ARM mode. FIXME: NEON?
10343     if (!Subtarget->hasVFP2())
10344       return false;
10345     if ((V & 3) != 0)
10346       return false;
10347     V >>= 2;
10348     return V == (V & ((1LL << 8) - 1));
10349   }
10350 }
10351
10352 /// isLegalAddressImmediate - Return true if the integer value can be used
10353 /// as the offset of the target addressing mode for load / store of the
10354 /// given type.
10355 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10356                                     const ARMSubtarget *Subtarget) {
10357   if (V == 0)
10358     return true;
10359
10360   if (!VT.isSimple())
10361     return false;
10362
10363   if (Subtarget->isThumb1Only())
10364     return isLegalT1AddressImmediate(V, VT);
10365   else if (Subtarget->isThumb2())
10366     return isLegalT2AddressImmediate(V, VT, Subtarget);
10367
10368   // ARM mode.
10369   if (V < 0)
10370     V = - V;
10371   switch (VT.getSimpleVT().SimpleTy) {
10372   default: return false;
10373   case MVT::i1:
10374   case MVT::i8:
10375   case MVT::i32:
10376     // +- imm12
10377     return V == (V & ((1LL << 12) - 1));
10378   case MVT::i16:
10379     // +- imm8
10380     return V == (V & ((1LL << 8) - 1));
10381   case MVT::f32:
10382   case MVT::f64:
10383     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10384       return false;
10385     if ((V & 3) != 0)
10386       return false;
10387     V >>= 2;
10388     return V == (V & ((1LL << 8) - 1));
10389   }
10390 }
10391
10392 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10393                                                       EVT VT) const {
10394   int Scale = AM.Scale;
10395   if (Scale < 0)
10396     return false;
10397
10398   switch (VT.getSimpleVT().SimpleTy) {
10399   default: return false;
10400   case MVT::i1:
10401   case MVT::i8:
10402   case MVT::i16:
10403   case MVT::i32:
10404     if (Scale == 1)
10405       return true;
10406     // r + r << imm
10407     Scale = Scale & ~1;
10408     return Scale == 2 || Scale == 4 || Scale == 8;
10409   case MVT::i64:
10410     // r + r
10411     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10412       return true;
10413     return false;
10414   case MVT::isVoid:
10415     // Note, we allow "void" uses (basically, uses that aren't loads or
10416     // stores), because arm allows folding a scale into many arithmetic
10417     // operations.  This should be made more precise and revisited later.
10418
10419     // Allow r << imm, but the imm has to be a multiple of two.
10420     if (Scale & 1) return false;
10421     return isPowerOf2_32(Scale);
10422   }
10423 }
10424
10425 /// isLegalAddressingMode - Return true if the addressing mode represented
10426 /// by AM is legal for this target, for a load/store of the specified type.
10427 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10428                                               Type *Ty) const {
10429   EVT VT = getValueType(Ty, true);
10430   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10431     return false;
10432
10433   // Can never fold addr of global into load/store.
10434   if (AM.BaseGV)
10435     return false;
10436
10437   switch (AM.Scale) {
10438   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10439     break;
10440   case 1:
10441     if (Subtarget->isThumb1Only())
10442       return false;
10443     // FALL THROUGH.
10444   default:
10445     // ARM doesn't support any R+R*scale+imm addr modes.
10446     if (AM.BaseOffs)
10447       return false;
10448
10449     if (!VT.isSimple())
10450       return false;
10451
10452     if (Subtarget->isThumb2())
10453       return isLegalT2ScaledAddressingMode(AM, VT);
10454
10455     int Scale = AM.Scale;
10456     switch (VT.getSimpleVT().SimpleTy) {
10457     default: return false;
10458     case MVT::i1:
10459     case MVT::i8:
10460     case MVT::i32:
10461       if (Scale < 0) Scale = -Scale;
10462       if (Scale == 1)
10463         return true;
10464       // r + r << imm
10465       return isPowerOf2_32(Scale & ~1);
10466     case MVT::i16:
10467     case MVT::i64:
10468       // r + r
10469       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10470         return true;
10471       return false;
10472
10473     case MVT::isVoid:
10474       // Note, we allow "void" uses (basically, uses that aren't loads or
10475       // stores), because arm allows folding a scale into many arithmetic
10476       // operations.  This should be made more precise and revisited later.
10477
10478       // Allow r << imm, but the imm has to be a multiple of two.
10479       if (Scale & 1) return false;
10480       return isPowerOf2_32(Scale);
10481     }
10482   }
10483   return true;
10484 }
10485
10486 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10487 /// icmp immediate, that is the target has icmp instructions which can compare
10488 /// a register against the immediate without having to materialize the
10489 /// immediate into a register.
10490 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10491   // Thumb2 and ARM modes can use cmn for negative immediates.
10492   if (!Subtarget->isThumb())
10493     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10494   if (Subtarget->isThumb2())
10495     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10496   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10497   return Imm >= 0 && Imm <= 255;
10498 }
10499
10500 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10501 /// *or sub* immediate, that is the target has add or sub instructions which can
10502 /// add a register with the immediate without having to materialize the
10503 /// immediate into a register.
10504 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10505   // Same encoding for add/sub, just flip the sign.
10506   int64_t AbsImm = llvm::abs64(Imm);
10507   if (!Subtarget->isThumb())
10508     return ARM_AM::getSOImmVal(AbsImm) != -1;
10509   if (Subtarget->isThumb2())
10510     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10511   // Thumb1 only has 8-bit unsigned immediate.
10512   return AbsImm >= 0 && AbsImm <= 255;
10513 }
10514
10515 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10516                                       bool isSEXTLoad, SDValue &Base,
10517                                       SDValue &Offset, bool &isInc,
10518                                       SelectionDAG &DAG) {
10519   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10520     return false;
10521
10522   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10523     // AddressingMode 3
10524     Base = Ptr->getOperand(0);
10525     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10526       int RHSC = (int)RHS->getZExtValue();
10527       if (RHSC < 0 && RHSC > -256) {
10528         assert(Ptr->getOpcode() == ISD::ADD);
10529         isInc = false;
10530         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10531         return true;
10532       }
10533     }
10534     isInc = (Ptr->getOpcode() == ISD::ADD);
10535     Offset = Ptr->getOperand(1);
10536     return true;
10537   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10538     // AddressingMode 2
10539     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10540       int RHSC = (int)RHS->getZExtValue();
10541       if (RHSC < 0 && RHSC > -0x1000) {
10542         assert(Ptr->getOpcode() == ISD::ADD);
10543         isInc = false;
10544         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10545         Base = Ptr->getOperand(0);
10546         return true;
10547       }
10548     }
10549
10550     if (Ptr->getOpcode() == ISD::ADD) {
10551       isInc = true;
10552       ARM_AM::ShiftOpc ShOpcVal=
10553         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10554       if (ShOpcVal != ARM_AM::no_shift) {
10555         Base = Ptr->getOperand(1);
10556         Offset = Ptr->getOperand(0);
10557       } else {
10558         Base = Ptr->getOperand(0);
10559         Offset = Ptr->getOperand(1);
10560       }
10561       return true;
10562     }
10563
10564     isInc = (Ptr->getOpcode() == ISD::ADD);
10565     Base = Ptr->getOperand(0);
10566     Offset = Ptr->getOperand(1);
10567     return true;
10568   }
10569
10570   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10571   return false;
10572 }
10573
10574 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10575                                      bool isSEXTLoad, SDValue &Base,
10576                                      SDValue &Offset, bool &isInc,
10577                                      SelectionDAG &DAG) {
10578   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10579     return false;
10580
10581   Base = Ptr->getOperand(0);
10582   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10583     int RHSC = (int)RHS->getZExtValue();
10584     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10585       assert(Ptr->getOpcode() == ISD::ADD);
10586       isInc = false;
10587       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10588       return true;
10589     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10590       isInc = Ptr->getOpcode() == ISD::ADD;
10591       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10592       return true;
10593     }
10594   }
10595
10596   return false;
10597 }
10598
10599 /// getPreIndexedAddressParts - returns true by value, base pointer and
10600 /// offset pointer and addressing mode by reference if the node's address
10601 /// can be legally represented as pre-indexed load / store address.
10602 bool
10603 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10604                                              SDValue &Offset,
10605                                              ISD::MemIndexedMode &AM,
10606                                              SelectionDAG &DAG) const {
10607   if (Subtarget->isThumb1Only())
10608     return false;
10609
10610   EVT VT;
10611   SDValue Ptr;
10612   bool isSEXTLoad = false;
10613   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10614     Ptr = LD->getBasePtr();
10615     VT  = LD->getMemoryVT();
10616     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10617   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10618     Ptr = ST->getBasePtr();
10619     VT  = ST->getMemoryVT();
10620   } else
10621     return false;
10622
10623   bool isInc;
10624   bool isLegal = false;
10625   if (Subtarget->isThumb2())
10626     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10627                                        Offset, isInc, DAG);
10628   else
10629     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10630                                         Offset, isInc, DAG);
10631   if (!isLegal)
10632     return false;
10633
10634   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10635   return true;
10636 }
10637
10638 /// getPostIndexedAddressParts - returns true by value, base pointer and
10639 /// offset pointer and addressing mode by reference if this node can be
10640 /// combined with a load / store to form a post-indexed load / store.
10641 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10642                                                    SDValue &Base,
10643                                                    SDValue &Offset,
10644                                                    ISD::MemIndexedMode &AM,
10645                                                    SelectionDAG &DAG) const {
10646   if (Subtarget->isThumb1Only())
10647     return false;
10648
10649   EVT VT;
10650   SDValue Ptr;
10651   bool isSEXTLoad = false;
10652   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10653     VT  = LD->getMemoryVT();
10654     Ptr = LD->getBasePtr();
10655     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10656   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10657     VT  = ST->getMemoryVT();
10658     Ptr = ST->getBasePtr();
10659   } else
10660     return false;
10661
10662   bool isInc;
10663   bool isLegal = false;
10664   if (Subtarget->isThumb2())
10665     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10666                                        isInc, DAG);
10667   else
10668     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10669                                         isInc, DAG);
10670   if (!isLegal)
10671     return false;
10672
10673   if (Ptr != Base) {
10674     // Swap base ptr and offset to catch more post-index load / store when
10675     // it's legal. In Thumb2 mode, offset must be an immediate.
10676     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10677         !Subtarget->isThumb2())
10678       std::swap(Base, Offset);
10679
10680     // Post-indexed load / store update the base pointer.
10681     if (Ptr != Base)
10682       return false;
10683   }
10684
10685   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10686   return true;
10687 }
10688
10689 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10690                                                        APInt &KnownZero,
10691                                                        APInt &KnownOne,
10692                                                        const SelectionDAG &DAG,
10693                                                        unsigned Depth) const {
10694   unsigned BitWidth = KnownOne.getBitWidth();
10695   KnownZero = KnownOne = APInt(BitWidth, 0);
10696   switch (Op.getOpcode()) {
10697   default: break;
10698   case ARMISD::ADDC:
10699   case ARMISD::ADDE:
10700   case ARMISD::SUBC:
10701   case ARMISD::SUBE:
10702     // These nodes' second result is a boolean
10703     if (Op.getResNo() == 0)
10704       break;
10705     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10706     break;
10707   case ARMISD::CMOV: {
10708     // Bits are known zero/one if known on the LHS and RHS.
10709     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10710     if (KnownZero == 0 && KnownOne == 0) return;
10711
10712     APInt KnownZeroRHS, KnownOneRHS;
10713     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10714     KnownZero &= KnownZeroRHS;
10715     KnownOne  &= KnownOneRHS;
10716     return;
10717   }
10718   }
10719 }
10720
10721 //===----------------------------------------------------------------------===//
10722 //                           ARM Inline Assembly Support
10723 //===----------------------------------------------------------------------===//
10724
10725 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10726   // Looking for "rev" which is V6+.
10727   if (!Subtarget->hasV6Ops())
10728     return false;
10729
10730   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10731   std::string AsmStr = IA->getAsmString();
10732   SmallVector<StringRef, 4> AsmPieces;
10733   SplitString(AsmStr, AsmPieces, ";\n");
10734
10735   switch (AsmPieces.size()) {
10736   default: return false;
10737   case 1:
10738     AsmStr = AsmPieces[0];
10739     AsmPieces.clear();
10740     SplitString(AsmStr, AsmPieces, " \t,");
10741
10742     // rev $0, $1
10743     if (AsmPieces.size() == 3 &&
10744         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10745         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10746       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10747       if (Ty && Ty->getBitWidth() == 32)
10748         return IntrinsicLowering::LowerToByteSwap(CI);
10749     }
10750     break;
10751   }
10752
10753   return false;
10754 }
10755
10756 /// getConstraintType - Given a constraint letter, return the type of
10757 /// constraint it is for this target.
10758 ARMTargetLowering::ConstraintType
10759 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10760   if (Constraint.size() == 1) {
10761     switch (Constraint[0]) {
10762     default:  break;
10763     case 'l': return C_RegisterClass;
10764     case 'w': return C_RegisterClass;
10765     case 'h': return C_RegisterClass;
10766     case 'x': return C_RegisterClass;
10767     case 't': return C_RegisterClass;
10768     case 'j': return C_Other; // Constant for movw.
10769       // An address with a single base register. Due to the way we
10770       // currently handle addresses it is the same as an 'r' memory constraint.
10771     case 'Q': return C_Memory;
10772     }
10773   } else if (Constraint.size() == 2) {
10774     switch (Constraint[0]) {
10775     default: break;
10776     // All 'U+' constraints are addresses.
10777     case 'U': return C_Memory;
10778     }
10779   }
10780   return TargetLowering::getConstraintType(Constraint);
10781 }
10782
10783 /// Examine constraint type and operand type and determine a weight value.
10784 /// This object must already have been set up with the operand type
10785 /// and the current alternative constraint selected.
10786 TargetLowering::ConstraintWeight
10787 ARMTargetLowering::getSingleConstraintMatchWeight(
10788     AsmOperandInfo &info, const char *constraint) const {
10789   ConstraintWeight weight = CW_Invalid;
10790   Value *CallOperandVal = info.CallOperandVal;
10791     // If we don't have a value, we can't do a match,
10792     // but allow it at the lowest weight.
10793   if (CallOperandVal == NULL)
10794     return CW_Default;
10795   Type *type = CallOperandVal->getType();
10796   // Look at the constraint type.
10797   switch (*constraint) {
10798   default:
10799     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10800     break;
10801   case 'l':
10802     if (type->isIntegerTy()) {
10803       if (Subtarget->isThumb())
10804         weight = CW_SpecificReg;
10805       else
10806         weight = CW_Register;
10807     }
10808     break;
10809   case 'w':
10810     if (type->isFloatingPointTy())
10811       weight = CW_Register;
10812     break;
10813   }
10814   return weight;
10815 }
10816
10817 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10818 RCPair
10819 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10820                                                 MVT VT) const {
10821   if (Constraint.size() == 1) {
10822     // GCC ARM Constraint Letters
10823     switch (Constraint[0]) {
10824     case 'l': // Low regs or general regs.
10825       if (Subtarget->isThumb())
10826         return RCPair(0U, &ARM::tGPRRegClass);
10827       return RCPair(0U, &ARM::GPRRegClass);
10828     case 'h': // High regs or no regs.
10829       if (Subtarget->isThumb())
10830         return RCPair(0U, &ARM::hGPRRegClass);
10831       break;
10832     case 'r':
10833       return RCPair(0U, &ARM::GPRRegClass);
10834     case 'w':
10835       if (VT == MVT::Other)
10836         break;
10837       if (VT == MVT::f32)
10838         return RCPair(0U, &ARM::SPRRegClass);
10839       if (VT.getSizeInBits() == 64)
10840         return RCPair(0U, &ARM::DPRRegClass);
10841       if (VT.getSizeInBits() == 128)
10842         return RCPair(0U, &ARM::QPRRegClass);
10843       break;
10844     case 'x':
10845       if (VT == MVT::Other)
10846         break;
10847       if (VT == MVT::f32)
10848         return RCPair(0U, &ARM::SPR_8RegClass);
10849       if (VT.getSizeInBits() == 64)
10850         return RCPair(0U, &ARM::DPR_8RegClass);
10851       if (VT.getSizeInBits() == 128)
10852         return RCPair(0U, &ARM::QPR_8RegClass);
10853       break;
10854     case 't':
10855       if (VT == MVT::f32)
10856         return RCPair(0U, &ARM::SPRRegClass);
10857       break;
10858     }
10859   }
10860   if (StringRef("{cc}").equals_lower(Constraint))
10861     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10862
10863   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10864 }
10865
10866 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10867 /// vector.  If it is invalid, don't add anything to Ops.
10868 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10869                                                      std::string &Constraint,
10870                                                      std::vector<SDValue>&Ops,
10871                                                      SelectionDAG &DAG) const {
10872   SDValue Result(0, 0);
10873
10874   // Currently only support length 1 constraints.
10875   if (Constraint.length() != 1) return;
10876
10877   char ConstraintLetter = Constraint[0];
10878   switch (ConstraintLetter) {
10879   default: break;
10880   case 'j':
10881   case 'I': case 'J': case 'K': case 'L':
10882   case 'M': case 'N': case 'O':
10883     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10884     if (!C)
10885       return;
10886
10887     int64_t CVal64 = C->getSExtValue();
10888     int CVal = (int) CVal64;
10889     // None of these constraints allow values larger than 32 bits.  Check
10890     // that the value fits in an int.
10891     if (CVal != CVal64)
10892       return;
10893
10894     switch (ConstraintLetter) {
10895       case 'j':
10896         // Constant suitable for movw, must be between 0 and
10897         // 65535.
10898         if (Subtarget->hasV6T2Ops())
10899           if (CVal >= 0 && CVal <= 65535)
10900             break;
10901         return;
10902       case 'I':
10903         if (Subtarget->isThumb1Only()) {
10904           // This must be a constant between 0 and 255, for ADD
10905           // immediates.
10906           if (CVal >= 0 && CVal <= 255)
10907             break;
10908         } else if (Subtarget->isThumb2()) {
10909           // A constant that can be used as an immediate value in a
10910           // data-processing instruction.
10911           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10912             break;
10913         } else {
10914           // A constant that can be used as an immediate value in a
10915           // data-processing instruction.
10916           if (ARM_AM::getSOImmVal(CVal) != -1)
10917             break;
10918         }
10919         return;
10920
10921       case 'J':
10922         if (Subtarget->isThumb()) {  // FIXME thumb2
10923           // This must be a constant between -255 and -1, for negated ADD
10924           // immediates. This can be used in GCC with an "n" modifier that
10925           // prints the negated value, for use with SUB instructions. It is
10926           // not useful otherwise but is implemented for compatibility.
10927           if (CVal >= -255 && CVal <= -1)
10928             break;
10929         } else {
10930           // This must be a constant between -4095 and 4095. It is not clear
10931           // what this constraint is intended for. Implemented for
10932           // compatibility with GCC.
10933           if (CVal >= -4095 && CVal <= 4095)
10934             break;
10935         }
10936         return;
10937
10938       case 'K':
10939         if (Subtarget->isThumb1Only()) {
10940           // A 32-bit value where only one byte has a nonzero value. Exclude
10941           // zero to match GCC. This constraint is used by GCC internally for
10942           // constants that can be loaded with a move/shift combination.
10943           // It is not useful otherwise but is implemented for compatibility.
10944           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10945             break;
10946         } else if (Subtarget->isThumb2()) {
10947           // A constant whose bitwise inverse can be used as an immediate
10948           // value in a data-processing instruction. This can be used in GCC
10949           // with a "B" modifier that prints the inverted value, for use with
10950           // BIC and MVN instructions. It is not useful otherwise but is
10951           // implemented for compatibility.
10952           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10953             break;
10954         } else {
10955           // A constant whose bitwise inverse can be used as an immediate
10956           // value in a data-processing instruction. This can be used in GCC
10957           // with a "B" modifier that prints the inverted value, for use with
10958           // BIC and MVN instructions. It is not useful otherwise but is
10959           // implemented for compatibility.
10960           if (ARM_AM::getSOImmVal(~CVal) != -1)
10961             break;
10962         }
10963         return;
10964
10965       case 'L':
10966         if (Subtarget->isThumb1Only()) {
10967           // This must be a constant between -7 and 7,
10968           // for 3-operand ADD/SUB immediate instructions.
10969           if (CVal >= -7 && CVal < 7)
10970             break;
10971         } else if (Subtarget->isThumb2()) {
10972           // A constant whose negation can be used as an immediate value in a
10973           // data-processing instruction. This can be used in GCC with an "n"
10974           // modifier that prints the negated value, for use with SUB
10975           // instructions. It is not useful otherwise but is implemented for
10976           // compatibility.
10977           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10978             break;
10979         } else {
10980           // A constant whose negation can be used as an immediate value in a
10981           // data-processing instruction. This can be used in GCC with an "n"
10982           // modifier that prints the negated value, for use with SUB
10983           // instructions. It is not useful otherwise but is implemented for
10984           // compatibility.
10985           if (ARM_AM::getSOImmVal(-CVal) != -1)
10986             break;
10987         }
10988         return;
10989
10990       case 'M':
10991         if (Subtarget->isThumb()) { // FIXME thumb2
10992           // This must be a multiple of 4 between 0 and 1020, for
10993           // ADD sp + immediate.
10994           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10995             break;
10996         } else {
10997           // A power of two or a constant between 0 and 32.  This is used in
10998           // GCC for the shift amount on shifted register operands, but it is
10999           // useful in general for any shift amounts.
11000           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11001             break;
11002         }
11003         return;
11004
11005       case 'N':
11006         if (Subtarget->isThumb()) {  // FIXME thumb2
11007           // This must be a constant between 0 and 31, for shift amounts.
11008           if (CVal >= 0 && CVal <= 31)
11009             break;
11010         }
11011         return;
11012
11013       case 'O':
11014         if (Subtarget->isThumb()) {  // FIXME thumb2
11015           // This must be a multiple of 4 between -508 and 508, for
11016           // ADD/SUB sp = sp + immediate.
11017           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11018             break;
11019         }
11020         return;
11021     }
11022     Result = DAG.getTargetConstant(CVal, Op.getValueType());
11023     break;
11024   }
11025
11026   if (Result.getNode()) {
11027     Ops.push_back(Result);
11028     return;
11029   }
11030   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11031 }
11032
11033 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11034   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
11035   unsigned Opcode = Op->getOpcode();
11036   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11037       "Invalid opcode for Div/Rem lowering");
11038   bool isSigned = (Opcode == ISD::SDIVREM);
11039   EVT VT = Op->getValueType(0);
11040   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11041
11042   RTLIB::Libcall LC;
11043   switch (VT.getSimpleVT().SimpleTy) {
11044   default: llvm_unreachable("Unexpected request for libcall!");
11045   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
11046   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11047   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11048   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11049   }
11050
11051   SDValue InChain = DAG.getEntryNode();
11052
11053   TargetLowering::ArgListTy Args;
11054   TargetLowering::ArgListEntry Entry;
11055   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
11056     EVT ArgVT = Op->getOperand(i).getValueType();
11057     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11058     Entry.Node = Op->getOperand(i);
11059     Entry.Ty = ArgTy;
11060     Entry.isSExt = isSigned;
11061     Entry.isZExt = !isSigned;
11062     Args.push_back(Entry);
11063   }
11064
11065   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11066                                          getPointerTy());
11067
11068   Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
11069
11070   SDLoc dl(Op);
11071   TargetLowering::
11072   CallLoweringInfo CLI(InChain, RetTy, isSigned, !isSigned, false, true,
11073                     0, getLibcallCallingConv(LC), /*isTailCall=*/false,
11074                     /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
11075                     Callee, Args, DAG, dl);
11076   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11077
11078   return CallInfo.first;
11079 }
11080
11081 bool
11082 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11083   // The ARM target isn't yet aware of offsets.
11084   return false;
11085 }
11086
11087 bool ARM::isBitFieldInvertedMask(unsigned v) {
11088   if (v == 0xffffffff)
11089     return false;
11090
11091   // there can be 1's on either or both "outsides", all the "inside"
11092   // bits must be 0's
11093   unsigned TO = CountTrailingOnes_32(v);
11094   unsigned LO = CountLeadingOnes_32(v);
11095   v = (v >> TO) << TO;
11096   v = (v << LO) >> LO;
11097   return v == 0;
11098 }
11099
11100 /// isFPImmLegal - Returns true if the target can instruction select the
11101 /// specified FP immediate natively. If false, the legalizer will
11102 /// materialize the FP immediate as a load from a constant pool.
11103 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11104   if (!Subtarget->hasVFP3())
11105     return false;
11106   if (VT == MVT::f32)
11107     return ARM_AM::getFP32Imm(Imm) != -1;
11108   if (VT == MVT::f64)
11109     return ARM_AM::getFP64Imm(Imm) != -1;
11110   return false;
11111 }
11112
11113 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11114 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11115 /// specified in the intrinsic calls.
11116 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11117                                            const CallInst &I,
11118                                            unsigned Intrinsic) const {
11119   switch (Intrinsic) {
11120   case Intrinsic::arm_neon_vld1:
11121   case Intrinsic::arm_neon_vld2:
11122   case Intrinsic::arm_neon_vld3:
11123   case Intrinsic::arm_neon_vld4:
11124   case Intrinsic::arm_neon_vld2lane:
11125   case Intrinsic::arm_neon_vld3lane:
11126   case Intrinsic::arm_neon_vld4lane: {
11127     Info.opc = ISD::INTRINSIC_W_CHAIN;
11128     // Conservatively set memVT to the entire set of vectors loaded.
11129     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
11130     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11131     Info.ptrVal = I.getArgOperand(0);
11132     Info.offset = 0;
11133     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11134     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11135     Info.vol = false; // volatile loads with NEON intrinsics not supported
11136     Info.readMem = true;
11137     Info.writeMem = false;
11138     return true;
11139   }
11140   case Intrinsic::arm_neon_vst1:
11141   case Intrinsic::arm_neon_vst2:
11142   case Intrinsic::arm_neon_vst3:
11143   case Intrinsic::arm_neon_vst4:
11144   case Intrinsic::arm_neon_vst2lane:
11145   case Intrinsic::arm_neon_vst3lane:
11146   case Intrinsic::arm_neon_vst4lane: {
11147     Info.opc = ISD::INTRINSIC_VOID;
11148     // Conservatively set memVT to the entire set of vectors stored.
11149     unsigned NumElts = 0;
11150     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11151       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11152       if (!ArgTy->isVectorTy())
11153         break;
11154       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
11155     }
11156     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11157     Info.ptrVal = I.getArgOperand(0);
11158     Info.offset = 0;
11159     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11160     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11161     Info.vol = false; // volatile stores with NEON intrinsics not supported
11162     Info.readMem = false;
11163     Info.writeMem = true;
11164     return true;
11165   }
11166   case Intrinsic::arm_ldrex: {
11167     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11168     Info.opc = ISD::INTRINSIC_W_CHAIN;
11169     Info.memVT = MVT::getVT(PtrTy->getElementType());
11170     Info.ptrVal = I.getArgOperand(0);
11171     Info.offset = 0;
11172     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11173     Info.vol = true;
11174     Info.readMem = true;
11175     Info.writeMem = false;
11176     return true;
11177   }
11178   case Intrinsic::arm_strex: {
11179     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11180     Info.opc = ISD::INTRINSIC_W_CHAIN;
11181     Info.memVT = MVT::getVT(PtrTy->getElementType());
11182     Info.ptrVal = I.getArgOperand(1);
11183     Info.offset = 0;
11184     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11185     Info.vol = true;
11186     Info.readMem = false;
11187     Info.writeMem = true;
11188     return true;
11189   }
11190   case Intrinsic::arm_strexd: {
11191     Info.opc = ISD::INTRINSIC_W_CHAIN;
11192     Info.memVT = MVT::i64;
11193     Info.ptrVal = I.getArgOperand(2);
11194     Info.offset = 0;
11195     Info.align = 8;
11196     Info.vol = true;
11197     Info.readMem = false;
11198     Info.writeMem = true;
11199     return true;
11200   }
11201   case Intrinsic::arm_ldrexd: {
11202     Info.opc = ISD::INTRINSIC_W_CHAIN;
11203     Info.memVT = MVT::i64;
11204     Info.ptrVal = I.getArgOperand(0);
11205     Info.offset = 0;
11206     Info.align = 8;
11207     Info.vol = true;
11208     Info.readMem = true;
11209     Info.writeMem = false;
11210     return true;
11211   }
11212   default:
11213     break;
11214   }
11215
11216   return false;
11217 }
11218
11219 /// \brief Returns true if it is beneficial to convert a load of a constant
11220 /// to just the constant itself.
11221 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11222                                                           Type *Ty) const {
11223   assert(Ty->isIntegerTy());
11224
11225   unsigned Bits = Ty->getPrimitiveSizeInBits();
11226   if (Bits == 0 || Bits > 32)
11227     return false;
11228   return true;
11229 }