ARM: decide whether to use movw/movt based on "minsize" attribute.
[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::QPRRegClass);
160   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
161 }
162
163 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
164   if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
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->isTargetIOS()) {
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->isTargetDarwin()) {
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->isTargetDarwin()) {
737     // Non-Darwin 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::VSHLLs:        return "ARMISD::VSHLLs";
1082   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
1083   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
1084   case ARMISD::VSHRN:         return "ARMISD::VSHRN";
1085   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1086   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1087   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1088   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1089   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1090   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1091   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1092   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1093   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1094   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1095   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1096   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1097   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1098   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1099   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1100   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1101   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1102   case ARMISD::VDUP:          return "ARMISD::VDUP";
1103   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1104   case ARMISD::VEXT:          return "ARMISD::VEXT";
1105   case ARMISD::VREV64:        return "ARMISD::VREV64";
1106   case ARMISD::VREV32:        return "ARMISD::VREV32";
1107   case ARMISD::VREV16:        return "ARMISD::VREV16";
1108   case ARMISD::VZIP:          return "ARMISD::VZIP";
1109   case ARMISD::VUZP:          return "ARMISD::VUZP";
1110   case ARMISD::VTRN:          return "ARMISD::VTRN";
1111   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1112   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1113   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1114   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1115   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1116   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1117   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1118   case ARMISD::FMAX:          return "ARMISD::FMAX";
1119   case ARMISD::FMIN:          return "ARMISD::FMIN";
1120   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1121   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1122   case ARMISD::BFI:           return "ARMISD::BFI";
1123   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1124   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1125   case ARMISD::VBSL:          return "ARMISD::VBSL";
1126   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1127   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1128   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1129   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1130   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1131   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1132   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1133   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1134   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1135   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1136   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1137   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1138   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1139   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1140   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1141   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1142   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1143   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1144   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1145   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1146   }
1147 }
1148
1149 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1150   if (!VT.isVector()) return getPointerTy();
1151   return VT.changeVectorElementTypeToInteger();
1152 }
1153
1154 /// getRegClassFor - Return the register class that should be used for the
1155 /// specified value type.
1156 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1157   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1158   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1159   // load / store 4 to 8 consecutive D registers.
1160   if (Subtarget->hasNEON()) {
1161     if (VT == MVT::v4i64)
1162       return &ARM::QQPRRegClass;
1163     if (VT == MVT::v8i64)
1164       return &ARM::QQQQPRRegClass;
1165   }
1166   return TargetLowering::getRegClassFor(VT);
1167 }
1168
1169 // Create a fast isel object.
1170 FastISel *
1171 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1172                                   const TargetLibraryInfo *libInfo) const {
1173   return ARM::createFastISel(funcInfo, libInfo);
1174 }
1175
1176 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1177 /// be used for loads / stores from the global.
1178 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1179   return (Subtarget->isThumb1Only() ? 127 : 4095);
1180 }
1181
1182 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1183   unsigned NumVals = N->getNumValues();
1184   if (!NumVals)
1185     return Sched::RegPressure;
1186
1187   for (unsigned i = 0; i != NumVals; ++i) {
1188     EVT VT = N->getValueType(i);
1189     if (VT == MVT::Glue || VT == MVT::Other)
1190       continue;
1191     if (VT.isFloatingPoint() || VT.isVector())
1192       return Sched::ILP;
1193   }
1194
1195   if (!N->isMachineOpcode())
1196     return Sched::RegPressure;
1197
1198   // Load are scheduled for latency even if there instruction itinerary
1199   // is not available.
1200   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1201   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1202
1203   if (MCID.getNumDefs() == 0)
1204     return Sched::RegPressure;
1205   if (!Itins->isEmpty() &&
1206       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1207     return Sched::ILP;
1208
1209   return Sched::RegPressure;
1210 }
1211
1212 //===----------------------------------------------------------------------===//
1213 // Lowering Code
1214 //===----------------------------------------------------------------------===//
1215
1216 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1217 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1218   switch (CC) {
1219   default: llvm_unreachable("Unknown condition code!");
1220   case ISD::SETNE:  return ARMCC::NE;
1221   case ISD::SETEQ:  return ARMCC::EQ;
1222   case ISD::SETGT:  return ARMCC::GT;
1223   case ISD::SETGE:  return ARMCC::GE;
1224   case ISD::SETLT:  return ARMCC::LT;
1225   case ISD::SETLE:  return ARMCC::LE;
1226   case ISD::SETUGT: return ARMCC::HI;
1227   case ISD::SETUGE: return ARMCC::HS;
1228   case ISD::SETULT: return ARMCC::LO;
1229   case ISD::SETULE: return ARMCC::LS;
1230   }
1231 }
1232
1233 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1234 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1235                         ARMCC::CondCodes &CondCode2) {
1236   CondCode2 = ARMCC::AL;
1237   switch (CC) {
1238   default: llvm_unreachable("Unknown FP condition!");
1239   case ISD::SETEQ:
1240   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1241   case ISD::SETGT:
1242   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1243   case ISD::SETGE:
1244   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1245   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1246   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1247   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1248   case ISD::SETO:   CondCode = ARMCC::VC; break;
1249   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1250   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1251   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1252   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1253   case ISD::SETLT:
1254   case ISD::SETULT: CondCode = ARMCC::LT; break;
1255   case ISD::SETLE:
1256   case ISD::SETULE: CondCode = ARMCC::LE; break;
1257   case ISD::SETNE:
1258   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1259   }
1260 }
1261
1262 //===----------------------------------------------------------------------===//
1263 //                      Calling Convention Implementation
1264 //===----------------------------------------------------------------------===//
1265
1266 #include "ARMGenCallingConv.inc"
1267
1268 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1269 /// given CallingConvention value.
1270 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1271                                                  bool Return,
1272                                                  bool isVarArg) const {
1273   switch (CC) {
1274   default:
1275     llvm_unreachable("Unsupported calling convention");
1276   case CallingConv::Fast:
1277     if (Subtarget->hasVFP2() && !isVarArg) {
1278       if (!Subtarget->isAAPCS_ABI())
1279         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1280       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1281       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1282     }
1283     // Fallthrough
1284   case CallingConv::C: {
1285     // Use target triple & subtarget features to do actual dispatch.
1286     if (!Subtarget->isAAPCS_ABI())
1287       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1288     else if (Subtarget->hasVFP2() &&
1289              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1290              !isVarArg)
1291       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1292     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1293   }
1294   case CallingConv::ARM_AAPCS_VFP:
1295     if (!isVarArg)
1296       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1297     // Fallthrough
1298   case CallingConv::ARM_AAPCS:
1299     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1300   case CallingConv::ARM_APCS:
1301     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1302   case CallingConv::GHC:
1303     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1304   }
1305 }
1306
1307 /// LowerCallResult - Lower the result values of a call into the
1308 /// appropriate copies out of appropriate physical registers.
1309 SDValue
1310 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1311                                    CallingConv::ID CallConv, bool isVarArg,
1312                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1313                                    SDLoc dl, SelectionDAG &DAG,
1314                                    SmallVectorImpl<SDValue> &InVals,
1315                                    bool isThisReturn, SDValue ThisVal) const {
1316
1317   // Assign locations to each value returned by this call.
1318   SmallVector<CCValAssign, 16> RVLocs;
1319   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1320                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1321   CCInfo.AnalyzeCallResult(Ins,
1322                            CCAssignFnForNode(CallConv, /* Return*/ true,
1323                                              isVarArg));
1324
1325   // Copy all of the result registers out of their specified physreg.
1326   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1327     CCValAssign VA = RVLocs[i];
1328
1329     // Pass 'this' value directly from the argument to return value, to avoid
1330     // reg unit interference
1331     if (i == 0 && isThisReturn) {
1332       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1333              "unexpected return calling convention register assignment");
1334       InVals.push_back(ThisVal);
1335       continue;
1336     }
1337
1338     SDValue Val;
1339     if (VA.needsCustom()) {
1340       // Handle f64 or half of a v2f64.
1341       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1342                                       InFlag);
1343       Chain = Lo.getValue(1);
1344       InFlag = Lo.getValue(2);
1345       VA = RVLocs[++i]; // skip ahead to next loc
1346       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1347                                       InFlag);
1348       Chain = Hi.getValue(1);
1349       InFlag = Hi.getValue(2);
1350       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1351
1352       if (VA.getLocVT() == MVT::v2f64) {
1353         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1354         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1355                           DAG.getConstant(0, MVT::i32));
1356
1357         VA = RVLocs[++i]; // skip ahead to next loc
1358         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1359         Chain = Lo.getValue(1);
1360         InFlag = Lo.getValue(2);
1361         VA = RVLocs[++i]; // skip ahead to next loc
1362         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1363         Chain = Hi.getValue(1);
1364         InFlag = Hi.getValue(2);
1365         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1366         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1367                           DAG.getConstant(1, MVT::i32));
1368       }
1369     } else {
1370       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1371                                InFlag);
1372       Chain = Val.getValue(1);
1373       InFlag = Val.getValue(2);
1374     }
1375
1376     switch (VA.getLocInfo()) {
1377     default: llvm_unreachable("Unknown loc info!");
1378     case CCValAssign::Full: break;
1379     case CCValAssign::BCvt:
1380       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1381       break;
1382     }
1383
1384     InVals.push_back(Val);
1385   }
1386
1387   return Chain;
1388 }
1389
1390 /// LowerMemOpCallTo - Store the argument to the stack.
1391 SDValue
1392 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1393                                     SDValue StackPtr, SDValue Arg,
1394                                     SDLoc dl, SelectionDAG &DAG,
1395                                     const CCValAssign &VA,
1396                                     ISD::ArgFlagsTy Flags) const {
1397   unsigned LocMemOffset = VA.getLocMemOffset();
1398   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1399   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1400   return DAG.getStore(Chain, dl, Arg, PtrOff,
1401                       MachinePointerInfo::getStack(LocMemOffset),
1402                       false, false, 0);
1403 }
1404
1405 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1406                                          SDValue Chain, SDValue &Arg,
1407                                          RegsToPassVector &RegsToPass,
1408                                          CCValAssign &VA, CCValAssign &NextVA,
1409                                          SDValue &StackPtr,
1410                                          SmallVectorImpl<SDValue> &MemOpChains,
1411                                          ISD::ArgFlagsTy Flags) const {
1412
1413   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1414                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1415   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1416
1417   if (NextVA.isRegLoc())
1418     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1419   else {
1420     assert(NextVA.isMemLoc());
1421     if (StackPtr.getNode() == 0)
1422       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1423
1424     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1425                                            dl, DAG, NextVA,
1426                                            Flags));
1427   }
1428 }
1429
1430 /// LowerCall - Lowering a call into a callseq_start <-
1431 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1432 /// nodes.
1433 SDValue
1434 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1435                              SmallVectorImpl<SDValue> &InVals) const {
1436   SelectionDAG &DAG                     = CLI.DAG;
1437   SDLoc &dl                          = CLI.DL;
1438   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1439   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1440   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1441   SDValue Chain                         = CLI.Chain;
1442   SDValue Callee                        = CLI.Callee;
1443   bool &isTailCall                      = CLI.IsTailCall;
1444   CallingConv::ID CallConv              = CLI.CallConv;
1445   bool doesNotRet                       = CLI.DoesNotReturn;
1446   bool isVarArg                         = CLI.IsVarArg;
1447
1448   MachineFunction &MF = DAG.getMachineFunction();
1449   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1450   bool isThisReturn   = false;
1451   bool isSibCall      = false;
1452   // Disable tail calls if they're not supported.
1453   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1454     isTailCall = false;
1455   if (isTailCall) {
1456     // Check if it's really possible to do a tail call.
1457     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1458                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1459                                                    Outs, OutVals, Ins, DAG);
1460     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1461     // detected sibcalls.
1462     if (isTailCall) {
1463       ++NumTailCalls;
1464       isSibCall = true;
1465     }
1466   }
1467
1468   // Analyze operands of the call, assigning locations to each operand.
1469   SmallVector<CCValAssign, 16> ArgLocs;
1470   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1471                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1472   CCInfo.AnalyzeCallOperands(Outs,
1473                              CCAssignFnForNode(CallConv, /* Return*/ false,
1474                                                isVarArg));
1475
1476   // Get a count of how many bytes are to be pushed on the stack.
1477   unsigned NumBytes = CCInfo.getNextStackOffset();
1478
1479   // For tail calls, memory operands are available in our caller's stack.
1480   if (isSibCall)
1481     NumBytes = 0;
1482
1483   // Adjust the stack pointer for the new arguments...
1484   // These operations are automatically eliminated by the prolog/epilog pass
1485   if (!isSibCall)
1486     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1487                                  dl);
1488
1489   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1490
1491   RegsToPassVector RegsToPass;
1492   SmallVector<SDValue, 8> MemOpChains;
1493
1494   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1495   // of tail call optimization, arguments are handled later.
1496   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1497        i != e;
1498        ++i, ++realArgIdx) {
1499     CCValAssign &VA = ArgLocs[i];
1500     SDValue Arg = OutVals[realArgIdx];
1501     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1502     bool isByVal = Flags.isByVal();
1503
1504     // Promote the value if needed.
1505     switch (VA.getLocInfo()) {
1506     default: llvm_unreachable("Unknown loc info!");
1507     case CCValAssign::Full: break;
1508     case CCValAssign::SExt:
1509       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1510       break;
1511     case CCValAssign::ZExt:
1512       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1513       break;
1514     case CCValAssign::AExt:
1515       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1516       break;
1517     case CCValAssign::BCvt:
1518       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1519       break;
1520     }
1521
1522     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1523     if (VA.needsCustom()) {
1524       if (VA.getLocVT() == MVT::v2f64) {
1525         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1526                                   DAG.getConstant(0, MVT::i32));
1527         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1528                                   DAG.getConstant(1, MVT::i32));
1529
1530         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1531                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1532
1533         VA = ArgLocs[++i]; // skip ahead to next loc
1534         if (VA.isRegLoc()) {
1535           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1536                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1537         } else {
1538           assert(VA.isMemLoc());
1539
1540           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1541                                                  dl, DAG, VA, Flags));
1542         }
1543       } else {
1544         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1545                          StackPtr, MemOpChains, Flags);
1546       }
1547     } else if (VA.isRegLoc()) {
1548       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1549         assert(VA.getLocVT() == MVT::i32 &&
1550                "unexpected calling convention register assignment");
1551         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1552                "unexpected use of 'returned'");
1553         isThisReturn = true;
1554       }
1555       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1556     } else if (isByVal) {
1557       assert(VA.isMemLoc());
1558       unsigned offset = 0;
1559
1560       // True if this byval aggregate will be split between registers
1561       // and memory.
1562       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1563       unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1564
1565       if (CurByValIdx < ByValArgsCount) {
1566
1567         unsigned RegBegin, RegEnd;
1568         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1569
1570         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1571         unsigned int i, j;
1572         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1573           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1574           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1575           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1576                                      MachinePointerInfo(),
1577                                      false, false, false,
1578                                      DAG.InferPtrAlignment(AddArg));
1579           MemOpChains.push_back(Load.getValue(1));
1580           RegsToPass.push_back(std::make_pair(j, Load));
1581         }
1582
1583         // If parameter size outsides register area, "offset" value
1584         // helps us to calculate stack slot for remained part properly.
1585         offset = RegEnd - RegBegin;
1586
1587         CCInfo.nextInRegsParam();
1588       }
1589
1590       if (Flags.getByValSize() > 4*offset) {
1591         unsigned LocMemOffset = VA.getLocMemOffset();
1592         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1593         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1594                                   StkPtrOff);
1595         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1596         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1597         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1598                                            MVT::i32);
1599         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1600
1601         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1602         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1603         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1604                                           Ops, array_lengthof(Ops)));
1605       }
1606     } else if (!isSibCall) {
1607       assert(VA.isMemLoc());
1608
1609       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1610                                              dl, DAG, VA, Flags));
1611     }
1612   }
1613
1614   if (!MemOpChains.empty())
1615     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1616                         &MemOpChains[0], MemOpChains.size());
1617
1618   // Build a sequence of copy-to-reg nodes chained together with token chain
1619   // and flag operands which copy the outgoing args into the appropriate regs.
1620   SDValue InFlag;
1621   // Tail call byval lowering might overwrite argument registers so in case of
1622   // tail call optimization the copies to registers are lowered later.
1623   if (!isTailCall)
1624     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1625       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1626                                RegsToPass[i].second, InFlag);
1627       InFlag = Chain.getValue(1);
1628     }
1629
1630   // For tail calls lower the arguments to the 'real' stack slot.
1631   if (isTailCall) {
1632     // Force all the incoming stack arguments to be loaded from the stack
1633     // before any new outgoing arguments are stored to the stack, because the
1634     // outgoing stack slots may alias the incoming argument stack slots, and
1635     // the alias isn't otherwise explicit. This is slightly more conservative
1636     // than necessary, because it means that each store effectively depends
1637     // on every argument instead of just those arguments it would clobber.
1638
1639     // Do not flag preceding copytoreg stuff together with the following stuff.
1640     InFlag = SDValue();
1641     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1642       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1643                                RegsToPass[i].second, InFlag);
1644       InFlag = Chain.getValue(1);
1645     }
1646     InFlag = SDValue();
1647   }
1648
1649   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1650   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1651   // node so that legalize doesn't hack it.
1652   bool isDirect = false;
1653   bool isARMFunc = false;
1654   bool isLocalARMFunc = false;
1655   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1656
1657   if (EnableARMLongCalls) {
1658     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1659             && "long-calls with non-static relocation model!");
1660     // Handle a global address or an external symbol. If it's not one of
1661     // those, the target's already in a register, so we don't need to do
1662     // anything extra.
1663     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1664       const GlobalValue *GV = G->getGlobal();
1665       // Create a constant pool entry for the callee address
1666       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1667       ARMConstantPoolValue *CPV =
1668         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1669
1670       // Get the address of the callee into a register
1671       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1672       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1673       Callee = DAG.getLoad(getPointerTy(), dl,
1674                            DAG.getEntryNode(), CPAddr,
1675                            MachinePointerInfo::getConstantPool(),
1676                            false, false, false, 0);
1677     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1678       const char *Sym = S->getSymbol();
1679
1680       // Create a constant pool entry for the callee address
1681       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1682       ARMConstantPoolValue *CPV =
1683         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1684                                       ARMPCLabelIndex, 0);
1685       // Get the address of the callee into a register
1686       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1687       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1688       Callee = DAG.getLoad(getPointerTy(), dl,
1689                            DAG.getEntryNode(), CPAddr,
1690                            MachinePointerInfo::getConstantPool(),
1691                            false, false, false, 0);
1692     }
1693   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1694     const GlobalValue *GV = G->getGlobal();
1695     isDirect = true;
1696     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1697     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1698                    getTargetMachine().getRelocationModel() != Reloc::Static;
1699     isARMFunc = !Subtarget->isThumb() || isStub;
1700     // ARM call to a local ARM function is predicable.
1701     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1702     // tBX takes a register source operand.
1703     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1704       assert(Subtarget->isTargetDarwin() && "WrapperPIC use on non-Darwin?");
1705       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1706                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy()));
1707     } else {
1708       // On ELF targets for PIC code, direct calls should go through the PLT
1709       unsigned OpFlags = 0;
1710       if (Subtarget->isTargetELF() &&
1711           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1712         OpFlags = ARMII::MO_PLT;
1713       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1714     }
1715   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1716     isDirect = true;
1717     bool isStub = Subtarget->isTargetDarwin() &&
1718                   getTargetMachine().getRelocationModel() != Reloc::Static;
1719     isARMFunc = !Subtarget->isThumb() || isStub;
1720     // tBX takes a register source operand.
1721     const char *Sym = S->getSymbol();
1722     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1723       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1724       ARMConstantPoolValue *CPV =
1725         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1726                                       ARMPCLabelIndex, 4);
1727       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1728       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1729       Callee = DAG.getLoad(getPointerTy(), dl,
1730                            DAG.getEntryNode(), CPAddr,
1731                            MachinePointerInfo::getConstantPool(),
1732                            false, false, false, 0);
1733       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1734       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1735                            getPointerTy(), Callee, PICLabel);
1736     } else {
1737       unsigned OpFlags = 0;
1738       // On ELF targets for PIC code, direct calls should go through the PLT
1739       if (Subtarget->isTargetELF() &&
1740                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1741         OpFlags = ARMII::MO_PLT;
1742       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1743     }
1744   }
1745
1746   // FIXME: handle tail calls differently.
1747   unsigned CallOpc;
1748   bool HasMinSizeAttr = Subtarget->isMinSize();
1749   if (Subtarget->isThumb()) {
1750     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1751       CallOpc = ARMISD::CALL_NOLINK;
1752     else
1753       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1754   } else {
1755     if (!isDirect && !Subtarget->hasV5TOps())
1756       CallOpc = ARMISD::CALL_NOLINK;
1757     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1758                // Emit regular call when code size is the priority
1759                !HasMinSizeAttr)
1760       // "mov lr, pc; b _foo" to avoid confusing the RSP
1761       CallOpc = ARMISD::CALL_NOLINK;
1762     else
1763       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1764   }
1765
1766   std::vector<SDValue> Ops;
1767   Ops.push_back(Chain);
1768   Ops.push_back(Callee);
1769
1770   // Add argument registers to the end of the list so that they are known live
1771   // into the call.
1772   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1773     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1774                                   RegsToPass[i].second.getValueType()));
1775
1776   // Add a register mask operand representing the call-preserved registers.
1777   if (!isTailCall) {
1778     const uint32_t *Mask;
1779     const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1780     const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1781     if (isThisReturn) {
1782       // For 'this' returns, use the R0-preserving mask if applicable
1783       Mask = ARI->getThisReturnPreservedMask(CallConv);
1784       if (!Mask) {
1785         // Set isThisReturn to false if the calling convention is not one that
1786         // allows 'returned' to be modeled in this way, so LowerCallResult does
1787         // not try to pass 'this' straight through
1788         isThisReturn = false;
1789         Mask = ARI->getCallPreservedMask(CallConv);
1790       }
1791     } else
1792       Mask = ARI->getCallPreservedMask(CallConv);
1793
1794     assert(Mask && "Missing call preserved mask for calling convention");
1795     Ops.push_back(DAG.getRegisterMask(Mask));
1796   }
1797
1798   if (InFlag.getNode())
1799     Ops.push_back(InFlag);
1800
1801   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1802   if (isTailCall)
1803     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1804
1805   // Returns a chain and a flag for retval copy to use.
1806   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1807   InFlag = Chain.getValue(1);
1808
1809   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1810                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1811   if (!Ins.empty())
1812     InFlag = Chain.getValue(1);
1813
1814   // Handle result values, copying them out of physregs into vregs that we
1815   // return.
1816   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1817                          InVals, isThisReturn,
1818                          isThisReturn ? OutVals[0] : SDValue());
1819 }
1820
1821 /// HandleByVal - Every parameter *after* a byval parameter is passed
1822 /// on the stack.  Remember the next parameter register to allocate,
1823 /// and then confiscate the rest of the parameter registers to insure
1824 /// this.
1825 void
1826 ARMTargetLowering::HandleByVal(
1827     CCState *State, unsigned &size, unsigned Align) const {
1828   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1829   assert((State->getCallOrPrologue() == Prologue ||
1830           State->getCallOrPrologue() == Call) &&
1831          "unhandled ParmContext");
1832
1833   // For in-prologue parameters handling, we also introduce stack offset
1834   // for byval registers: see CallingConvLower.cpp, CCState::HandleByVal.
1835   // This behaviour outsides AAPCS rules (5.5 Parameters Passing) of how
1836   // NSAA should be evaluted (NSAA means "next stacked argument address").
1837   // So: NextStackOffset = NSAAOffset + SizeOfByValParamsStoredInRegs.
1838   // Then: NSAAOffset = NextStackOffset - SizeOfByValParamsStoredInRegs.
1839   unsigned NSAAOffset = State->getNextStackOffset();
1840   if (State->getCallOrPrologue() != Call) {
1841     for (unsigned i = 0, e = State->getInRegsParamsCount(); i != e; ++i) {
1842       unsigned RB, RE;
1843       State->getInRegsParamInfo(i, RB, RE);
1844       assert(NSAAOffset >= (RE-RB)*4 &&
1845              "Stack offset for byval regs doesn't introduced anymore?");
1846       NSAAOffset -= (RE-RB)*4;
1847     }
1848   }
1849   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1850     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1851       unsigned AlignInRegs = Align / 4;
1852       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1853       for (unsigned i = 0; i < Waste; ++i)
1854         reg = State->AllocateReg(GPRArgRegs, 4);
1855     }
1856     if (reg != 0) {
1857       unsigned excess = 4 * (ARM::R4 - reg);
1858
1859       // Special case when NSAA != SP and parameter size greater than size of
1860       // all remained GPR regs. In that case we can't split parameter, we must
1861       // send it to stack. We also must set NCRN to R4, so waste all
1862       // remained registers.
1863       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1864         while (State->AllocateReg(GPRArgRegs, 4))
1865           ;
1866         return;
1867       }
1868
1869       // First register for byval parameter is the first register that wasn't
1870       // allocated before this method call, so it would be "reg".
1871       // If parameter is small enough to be saved in range [reg, r4), then
1872       // the end (first after last) register would be reg + param-size-in-regs,
1873       // else parameter would be splitted between registers and stack,
1874       // end register would be r4 in this case.
1875       unsigned ByValRegBegin = reg;
1876       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1877       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1878       // Note, first register is allocated in the beginning of function already,
1879       // allocate remained amount of registers we need.
1880       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1881         State->AllocateReg(GPRArgRegs, 4);
1882       // At a call site, a byval parameter that is split between
1883       // registers and memory needs its size truncated here.  In a
1884       // function prologue, such byval parameters are reassembled in
1885       // memory, and are not truncated.
1886       if (State->getCallOrPrologue() == Call) {
1887         // Make remained size equal to 0 in case, when
1888         // the whole structure may be stored into registers.
1889         if (size < excess)
1890           size = 0;
1891         else
1892           size -= excess;
1893       }
1894     }
1895   }
1896 }
1897
1898 /// MatchingStackOffset - Return true if the given stack call argument is
1899 /// already available in the same position (relatively) of the caller's
1900 /// incoming argument stack.
1901 static
1902 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1903                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1904                          const TargetInstrInfo *TII) {
1905   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1906   int FI = INT_MAX;
1907   if (Arg.getOpcode() == ISD::CopyFromReg) {
1908     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1909     if (!TargetRegisterInfo::isVirtualRegister(VR))
1910       return false;
1911     MachineInstr *Def = MRI->getVRegDef(VR);
1912     if (!Def)
1913       return false;
1914     if (!Flags.isByVal()) {
1915       if (!TII->isLoadFromStackSlot(Def, FI))
1916         return false;
1917     } else {
1918       return false;
1919     }
1920   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1921     if (Flags.isByVal())
1922       // ByVal argument is passed in as a pointer but it's now being
1923       // dereferenced. e.g.
1924       // define @foo(%struct.X* %A) {
1925       //   tail call @bar(%struct.X* byval %A)
1926       // }
1927       return false;
1928     SDValue Ptr = Ld->getBasePtr();
1929     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1930     if (!FINode)
1931       return false;
1932     FI = FINode->getIndex();
1933   } else
1934     return false;
1935
1936   assert(FI != INT_MAX);
1937   if (!MFI->isFixedObjectIndex(FI))
1938     return false;
1939   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1940 }
1941
1942 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1943 /// for tail call optimization. Targets which want to do tail call
1944 /// optimization should implement this function.
1945 bool
1946 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1947                                                      CallingConv::ID CalleeCC,
1948                                                      bool isVarArg,
1949                                                      bool isCalleeStructRet,
1950                                                      bool isCallerStructRet,
1951                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1952                                     const SmallVectorImpl<SDValue> &OutVals,
1953                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1954                                                      SelectionDAG& DAG) const {
1955   const Function *CallerF = DAG.getMachineFunction().getFunction();
1956   CallingConv::ID CallerCC = CallerF->getCallingConv();
1957   bool CCMatch = CallerCC == CalleeCC;
1958
1959   // Look for obvious safe cases to perform tail call optimization that do not
1960   // require ABI changes. This is what gcc calls sibcall.
1961
1962   // Do not sibcall optimize vararg calls unless the call site is not passing
1963   // any arguments.
1964   if (isVarArg && !Outs.empty())
1965     return false;
1966
1967   // Exception-handling functions need a special set of instructions to indicate
1968   // a return to the hardware. Tail-calling another function would probably
1969   // break this.
1970   if (CallerF->hasFnAttribute("interrupt"))
1971     return false;
1972
1973   // Also avoid sibcall optimization if either caller or callee uses struct
1974   // return semantics.
1975   if (isCalleeStructRet || isCallerStructRet)
1976     return false;
1977
1978   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1979   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1980   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1981   // support in the assembler and linker to be used. This would need to be
1982   // fixed to fully support tail calls in Thumb1.
1983   //
1984   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1985   // LR.  This means if we need to reload LR, it takes an extra instructions,
1986   // which outweighs the value of the tail call; but here we don't know yet
1987   // whether LR is going to be used.  Probably the right approach is to
1988   // generate the tail call here and turn it back into CALL/RET in
1989   // emitEpilogue if LR is used.
1990
1991   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1992   // but we need to make sure there are enough registers; the only valid
1993   // registers are the 4 used for parameters.  We don't currently do this
1994   // case.
1995   if (Subtarget->isThumb1Only())
1996     return false;
1997
1998   // If the calling conventions do not match, then we'd better make sure the
1999   // results are returned in the same way as what the caller expects.
2000   if (!CCMatch) {
2001     SmallVector<CCValAssign, 16> RVLocs1;
2002     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2003                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
2004     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2005
2006     SmallVector<CCValAssign, 16> RVLocs2;
2007     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2008                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
2009     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2010
2011     if (RVLocs1.size() != RVLocs2.size())
2012       return false;
2013     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2014       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2015         return false;
2016       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2017         return false;
2018       if (RVLocs1[i].isRegLoc()) {
2019         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2020           return false;
2021       } else {
2022         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2023           return false;
2024       }
2025     }
2026   }
2027
2028   // If Caller's vararg or byval argument has been split between registers and
2029   // stack, do not perform tail call, since part of the argument is in caller's
2030   // local frame.
2031   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2032                                       getInfo<ARMFunctionInfo>();
2033   if (AFI_Caller->getArgRegsSaveSize())
2034     return false;
2035
2036   // If the callee takes no arguments then go on to check the results of the
2037   // call.
2038   if (!Outs.empty()) {
2039     // Check if stack adjustment is needed. For now, do not do this if any
2040     // argument is passed on the stack.
2041     SmallVector<CCValAssign, 16> ArgLocs;
2042     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2043                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
2044     CCInfo.AnalyzeCallOperands(Outs,
2045                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2046     if (CCInfo.getNextStackOffset()) {
2047       MachineFunction &MF = DAG.getMachineFunction();
2048
2049       // Check if the arguments are already laid out in the right way as
2050       // the caller's fixed stack objects.
2051       MachineFrameInfo *MFI = MF.getFrameInfo();
2052       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2053       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2054       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2055            i != e;
2056            ++i, ++realArgIdx) {
2057         CCValAssign &VA = ArgLocs[i];
2058         EVT RegVT = VA.getLocVT();
2059         SDValue Arg = OutVals[realArgIdx];
2060         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2061         if (VA.getLocInfo() == CCValAssign::Indirect)
2062           return false;
2063         if (VA.needsCustom()) {
2064           // f64 and vector types are split into multiple registers or
2065           // register/stack-slot combinations.  The types will not match
2066           // the registers; give up on memory f64 refs until we figure
2067           // out what to do about this.
2068           if (!VA.isRegLoc())
2069             return false;
2070           if (!ArgLocs[++i].isRegLoc())
2071             return false;
2072           if (RegVT == MVT::v2f64) {
2073             if (!ArgLocs[++i].isRegLoc())
2074               return false;
2075             if (!ArgLocs[++i].isRegLoc())
2076               return false;
2077           }
2078         } else if (!VA.isRegLoc()) {
2079           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2080                                    MFI, MRI, TII))
2081             return false;
2082         }
2083       }
2084     }
2085   }
2086
2087   return true;
2088 }
2089
2090 bool
2091 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2092                                   MachineFunction &MF, bool isVarArg,
2093                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2094                                   LLVMContext &Context) const {
2095   SmallVector<CCValAssign, 16> RVLocs;
2096   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2097   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2098                                                     isVarArg));
2099 }
2100
2101 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2102                                     SDLoc DL, SelectionDAG &DAG) {
2103   const MachineFunction &MF = DAG.getMachineFunction();
2104   const Function *F = MF.getFunction();
2105
2106   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2107
2108   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2109   // version of the "preferred return address". These offsets affect the return
2110   // instruction if this is a return from PL1 without hypervisor extensions.
2111   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2112   //    SWI:     0      "subs pc, lr, #0"
2113   //    ABORT:   +4     "subs pc, lr, #4"
2114   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2115   // UNDEF varies depending on where the exception came from ARM or Thumb
2116   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2117
2118   int64_t LROffset;
2119   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2120       IntKind == "ABORT")
2121     LROffset = 4;
2122   else if (IntKind == "SWI" || IntKind == "UNDEF")
2123     LROffset = 0;
2124   else
2125     report_fatal_error("Unsupported interrupt attribute. If present, value "
2126                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2127
2128   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2129
2130   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other,
2131                      RetOps.data(), RetOps.size());
2132 }
2133
2134 SDValue
2135 ARMTargetLowering::LowerReturn(SDValue Chain,
2136                                CallingConv::ID CallConv, bool isVarArg,
2137                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2138                                const SmallVectorImpl<SDValue> &OutVals,
2139                                SDLoc dl, SelectionDAG &DAG) const {
2140
2141   // CCValAssign - represent the assignment of the return value to a location.
2142   SmallVector<CCValAssign, 16> RVLocs;
2143
2144   // CCState - Info about the registers and stack slots.
2145   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2146                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2147
2148   // Analyze outgoing return values.
2149   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2150                                                isVarArg));
2151
2152   SDValue Flag;
2153   SmallVector<SDValue, 4> RetOps;
2154   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2155
2156   // Copy the result values into the output registers.
2157   for (unsigned i = 0, realRVLocIdx = 0;
2158        i != RVLocs.size();
2159        ++i, ++realRVLocIdx) {
2160     CCValAssign &VA = RVLocs[i];
2161     assert(VA.isRegLoc() && "Can only return in registers!");
2162
2163     SDValue Arg = OutVals[realRVLocIdx];
2164
2165     switch (VA.getLocInfo()) {
2166     default: llvm_unreachable("Unknown loc info!");
2167     case CCValAssign::Full: break;
2168     case CCValAssign::BCvt:
2169       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2170       break;
2171     }
2172
2173     if (VA.needsCustom()) {
2174       if (VA.getLocVT() == MVT::v2f64) {
2175         // Extract the first half and return it in two registers.
2176         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2177                                    DAG.getConstant(0, MVT::i32));
2178         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2179                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2180
2181         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
2182         Flag = Chain.getValue(1);
2183         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2184         VA = RVLocs[++i]; // skip ahead to next loc
2185         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2186                                  HalfGPRs.getValue(1), Flag);
2187         Flag = Chain.getValue(1);
2188         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2189         VA = RVLocs[++i]; // skip ahead to next loc
2190
2191         // Extract the 2nd half and fall through to handle it as an f64 value.
2192         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2193                           DAG.getConstant(1, MVT::i32));
2194       }
2195       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2196       // available.
2197       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2198                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
2199       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
2200       Flag = Chain.getValue(1);
2201       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2202       VA = RVLocs[++i]; // skip ahead to next loc
2203       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
2204                                Flag);
2205     } else
2206       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2207
2208     // Guarantee that all emitted copies are
2209     // stuck together, avoiding something bad.
2210     Flag = Chain.getValue(1);
2211     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2212   }
2213
2214   // Update chain and glue.
2215   RetOps[0] = Chain;
2216   if (Flag.getNode())
2217     RetOps.push_back(Flag);
2218
2219   // CPUs which aren't M-class use a special sequence to return from
2220   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2221   // though we use "subs pc, lr, #N").
2222   //
2223   // M-class CPUs actually use a normal return sequence with a special
2224   // (hardware-provided) value in LR, so the normal code path works.
2225   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2226       !Subtarget->isMClass()) {
2227     if (Subtarget->isThumb1Only())
2228       report_fatal_error("interrupt attribute is not supported in Thumb1");
2229     return LowerInterruptReturn(RetOps, dl, DAG);
2230   }
2231
2232   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
2233                      RetOps.data(), RetOps.size());
2234 }
2235
2236 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2237   if (N->getNumValues() != 1)
2238     return false;
2239   if (!N->hasNUsesOfValue(1, 0))
2240     return false;
2241
2242   SDValue TCChain = Chain;
2243   SDNode *Copy = *N->use_begin();
2244   if (Copy->getOpcode() == ISD::CopyToReg) {
2245     // If the copy has a glue operand, we conservatively assume it isn't safe to
2246     // perform a tail call.
2247     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2248       return false;
2249     TCChain = Copy->getOperand(0);
2250   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2251     SDNode *VMov = Copy;
2252     // f64 returned in a pair of GPRs.
2253     SmallPtrSet<SDNode*, 2> Copies;
2254     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2255          UI != UE; ++UI) {
2256       if (UI->getOpcode() != ISD::CopyToReg)
2257         return false;
2258       Copies.insert(*UI);
2259     }
2260     if (Copies.size() > 2)
2261       return false;
2262
2263     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2264          UI != UE; ++UI) {
2265       SDValue UseChain = UI->getOperand(0);
2266       if (Copies.count(UseChain.getNode()))
2267         // Second CopyToReg
2268         Copy = *UI;
2269       else
2270         // First CopyToReg
2271         TCChain = UseChain;
2272     }
2273   } else if (Copy->getOpcode() == ISD::BITCAST) {
2274     // f32 returned in a single GPR.
2275     if (!Copy->hasOneUse())
2276       return false;
2277     Copy = *Copy->use_begin();
2278     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2279       return false;
2280     TCChain = Copy->getOperand(0);
2281   } else {
2282     return false;
2283   }
2284
2285   bool HasRet = false;
2286   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2287        UI != UE; ++UI) {
2288     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2289         UI->getOpcode() != ARMISD::INTRET_FLAG)
2290       return false;
2291     HasRet = true;
2292   }
2293
2294   if (!HasRet)
2295     return false;
2296
2297   Chain = TCChain;
2298   return true;
2299 }
2300
2301 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2302   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2303     return false;
2304
2305   if (!CI->isTailCall())
2306     return false;
2307
2308   return !Subtarget->isThumb1Only();
2309 }
2310
2311 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2312 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2313 // one of the above mentioned nodes. It has to be wrapped because otherwise
2314 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2315 // be used to form addressing mode. These wrapped nodes will be selected
2316 // into MOVi.
2317 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2318   EVT PtrVT = Op.getValueType();
2319   // FIXME there is no actual debug info here
2320   SDLoc dl(Op);
2321   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2322   SDValue Res;
2323   if (CP->isMachineConstantPoolEntry())
2324     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2325                                     CP->getAlignment());
2326   else
2327     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2328                                     CP->getAlignment());
2329   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2330 }
2331
2332 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2333   return MachineJumpTableInfo::EK_Inline;
2334 }
2335
2336 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2337                                              SelectionDAG &DAG) const {
2338   MachineFunction &MF = DAG.getMachineFunction();
2339   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2340   unsigned ARMPCLabelIndex = 0;
2341   SDLoc DL(Op);
2342   EVT PtrVT = getPointerTy();
2343   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2344   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2345   SDValue CPAddr;
2346   if (RelocM == Reloc::Static) {
2347     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2348   } else {
2349     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2350     ARMPCLabelIndex = AFI->createPICLabelUId();
2351     ARMConstantPoolValue *CPV =
2352       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2353                                       ARMCP::CPBlockAddress, PCAdj);
2354     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2355   }
2356   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2357   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2358                                MachinePointerInfo::getConstantPool(),
2359                                false, false, false, 0);
2360   if (RelocM == Reloc::Static)
2361     return Result;
2362   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2363   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2364 }
2365
2366 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2367 SDValue
2368 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2369                                                  SelectionDAG &DAG) const {
2370   SDLoc dl(GA);
2371   EVT PtrVT = getPointerTy();
2372   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2373   MachineFunction &MF = DAG.getMachineFunction();
2374   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2375   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2376   ARMConstantPoolValue *CPV =
2377     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2378                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2379   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2380   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2381   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2382                          MachinePointerInfo::getConstantPool(),
2383                          false, false, false, 0);
2384   SDValue Chain = Argument.getValue(1);
2385
2386   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2387   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2388
2389   // call __tls_get_addr.
2390   ArgListTy Args;
2391   ArgListEntry Entry;
2392   Entry.Node = Argument;
2393   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2394   Args.push_back(Entry);
2395   // FIXME: is there useful debug info available here?
2396   TargetLowering::CallLoweringInfo CLI(Chain,
2397                 (Type *) Type::getInt32Ty(*DAG.getContext()),
2398                 false, false, false, false,
2399                 0, CallingConv::C, /*isTailCall=*/false,
2400                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2401                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2402   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2403   return CallResult.first;
2404 }
2405
2406 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2407 // "local exec" model.
2408 SDValue
2409 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2410                                         SelectionDAG &DAG,
2411                                         TLSModel::Model model) const {
2412   const GlobalValue *GV = GA->getGlobal();
2413   SDLoc dl(GA);
2414   SDValue Offset;
2415   SDValue Chain = DAG.getEntryNode();
2416   EVT PtrVT = getPointerTy();
2417   // Get the Thread Pointer
2418   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2419
2420   if (model == TLSModel::InitialExec) {
2421     MachineFunction &MF = DAG.getMachineFunction();
2422     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2423     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2424     // Initial exec model.
2425     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2426     ARMConstantPoolValue *CPV =
2427       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2428                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2429                                       true);
2430     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2431     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2432     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2433                          MachinePointerInfo::getConstantPool(),
2434                          false, false, false, 0);
2435     Chain = Offset.getValue(1);
2436
2437     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2438     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2439
2440     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2441                          MachinePointerInfo::getConstantPool(),
2442                          false, false, false, 0);
2443   } else {
2444     // local exec model
2445     assert(model == TLSModel::LocalExec);
2446     ARMConstantPoolValue *CPV =
2447       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2448     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2449     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2450     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2451                          MachinePointerInfo::getConstantPool(),
2452                          false, false, false, 0);
2453   }
2454
2455   // The address of the thread local variable is the add of the thread
2456   // pointer with the offset of the variable.
2457   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2458 }
2459
2460 SDValue
2461 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2462   // TODO: implement the "local dynamic" model
2463   assert(Subtarget->isTargetELF() &&
2464          "TLS not implemented for non-ELF targets");
2465   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2466
2467   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2468
2469   switch (model) {
2470     case TLSModel::GeneralDynamic:
2471     case TLSModel::LocalDynamic:
2472       return LowerToTLSGeneralDynamicModel(GA, DAG);
2473     case TLSModel::InitialExec:
2474     case TLSModel::LocalExec:
2475       return LowerToTLSExecModels(GA, DAG, model);
2476   }
2477   llvm_unreachable("bogus TLS model");
2478 }
2479
2480 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2481                                                  SelectionDAG &DAG) const {
2482   EVT PtrVT = getPointerTy();
2483   SDLoc dl(Op);
2484   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2485   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2486     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2487     ARMConstantPoolValue *CPV =
2488       ARMConstantPoolConstant::Create(GV,
2489                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2490     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2491     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2492     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2493                                  CPAddr,
2494                                  MachinePointerInfo::getConstantPool(),
2495                                  false, false, false, 0);
2496     SDValue Chain = Result.getValue(1);
2497     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2498     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2499     if (!UseGOTOFF)
2500       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2501                            MachinePointerInfo::getGOT(),
2502                            false, false, false, 0);
2503     return Result;
2504   }
2505
2506   // If we have T2 ops, we can materialize the address directly via movt/movw
2507   // pair. This is always cheaper.
2508   if (Subtarget->useMovt()) {
2509     ++NumMovwMovt;
2510     // FIXME: Once remat is capable of dealing with instructions with register
2511     // operands, expand this into two nodes.
2512     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2513                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2514   } else {
2515     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2516     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2517     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2518                        MachinePointerInfo::getConstantPool(),
2519                        false, false, false, 0);
2520   }
2521 }
2522
2523 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2524                                                     SelectionDAG &DAG) const {
2525   EVT PtrVT = getPointerTy();
2526   SDLoc dl(Op);
2527   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2528   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2529
2530   if (Subtarget->useMovt())
2531     ++NumMovwMovt;
2532
2533   // FIXME: Once remat is capable of dealing with instructions with register
2534   // operands, expand this into multiple nodes
2535   unsigned Wrapper =
2536       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2537
2538   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2539   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2540
2541   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2542     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2543                          MachinePointerInfo::getGOT(), false, false, false, 0);
2544   return Result;
2545 }
2546
2547 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2548                                                     SelectionDAG &DAG) const {
2549   assert(Subtarget->isTargetELF() &&
2550          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2551   MachineFunction &MF = DAG.getMachineFunction();
2552   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2553   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2554   EVT PtrVT = getPointerTy();
2555   SDLoc dl(Op);
2556   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2557   ARMConstantPoolValue *CPV =
2558     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2559                                   ARMPCLabelIndex, PCAdj);
2560   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2561   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2562   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2563                                MachinePointerInfo::getConstantPool(),
2564                                false, false, false, 0);
2565   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2566   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2567 }
2568
2569 SDValue
2570 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2571   SDLoc dl(Op);
2572   SDValue Val = DAG.getConstant(0, MVT::i32);
2573   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2574                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2575                      Op.getOperand(1), Val);
2576 }
2577
2578 SDValue
2579 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2580   SDLoc dl(Op);
2581   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2582                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2583 }
2584
2585 SDValue
2586 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2587                                           const ARMSubtarget *Subtarget) const {
2588   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2589   SDLoc dl(Op);
2590   switch (IntNo) {
2591   default: return SDValue();    // Don't custom lower most intrinsics.
2592   case Intrinsic::arm_thread_pointer: {
2593     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2594     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2595   }
2596   case Intrinsic::eh_sjlj_lsda: {
2597     MachineFunction &MF = DAG.getMachineFunction();
2598     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2599     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2600     EVT PtrVT = getPointerTy();
2601     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2602     SDValue CPAddr;
2603     unsigned PCAdj = (RelocM != Reloc::PIC_)
2604       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2605     ARMConstantPoolValue *CPV =
2606       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2607                                       ARMCP::CPLSDA, PCAdj);
2608     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2609     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2610     SDValue Result =
2611       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2612                   MachinePointerInfo::getConstantPool(),
2613                   false, false, false, 0);
2614
2615     if (RelocM == Reloc::PIC_) {
2616       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2617       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2618     }
2619     return Result;
2620   }
2621   case Intrinsic::arm_neon_vmulls:
2622   case Intrinsic::arm_neon_vmullu: {
2623     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2624       ? ARMISD::VMULLs : ARMISD::VMULLu;
2625     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2626                        Op.getOperand(1), Op.getOperand(2));
2627   }
2628   }
2629 }
2630
2631 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2632                                  const ARMSubtarget *Subtarget) {
2633   // FIXME: handle "fence singlethread" more efficiently.
2634   SDLoc dl(Op);
2635   if (!Subtarget->hasDataBarrier()) {
2636     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2637     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2638     // here.
2639     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2640            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2641     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2642                        DAG.getConstant(0, MVT::i32));
2643   }
2644
2645   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2646   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2647   unsigned Domain = ARM_MB::ISH;
2648   if (Subtarget->isMClass()) {
2649     // Only a full system barrier exists in the M-class architectures.
2650     Domain = ARM_MB::SY;
2651   } else if (Subtarget->isSwift() && Ord == Release) {
2652     // Swift happens to implement ISHST barriers in a way that's compatible with
2653     // Release semantics but weaker than ISH so we'd be fools not to use
2654     // it. Beware: other processors probably don't!
2655     Domain = ARM_MB::ISHST;
2656   }
2657
2658   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2659                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2660                      DAG.getConstant(Domain, MVT::i32));
2661 }
2662
2663 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2664                              const ARMSubtarget *Subtarget) {
2665   // ARM pre v5TE and Thumb1 does not have preload instructions.
2666   if (!(Subtarget->isThumb2() ||
2667         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2668     // Just preserve the chain.
2669     return Op.getOperand(0);
2670
2671   SDLoc dl(Op);
2672   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2673   if (!isRead &&
2674       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2675     // ARMv7 with MP extension has PLDW.
2676     return Op.getOperand(0);
2677
2678   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2679   if (Subtarget->isThumb()) {
2680     // Invert the bits.
2681     isRead = ~isRead & 1;
2682     isData = ~isData & 1;
2683   }
2684
2685   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2686                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2687                      DAG.getConstant(isData, MVT::i32));
2688 }
2689
2690 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2691   MachineFunction &MF = DAG.getMachineFunction();
2692   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2693
2694   // vastart just stores the address of the VarArgsFrameIndex slot into the
2695   // memory location argument.
2696   SDLoc dl(Op);
2697   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2698   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2699   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2700   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2701                       MachinePointerInfo(SV), false, false, 0);
2702 }
2703
2704 SDValue
2705 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2706                                         SDValue &Root, SelectionDAG &DAG,
2707                                         SDLoc dl) const {
2708   MachineFunction &MF = DAG.getMachineFunction();
2709   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2710
2711   const TargetRegisterClass *RC;
2712   if (AFI->isThumb1OnlyFunction())
2713     RC = &ARM::tGPRRegClass;
2714   else
2715     RC = &ARM::GPRRegClass;
2716
2717   // Transform the arguments stored in physical registers into virtual ones.
2718   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2719   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2720
2721   SDValue ArgValue2;
2722   if (NextVA.isMemLoc()) {
2723     MachineFrameInfo *MFI = MF.getFrameInfo();
2724     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2725
2726     // Create load node to retrieve arguments from the stack.
2727     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2728     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2729                             MachinePointerInfo::getFixedStack(FI),
2730                             false, false, false, 0);
2731   } else {
2732     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2733     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2734   }
2735
2736   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2737 }
2738
2739 void
2740 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2741                                   unsigned InRegsParamRecordIdx,
2742                                   unsigned ArgSize,
2743                                   unsigned &ArgRegsSize,
2744                                   unsigned &ArgRegsSaveSize)
2745   const {
2746   unsigned NumGPRs;
2747   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2748     unsigned RBegin, REnd;
2749     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2750     NumGPRs = REnd - RBegin;
2751   } else {
2752     unsigned int firstUnalloced;
2753     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2754                                                 sizeof(GPRArgRegs) /
2755                                                 sizeof(GPRArgRegs[0]));
2756     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2757   }
2758
2759   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2760   ArgRegsSize = NumGPRs * 4;
2761
2762   // If parameter is split between stack and GPRs...
2763   if (NumGPRs && Align == 8 &&
2764       (ArgRegsSize < ArgSize ||
2765         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2766     // Add padding for part of param recovered from GPRs, so
2767     // its last byte must be at address K*8 - 1.
2768     // We need to do it, since remained (stack) part of parameter has
2769     // stack alignment, and we need to "attach" "GPRs head" without gaps
2770     // to it:
2771     // Stack:
2772     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2773     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2774     //
2775     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2776     unsigned Padding =
2777         ((ArgRegsSize + AFI->getArgRegsSaveSize() + Align - 1) & ~(Align-1)) -
2778         (ArgRegsSize + AFI->getArgRegsSaveSize());
2779     ArgRegsSaveSize = ArgRegsSize + Padding;
2780   } else
2781     // We don't need to extend regs save size for byval parameters if they
2782     // are passed via GPRs only.
2783     ArgRegsSaveSize = ArgRegsSize;
2784 }
2785
2786 // The remaining GPRs hold either the beginning of variable-argument
2787 // data, or the beginning of an aggregate passed by value (usually
2788 // byval).  Either way, we allocate stack slots adjacent to the data
2789 // provided by our caller, and store the unallocated registers there.
2790 // If this is a variadic function, the va_list pointer will begin with
2791 // these values; otherwise, this reassembles a (byval) structure that
2792 // was split between registers and memory.
2793 // Return: The frame index registers were stored into.
2794 int
2795 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2796                                   SDLoc dl, SDValue &Chain,
2797                                   const Value *OrigArg,
2798                                   unsigned InRegsParamRecordIdx,
2799                                   unsigned OffsetFromOrigArg,
2800                                   unsigned ArgOffset,
2801                                   unsigned ArgSize,
2802                                   bool ForceMutable) const {
2803
2804   // Currently, two use-cases possible:
2805   // Case #1. Non var-args function, and we meet first byval parameter.
2806   //          Setup first unallocated register as first byval register;
2807   //          eat all remained registers
2808   //          (these two actions are performed by HandleByVal method).
2809   //          Then, here, we initialize stack frame with
2810   //          "store-reg" instructions.
2811   // Case #2. Var-args function, that doesn't contain byval parameters.
2812   //          The same: eat all remained unallocated registers,
2813   //          initialize stack frame.
2814
2815   MachineFunction &MF = DAG.getMachineFunction();
2816   MachineFrameInfo *MFI = MF.getFrameInfo();
2817   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2818   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2819   unsigned RBegin, REnd;
2820   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2821     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2822     firstRegToSaveIndex = RBegin - ARM::R0;
2823     lastRegToSaveIndex = REnd - ARM::R0;
2824   } else {
2825     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2826       (GPRArgRegs, array_lengthof(GPRArgRegs));
2827     lastRegToSaveIndex = 4;
2828   }
2829
2830   unsigned ArgRegsSize, ArgRegsSaveSize;
2831   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2832                  ArgRegsSize, ArgRegsSaveSize);
2833
2834   // Store any by-val regs to their spots on the stack so that they may be
2835   // loaded by deferencing the result of formal parameter pointer or va_next.
2836   // Note: once stack area for byval/varargs registers
2837   // was initialized, it can't be initialized again.
2838   if (ArgRegsSaveSize) {
2839
2840     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2841
2842     if (Padding) {
2843       assert(AFI->getStoredByValParamsPadding() == 0 &&
2844              "The only parameter may be padded.");
2845       AFI->setStoredByValParamsPadding(Padding);
2846     }
2847
2848     int FrameIndex = MFI->CreateFixedObject(
2849                       ArgRegsSaveSize,
2850                       Padding + ArgOffset,
2851                       false);
2852     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2853
2854     SmallVector<SDValue, 4> MemOps;
2855     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2856          ++firstRegToSaveIndex, ++i) {
2857       const TargetRegisterClass *RC;
2858       if (AFI->isThumb1OnlyFunction())
2859         RC = &ARM::tGPRRegClass;
2860       else
2861         RC = &ARM::GPRRegClass;
2862
2863       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2864       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2865       SDValue Store =
2866         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2867                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2868                      false, false, 0);
2869       MemOps.push_back(Store);
2870       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2871                         DAG.getConstant(4, getPointerTy()));
2872     }
2873
2874     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2875
2876     if (!MemOps.empty())
2877       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2878                           &MemOps[0], MemOps.size());
2879     return FrameIndex;
2880   } else
2881     // This will point to the next argument passed via stack.
2882     return MFI->CreateFixedObject(
2883         4, AFI->getStoredByValParamsPadding() + ArgOffset, !ForceMutable);
2884 }
2885
2886 // Setup stack frame, the va_list pointer will start from.
2887 void
2888 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2889                                         SDLoc dl, SDValue &Chain,
2890                                         unsigned ArgOffset,
2891                                         bool ForceMutable) const {
2892   MachineFunction &MF = DAG.getMachineFunction();
2893   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2894
2895   // Try to store any remaining integer argument regs
2896   // to their spots on the stack so that they may be loaded by deferencing
2897   // the result of va_next.
2898   // If there is no regs to be stored, just point address after last
2899   // argument passed via stack.
2900   int FrameIndex =
2901     StoreByValRegs(CCInfo, DAG, dl, Chain, 0, CCInfo.getInRegsParamsCount(),
2902                    0, ArgOffset, 0, ForceMutable);
2903
2904   AFI->setVarArgsFrameIndex(FrameIndex);
2905 }
2906
2907 SDValue
2908 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2909                                         CallingConv::ID CallConv, bool isVarArg,
2910                                         const SmallVectorImpl<ISD::InputArg>
2911                                           &Ins,
2912                                         SDLoc dl, SelectionDAG &DAG,
2913                                         SmallVectorImpl<SDValue> &InVals)
2914                                           const {
2915   MachineFunction &MF = DAG.getMachineFunction();
2916   MachineFrameInfo *MFI = MF.getFrameInfo();
2917
2918   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2919
2920   // Assign locations to all of the incoming arguments.
2921   SmallVector<CCValAssign, 16> ArgLocs;
2922   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2923                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2924   CCInfo.AnalyzeFormalArguments(Ins,
2925                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2926                                                   isVarArg));
2927
2928   SmallVector<SDValue, 16> ArgValues;
2929   int lastInsIndex = -1;
2930   SDValue ArgValue;
2931   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2932   unsigned CurArgIdx = 0;
2933
2934   // Initially ArgRegsSaveSize is zero.
2935   // Then we increase this value each time we meet byval parameter.
2936   // We also increase this value in case of varargs function.
2937   AFI->setArgRegsSaveSize(0);
2938
2939   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2940     CCValAssign &VA = ArgLocs[i];
2941     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2942     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2943     // Arguments stored in registers.
2944     if (VA.isRegLoc()) {
2945       EVT RegVT = VA.getLocVT();
2946
2947       if (VA.needsCustom()) {
2948         // f64 and vector types are split up into multiple registers or
2949         // combinations of registers and stack slots.
2950         if (VA.getLocVT() == MVT::v2f64) {
2951           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2952                                                    Chain, DAG, dl);
2953           VA = ArgLocs[++i]; // skip ahead to next loc
2954           SDValue ArgValue2;
2955           if (VA.isMemLoc()) {
2956             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2957             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2958             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2959                                     MachinePointerInfo::getFixedStack(FI),
2960                                     false, false, false, 0);
2961           } else {
2962             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2963                                              Chain, DAG, dl);
2964           }
2965           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2966           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2967                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2968           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2969                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2970         } else
2971           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2972
2973       } else {
2974         const TargetRegisterClass *RC;
2975
2976         if (RegVT == MVT::f32)
2977           RC = &ARM::SPRRegClass;
2978         else if (RegVT == MVT::f64)
2979           RC = &ARM::DPRRegClass;
2980         else if (RegVT == MVT::v2f64)
2981           RC = &ARM::QPRRegClass;
2982         else if (RegVT == MVT::i32)
2983           RC = AFI->isThumb1OnlyFunction() ?
2984             (const TargetRegisterClass*)&ARM::tGPRRegClass :
2985             (const TargetRegisterClass*)&ARM::GPRRegClass;
2986         else
2987           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2988
2989         // Transform the arguments in physical registers into virtual ones.
2990         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2991         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2992       }
2993
2994       // If this is an 8 or 16-bit value, it is really passed promoted
2995       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2996       // truncate to the right size.
2997       switch (VA.getLocInfo()) {
2998       default: llvm_unreachable("Unknown loc info!");
2999       case CCValAssign::Full: break;
3000       case CCValAssign::BCvt:
3001         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3002         break;
3003       case CCValAssign::SExt:
3004         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3005                                DAG.getValueType(VA.getValVT()));
3006         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3007         break;
3008       case CCValAssign::ZExt:
3009         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3010                                DAG.getValueType(VA.getValVT()));
3011         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3012         break;
3013       }
3014
3015       InVals.push_back(ArgValue);
3016
3017     } else { // VA.isRegLoc()
3018
3019       // sanity check
3020       assert(VA.isMemLoc());
3021       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3022
3023       int index = ArgLocs[i].getValNo();
3024
3025       // Some Ins[] entries become multiple ArgLoc[] entries.
3026       // Process them only once.
3027       if (index != lastInsIndex)
3028         {
3029           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3030           // FIXME: For now, all byval parameter objects are marked mutable.
3031           // This can be changed with more analysis.
3032           // In case of tail call optimization mark all arguments mutable.
3033           // Since they could be overwritten by lowering of arguments in case of
3034           // a tail call.
3035           if (Flags.isByVal()) {
3036             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3037             int FrameIndex = StoreByValRegs(
3038                 CCInfo, DAG, dl, Chain, CurOrigArg,
3039                 CurByValIndex,
3040                 Ins[VA.getValNo()].PartOffset,
3041                 VA.getLocMemOffset(),
3042                 Flags.getByValSize(),
3043                 true /*force mutable frames*/);
3044             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3045             CCInfo.nextInRegsParam();
3046           } else {
3047             unsigned FIOffset = VA.getLocMemOffset() +
3048                                 AFI->getStoredByValParamsPadding();
3049             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3050                                             FIOffset, true);
3051
3052             // Create load nodes to retrieve arguments from the stack.
3053             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3054             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3055                                          MachinePointerInfo::getFixedStack(FI),
3056                                          false, false, false, 0));
3057           }
3058           lastInsIndex = index;
3059         }
3060     }
3061   }
3062
3063   // varargs
3064   if (isVarArg)
3065     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3066                          CCInfo.getNextStackOffset());
3067
3068   return Chain;
3069 }
3070
3071 /// isFloatingPointZero - Return true if this is +0.0.
3072 static bool isFloatingPointZero(SDValue Op) {
3073   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3074     return CFP->getValueAPF().isPosZero();
3075   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3076     // Maybe this has already been legalized into the constant pool?
3077     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3078       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3079       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3080         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3081           return CFP->getValueAPF().isPosZero();
3082     }
3083   }
3084   return false;
3085 }
3086
3087 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3088 /// the given operands.
3089 SDValue
3090 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3091                              SDValue &ARMcc, SelectionDAG &DAG,
3092                              SDLoc dl) const {
3093   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3094     unsigned C = RHSC->getZExtValue();
3095     if (!isLegalICmpImmediate(C)) {
3096       // Constant does not fit, try adjusting it by one?
3097       switch (CC) {
3098       default: break;
3099       case ISD::SETLT:
3100       case ISD::SETGE:
3101         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3102           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3103           RHS = DAG.getConstant(C-1, MVT::i32);
3104         }
3105         break;
3106       case ISD::SETULT:
3107       case ISD::SETUGE:
3108         if (C != 0 && isLegalICmpImmediate(C-1)) {
3109           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3110           RHS = DAG.getConstant(C-1, MVT::i32);
3111         }
3112         break;
3113       case ISD::SETLE:
3114       case ISD::SETGT:
3115         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3116           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3117           RHS = DAG.getConstant(C+1, MVT::i32);
3118         }
3119         break;
3120       case ISD::SETULE:
3121       case ISD::SETUGT:
3122         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3123           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3124           RHS = DAG.getConstant(C+1, MVT::i32);
3125         }
3126         break;
3127       }
3128     }
3129   }
3130
3131   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3132   ARMISD::NodeType CompareType;
3133   switch (CondCode) {
3134   default:
3135     CompareType = ARMISD::CMP;
3136     break;
3137   case ARMCC::EQ:
3138   case ARMCC::NE:
3139     // Uses only Z Flag
3140     CompareType = ARMISD::CMPZ;
3141     break;
3142   }
3143   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3144   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3145 }
3146
3147 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3148 SDValue
3149 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3150                              SDLoc dl) const {
3151   SDValue Cmp;
3152   if (!isFloatingPointZero(RHS))
3153     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3154   else
3155     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3156   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3157 }
3158
3159 /// duplicateCmp - Glue values can have only one use, so this function
3160 /// duplicates a comparison node.
3161 SDValue
3162 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3163   unsigned Opc = Cmp.getOpcode();
3164   SDLoc DL(Cmp);
3165   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3166     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3167
3168   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3169   Cmp = Cmp.getOperand(0);
3170   Opc = Cmp.getOpcode();
3171   if (Opc == ARMISD::CMPFP)
3172     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3173   else {
3174     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3175     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3176   }
3177   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3178 }
3179
3180 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3181   SDValue Cond = Op.getOperand(0);
3182   SDValue SelectTrue = Op.getOperand(1);
3183   SDValue SelectFalse = Op.getOperand(2);
3184   SDLoc dl(Op);
3185
3186   // Convert:
3187   //
3188   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3189   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3190   //
3191   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3192     const ConstantSDNode *CMOVTrue =
3193       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3194     const ConstantSDNode *CMOVFalse =
3195       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3196
3197     if (CMOVTrue && CMOVFalse) {
3198       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3199       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3200
3201       SDValue True;
3202       SDValue False;
3203       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3204         True = SelectTrue;
3205         False = SelectFalse;
3206       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3207         True = SelectFalse;
3208         False = SelectTrue;
3209       }
3210
3211       if (True.getNode() && False.getNode()) {
3212         EVT VT = Op.getValueType();
3213         SDValue ARMcc = Cond.getOperand(2);
3214         SDValue CCR = Cond.getOperand(3);
3215         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3216         assert(True.getValueType() == VT);
3217         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3218       }
3219     }
3220   }
3221
3222   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3223   // undefined bits before doing a full-word comparison with zero.
3224   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3225                      DAG.getConstant(1, Cond.getValueType()));
3226
3227   return DAG.getSelectCC(dl, Cond,
3228                          DAG.getConstant(0, Cond.getValueType()),
3229                          SelectTrue, SelectFalse, ISD::SETNE);
3230 }
3231
3232 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3233   if (CC == ISD::SETNE)
3234     return ISD::SETEQ;
3235   return ISD::getSetCCSwappedOperands(CC);
3236 }
3237
3238 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3239                                  bool &swpCmpOps, bool &swpVselOps) {
3240   // Start by selecting the GE condition code for opcodes that return true for
3241   // 'equality'
3242   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3243       CC == ISD::SETULE)
3244     CondCode = ARMCC::GE;
3245
3246   // and GT for opcodes that return false for 'equality'.
3247   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3248            CC == ISD::SETULT)
3249     CondCode = ARMCC::GT;
3250
3251   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3252   // to swap the compare operands.
3253   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3254       CC == ISD::SETULT)
3255     swpCmpOps = true;
3256
3257   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3258   // If we have an unordered opcode, we need to swap the operands to the VSEL
3259   // instruction (effectively negating the condition).
3260   //
3261   // This also has the effect of swapping which one of 'less' or 'greater'
3262   // returns true, so we also swap the compare operands. It also switches
3263   // whether we return true for 'equality', so we compensate by picking the
3264   // opposite condition code to our original choice.
3265   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3266       CC == ISD::SETUGT) {
3267     swpCmpOps = !swpCmpOps;
3268     swpVselOps = !swpVselOps;
3269     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3270   }
3271
3272   // 'ordered' is 'anything but unordered', so use the VS condition code and
3273   // swap the VSEL operands.
3274   if (CC == ISD::SETO) {
3275     CondCode = ARMCC::VS;
3276     swpVselOps = true;
3277   }
3278
3279   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3280   // code and swap the VSEL operands.
3281   if (CC == ISD::SETUNE) {
3282     CondCode = ARMCC::EQ;
3283     swpVselOps = true;
3284   }
3285 }
3286
3287 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3288   EVT VT = Op.getValueType();
3289   SDValue LHS = Op.getOperand(0);
3290   SDValue RHS = Op.getOperand(1);
3291   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3292   SDValue TrueVal = Op.getOperand(2);
3293   SDValue FalseVal = Op.getOperand(3);
3294   SDLoc dl(Op);
3295
3296   if (LHS.getValueType() == MVT::i32) {
3297     // Try to generate VSEL on ARMv8.
3298     // The VSEL instruction can't use all the usual ARM condition
3299     // codes: it only has two bits to select the condition code, so it's
3300     // constrained to use only GE, GT, VS and EQ.
3301     //
3302     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3303     // swap the operands of the previous compare instruction (effectively
3304     // inverting the compare condition, swapping 'less' and 'greater') and
3305     // sometimes need to swap the operands to the VSEL (which inverts the
3306     // condition in the sense of firing whenever the previous condition didn't)
3307     if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3308                                       TrueVal.getValueType() == MVT::f64)) {
3309       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3310       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3311           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3312         CC = getInverseCCForVSEL(CC);
3313         std::swap(TrueVal, FalseVal);
3314       }
3315     }
3316
3317     SDValue ARMcc;
3318     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3319     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3320     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3321                        Cmp);
3322   }
3323
3324   ARMCC::CondCodes CondCode, CondCode2;
3325   FPCCToARMCC(CC, CondCode, CondCode2);
3326
3327   // Try to generate VSEL on ARMv8.
3328   if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3329                                     TrueVal.getValueType() == MVT::f64)) {
3330     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3331     // same operands, as follows:
3332     //   c = fcmp [ogt, olt, ugt, ult] a, b
3333     //   select c, a, b
3334     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3335     // handled differently than the original code sequence.
3336     if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3337         RHS == FalseVal) {
3338       if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3339         return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3340       if (CC == ISD::SETOLT || CC == ISD::SETULT)
3341         return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3342     }
3343
3344     bool swpCmpOps = false;
3345     bool swpVselOps = false;
3346     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3347
3348     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3349         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3350       if (swpCmpOps)
3351         std::swap(LHS, RHS);
3352       if (swpVselOps)
3353         std::swap(TrueVal, FalseVal);
3354     }
3355   }
3356
3357   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3358   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3359   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3360   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3361                                ARMcc, CCR, Cmp);
3362   if (CondCode2 != ARMCC::AL) {
3363     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3364     // FIXME: Needs another CMP because flag can have but one use.
3365     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3366     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3367                          Result, TrueVal, ARMcc2, CCR, Cmp2);
3368   }
3369   return Result;
3370 }
3371
3372 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3373 /// to morph to an integer compare sequence.
3374 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3375                            const ARMSubtarget *Subtarget) {
3376   SDNode *N = Op.getNode();
3377   if (!N->hasOneUse())
3378     // Otherwise it requires moving the value from fp to integer registers.
3379     return false;
3380   if (!N->getNumValues())
3381     return false;
3382   EVT VT = Op.getValueType();
3383   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3384     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3385     // vmrs are very slow, e.g. cortex-a8.
3386     return false;
3387
3388   if (isFloatingPointZero(Op)) {
3389     SeenZero = true;
3390     return true;
3391   }
3392   return ISD::isNormalLoad(N);
3393 }
3394
3395 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3396   if (isFloatingPointZero(Op))
3397     return DAG.getConstant(0, MVT::i32);
3398
3399   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3400     return DAG.getLoad(MVT::i32, SDLoc(Op),
3401                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3402                        Ld->isVolatile(), Ld->isNonTemporal(),
3403                        Ld->isInvariant(), Ld->getAlignment());
3404
3405   llvm_unreachable("Unknown VFP cmp argument!");
3406 }
3407
3408 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3409                            SDValue &RetVal1, SDValue &RetVal2) {
3410   if (isFloatingPointZero(Op)) {
3411     RetVal1 = DAG.getConstant(0, MVT::i32);
3412     RetVal2 = DAG.getConstant(0, MVT::i32);
3413     return;
3414   }
3415
3416   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3417     SDValue Ptr = Ld->getBasePtr();
3418     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3419                           Ld->getChain(), Ptr,
3420                           Ld->getPointerInfo(),
3421                           Ld->isVolatile(), Ld->isNonTemporal(),
3422                           Ld->isInvariant(), Ld->getAlignment());
3423
3424     EVT PtrType = Ptr.getValueType();
3425     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3426     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3427                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3428     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3429                           Ld->getChain(), NewPtr,
3430                           Ld->getPointerInfo().getWithOffset(4),
3431                           Ld->isVolatile(), Ld->isNonTemporal(),
3432                           Ld->isInvariant(), NewAlign);
3433     return;
3434   }
3435
3436   llvm_unreachable("Unknown VFP cmp argument!");
3437 }
3438
3439 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3440 /// f32 and even f64 comparisons to integer ones.
3441 SDValue
3442 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3443   SDValue Chain = Op.getOperand(0);
3444   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3445   SDValue LHS = Op.getOperand(2);
3446   SDValue RHS = Op.getOperand(3);
3447   SDValue Dest = Op.getOperand(4);
3448   SDLoc dl(Op);
3449
3450   bool LHSSeenZero = false;
3451   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3452   bool RHSSeenZero = false;
3453   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3454   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3455     // If unsafe fp math optimization is enabled and there are no other uses of
3456     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3457     // to an integer comparison.
3458     if (CC == ISD::SETOEQ)
3459       CC = ISD::SETEQ;
3460     else if (CC == ISD::SETUNE)
3461       CC = ISD::SETNE;
3462
3463     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3464     SDValue ARMcc;
3465     if (LHS.getValueType() == MVT::f32) {
3466       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3467                         bitcastf32Toi32(LHS, DAG), Mask);
3468       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3469                         bitcastf32Toi32(RHS, DAG), Mask);
3470       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3471       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3472       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3473                          Chain, Dest, ARMcc, CCR, Cmp);
3474     }
3475
3476     SDValue LHS1, LHS2;
3477     SDValue RHS1, RHS2;
3478     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3479     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3480     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3481     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3482     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3483     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3484     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3485     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3486     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3487   }
3488
3489   return SDValue();
3490 }
3491
3492 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3493   SDValue Chain = Op.getOperand(0);
3494   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3495   SDValue LHS = Op.getOperand(2);
3496   SDValue RHS = Op.getOperand(3);
3497   SDValue Dest = Op.getOperand(4);
3498   SDLoc dl(Op);
3499
3500   if (LHS.getValueType() == MVT::i32) {
3501     SDValue ARMcc;
3502     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3503     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3504     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3505                        Chain, Dest, ARMcc, CCR, Cmp);
3506   }
3507
3508   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3509
3510   if (getTargetMachine().Options.UnsafeFPMath &&
3511       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3512        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3513     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3514     if (Result.getNode())
3515       return Result;
3516   }
3517
3518   ARMCC::CondCodes CondCode, CondCode2;
3519   FPCCToARMCC(CC, CondCode, CondCode2);
3520
3521   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3522   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3523   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3524   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3525   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3526   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3527   if (CondCode2 != ARMCC::AL) {
3528     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3529     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3530     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3531   }
3532   return Res;
3533 }
3534
3535 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3536   SDValue Chain = Op.getOperand(0);
3537   SDValue Table = Op.getOperand(1);
3538   SDValue Index = Op.getOperand(2);
3539   SDLoc dl(Op);
3540
3541   EVT PTy = getPointerTy();
3542   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3543   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3544   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3545   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3546   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3547   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3548   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3549   if (Subtarget->isThumb2()) {
3550     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3551     // which does another jump to the destination. This also makes it easier
3552     // to translate it to TBB / TBH later.
3553     // FIXME: This might not work if the function is extremely large.
3554     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3555                        Addr, Op.getOperand(2), JTI, UId);
3556   }
3557   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3558     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3559                        MachinePointerInfo::getJumpTable(),
3560                        false, false, false, 0);
3561     Chain = Addr.getValue(1);
3562     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3563     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3564   } else {
3565     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3566                        MachinePointerInfo::getJumpTable(),
3567                        false, false, false, 0);
3568     Chain = Addr.getValue(1);
3569     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3570   }
3571 }
3572
3573 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3574   EVT VT = Op.getValueType();
3575   SDLoc dl(Op);
3576
3577   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3578     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3579       return Op;
3580     return DAG.UnrollVectorOp(Op.getNode());
3581   }
3582
3583   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3584          "Invalid type for custom lowering!");
3585   if (VT != MVT::v4i16)
3586     return DAG.UnrollVectorOp(Op.getNode());
3587
3588   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3589   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3590 }
3591
3592 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3593   EVT VT = Op.getValueType();
3594   if (VT.isVector())
3595     return LowerVectorFP_TO_INT(Op, DAG);
3596
3597   SDLoc dl(Op);
3598   unsigned Opc;
3599
3600   switch (Op.getOpcode()) {
3601   default: llvm_unreachable("Invalid opcode!");
3602   case ISD::FP_TO_SINT:
3603     Opc = ARMISD::FTOSI;
3604     break;
3605   case ISD::FP_TO_UINT:
3606     Opc = ARMISD::FTOUI;
3607     break;
3608   }
3609   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3610   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3611 }
3612
3613 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3614   EVT VT = Op.getValueType();
3615   SDLoc dl(Op);
3616
3617   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3618     if (VT.getVectorElementType() == MVT::f32)
3619       return Op;
3620     return DAG.UnrollVectorOp(Op.getNode());
3621   }
3622
3623   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3624          "Invalid type for custom lowering!");
3625   if (VT != MVT::v4f32)
3626     return DAG.UnrollVectorOp(Op.getNode());
3627
3628   unsigned CastOpc;
3629   unsigned Opc;
3630   switch (Op.getOpcode()) {
3631   default: llvm_unreachable("Invalid opcode!");
3632   case ISD::SINT_TO_FP:
3633     CastOpc = ISD::SIGN_EXTEND;
3634     Opc = ISD::SINT_TO_FP;
3635     break;
3636   case ISD::UINT_TO_FP:
3637     CastOpc = ISD::ZERO_EXTEND;
3638     Opc = ISD::UINT_TO_FP;
3639     break;
3640   }
3641
3642   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3643   return DAG.getNode(Opc, dl, VT, Op);
3644 }
3645
3646 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3647   EVT VT = Op.getValueType();
3648   if (VT.isVector())
3649     return LowerVectorINT_TO_FP(Op, DAG);
3650
3651   SDLoc dl(Op);
3652   unsigned Opc;
3653
3654   switch (Op.getOpcode()) {
3655   default: llvm_unreachable("Invalid opcode!");
3656   case ISD::SINT_TO_FP:
3657     Opc = ARMISD::SITOF;
3658     break;
3659   case ISD::UINT_TO_FP:
3660     Opc = ARMISD::UITOF;
3661     break;
3662   }
3663
3664   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3665   return DAG.getNode(Opc, dl, VT, Op);
3666 }
3667
3668 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3669   // Implement fcopysign with a fabs and a conditional fneg.
3670   SDValue Tmp0 = Op.getOperand(0);
3671   SDValue Tmp1 = Op.getOperand(1);
3672   SDLoc dl(Op);
3673   EVT VT = Op.getValueType();
3674   EVT SrcVT = Tmp1.getValueType();
3675   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3676     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3677   bool UseNEON = !InGPR && Subtarget->hasNEON();
3678
3679   if (UseNEON) {
3680     // Use VBSL to copy the sign bit.
3681     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3682     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3683                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3684     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3685     if (VT == MVT::f64)
3686       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3687                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3688                          DAG.getConstant(32, MVT::i32));
3689     else /*if (VT == MVT::f32)*/
3690       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3691     if (SrcVT == MVT::f32) {
3692       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3693       if (VT == MVT::f64)
3694         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3695                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3696                            DAG.getConstant(32, MVT::i32));
3697     } else if (VT == MVT::f32)
3698       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3699                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3700                          DAG.getConstant(32, MVT::i32));
3701     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3702     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3703
3704     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3705                                             MVT::i32);
3706     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3707     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3708                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3709
3710     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3711                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3712                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3713     if (VT == MVT::f32) {
3714       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3715       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3716                         DAG.getConstant(0, MVT::i32));
3717     } else {
3718       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3719     }
3720
3721     return Res;
3722   }
3723
3724   // Bitcast operand 1 to i32.
3725   if (SrcVT == MVT::f64)
3726     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3727                        &Tmp1, 1).getValue(1);
3728   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3729
3730   // Or in the signbit with integer operations.
3731   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3732   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3733   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3734   if (VT == MVT::f32) {
3735     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3736                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3737     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3738                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3739   }
3740
3741   // f64: Or the high part with signbit and then combine two parts.
3742   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3743                      &Tmp0, 1);
3744   SDValue Lo = Tmp0.getValue(0);
3745   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3746   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3747   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3748 }
3749
3750 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3751   MachineFunction &MF = DAG.getMachineFunction();
3752   MachineFrameInfo *MFI = MF.getFrameInfo();
3753   MFI->setReturnAddressIsTaken(true);
3754
3755   EVT VT = Op.getValueType();
3756   SDLoc dl(Op);
3757   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3758   if (Depth) {
3759     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3760     SDValue Offset = DAG.getConstant(4, MVT::i32);
3761     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3762                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3763                        MachinePointerInfo(), false, false, false, 0);
3764   }
3765
3766   // Return LR, which contains the return address. Mark it an implicit live-in.
3767   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3768   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3769 }
3770
3771 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3772   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3773   MFI->setFrameAddressIsTaken(true);
3774
3775   EVT VT = Op.getValueType();
3776   SDLoc dl(Op);  // FIXME probably not meaningful
3777   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3778   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3779     ? ARM::R7 : ARM::R11;
3780   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3781   while (Depth--)
3782     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3783                             MachinePointerInfo(),
3784                             false, false, false, 0);
3785   return FrameAddr;
3786 }
3787
3788 /// ExpandBITCAST - If the target supports VFP, this function is called to
3789 /// expand a bit convert where either the source or destination type is i64 to
3790 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3791 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3792 /// vectors), since the legalizer won't know what to do with that.
3793 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3794   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3795   SDLoc dl(N);
3796   SDValue Op = N->getOperand(0);
3797
3798   // This function is only supposed to be called for i64 types, either as the
3799   // source or destination of the bit convert.
3800   EVT SrcVT = Op.getValueType();
3801   EVT DstVT = N->getValueType(0);
3802   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3803          "ExpandBITCAST called for non-i64 type");
3804
3805   // Turn i64->f64 into VMOVDRR.
3806   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3807     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3808                              DAG.getConstant(0, MVT::i32));
3809     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3810                              DAG.getConstant(1, MVT::i32));
3811     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3812                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3813   }
3814
3815   // Turn f64->i64 into VMOVRRD.
3816   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3817     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3818                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3819     // Merge the pieces into a single i64 value.
3820     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3821   }
3822
3823   return SDValue();
3824 }
3825
3826 /// getZeroVector - Returns a vector of specified type with all zero elements.
3827 /// Zero vectors are used to represent vector negation and in those cases
3828 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3829 /// not support i64 elements, so sometimes the zero vectors will need to be
3830 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3831 /// zero vector.
3832 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3833   assert(VT.isVector() && "Expected a vector type");
3834   // The canonical modified immediate encoding of a zero vector is....0!
3835   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3836   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3837   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3838   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3839 }
3840
3841 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3842 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3843 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3844                                                 SelectionDAG &DAG) const {
3845   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3846   EVT VT = Op.getValueType();
3847   unsigned VTBits = VT.getSizeInBits();
3848   SDLoc dl(Op);
3849   SDValue ShOpLo = Op.getOperand(0);
3850   SDValue ShOpHi = Op.getOperand(1);
3851   SDValue ShAmt  = Op.getOperand(2);
3852   SDValue ARMcc;
3853   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3854
3855   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3856
3857   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3858                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3859   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3860   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3861                                    DAG.getConstant(VTBits, MVT::i32));
3862   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3863   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3864   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3865
3866   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3867   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3868                           ARMcc, DAG, dl);
3869   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3870   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3871                            CCR, Cmp);
3872
3873   SDValue Ops[2] = { Lo, Hi };
3874   return DAG.getMergeValues(Ops, 2, dl);
3875 }
3876
3877 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3878 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3879 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3880                                                SelectionDAG &DAG) const {
3881   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3882   EVT VT = Op.getValueType();
3883   unsigned VTBits = VT.getSizeInBits();
3884   SDLoc dl(Op);
3885   SDValue ShOpLo = Op.getOperand(0);
3886   SDValue ShOpHi = Op.getOperand(1);
3887   SDValue ShAmt  = Op.getOperand(2);
3888   SDValue ARMcc;
3889
3890   assert(Op.getOpcode() == ISD::SHL_PARTS);
3891   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3892                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3893   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3894   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3895                                    DAG.getConstant(VTBits, MVT::i32));
3896   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3897   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3898
3899   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3900   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3901   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3902                           ARMcc, DAG, dl);
3903   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3904   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3905                            CCR, Cmp);
3906
3907   SDValue Ops[2] = { Lo, Hi };
3908   return DAG.getMergeValues(Ops, 2, dl);
3909 }
3910
3911 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3912                                             SelectionDAG &DAG) const {
3913   // The rounding mode is in bits 23:22 of the FPSCR.
3914   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3915   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3916   // so that the shift + and get folded into a bitfield extract.
3917   SDLoc dl(Op);
3918   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3919                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3920                                               MVT::i32));
3921   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3922                                   DAG.getConstant(1U << 22, MVT::i32));
3923   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3924                               DAG.getConstant(22, MVT::i32));
3925   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3926                      DAG.getConstant(3, MVT::i32));
3927 }
3928
3929 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3930                          const ARMSubtarget *ST) {
3931   EVT VT = N->getValueType(0);
3932   SDLoc dl(N);
3933
3934   if (!ST->hasV6T2Ops())
3935     return SDValue();
3936
3937   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3938   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3939 }
3940
3941 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3942 /// for each 16-bit element from operand, repeated.  The basic idea is to
3943 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3944 ///
3945 /// Trace for v4i16:
3946 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
3947 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3948 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3949 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3950 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
3951 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
3952 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3953 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
3954 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3955   EVT VT = N->getValueType(0);
3956   SDLoc DL(N);
3957
3958   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
3959   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
3960   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
3961   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
3962   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
3963   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
3964 }
3965
3966 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
3967 /// bit-count for each 16-bit element from the operand.  We need slightly
3968 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
3969 /// 64/128-bit registers.
3970 ///
3971 /// Trace for v4i16:
3972 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
3973 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
3974 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
3975 /// v4i16:Extracted = [k0    k1    k2    k3    ]
3976 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
3977   EVT VT = N->getValueType(0);
3978   SDLoc DL(N);
3979
3980   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
3981   if (VT.is64BitVector()) {
3982     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
3983     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
3984                        DAG.getIntPtrConstant(0));
3985   } else {
3986     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
3987                                     BitCounts, DAG.getIntPtrConstant(0));
3988     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
3989   }
3990 }
3991
3992 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
3993 /// bit-count for each 32-bit element from the operand.  The idea here is
3994 /// to split the vector into 16-bit elements, leverage the 16-bit count
3995 /// routine, and then combine the results.
3996 ///
3997 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
3998 /// input    = [v0    v1    ] (vi: 32-bit elements)
3999 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4000 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4001 /// vrev: N0 = [k1 k0 k3 k2 ]
4002 ///            [k0 k1 k2 k3 ]
4003 ///       N1 =+[k1 k0 k3 k2 ]
4004 ///            [k0 k2 k1 k3 ]
4005 ///       N2 =+[k1 k3 k0 k2 ]
4006 ///            [k0    k2    k1    k3    ]
4007 /// Extended =+[k1    k3    k0    k2    ]
4008 ///            [k0    k2    ]
4009 /// Extracted=+[k1    k3    ]
4010 ///
4011 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4012   EVT VT = N->getValueType(0);
4013   SDLoc DL(N);
4014
4015   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4016
4017   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4018   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4019   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4020   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4021   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4022
4023   if (VT.is64BitVector()) {
4024     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4025     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4026                        DAG.getIntPtrConstant(0));
4027   } else {
4028     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4029                                     DAG.getIntPtrConstant(0));
4030     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4031   }
4032 }
4033
4034 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4035                           const ARMSubtarget *ST) {
4036   EVT VT = N->getValueType(0);
4037
4038   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4039   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4040           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4041          "Unexpected type for custom ctpop lowering");
4042
4043   if (VT.getVectorElementType() == MVT::i32)
4044     return lowerCTPOP32BitElements(N, DAG);
4045   else
4046     return lowerCTPOP16BitElements(N, DAG);
4047 }
4048
4049 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4050                           const ARMSubtarget *ST) {
4051   EVT VT = N->getValueType(0);
4052   SDLoc dl(N);
4053
4054   if (!VT.isVector())
4055     return SDValue();
4056
4057   // Lower vector shifts on NEON to use VSHL.
4058   assert(ST->hasNEON() && "unexpected vector shift");
4059
4060   // Left shifts translate directly to the vshiftu intrinsic.
4061   if (N->getOpcode() == ISD::SHL)
4062     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4063                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4064                        N->getOperand(0), N->getOperand(1));
4065
4066   assert((N->getOpcode() == ISD::SRA ||
4067           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4068
4069   // NEON uses the same intrinsics for both left and right shifts.  For
4070   // right shifts, the shift amounts are negative, so negate the vector of
4071   // shift amounts.
4072   EVT ShiftVT = N->getOperand(1).getValueType();
4073   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4074                                      getZeroVector(ShiftVT, DAG, dl),
4075                                      N->getOperand(1));
4076   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4077                              Intrinsic::arm_neon_vshifts :
4078                              Intrinsic::arm_neon_vshiftu);
4079   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4080                      DAG.getConstant(vshiftInt, MVT::i32),
4081                      N->getOperand(0), NegatedCount);
4082 }
4083
4084 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4085                                 const ARMSubtarget *ST) {
4086   EVT VT = N->getValueType(0);
4087   SDLoc dl(N);
4088
4089   // We can get here for a node like i32 = ISD::SHL i32, i64
4090   if (VT != MVT::i64)
4091     return SDValue();
4092
4093   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4094          "Unknown shift to lower!");
4095
4096   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4097   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4098       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4099     return SDValue();
4100
4101   // If we are in thumb mode, we don't have RRX.
4102   if (ST->isThumb1Only()) return SDValue();
4103
4104   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4105   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4106                            DAG.getConstant(0, MVT::i32));
4107   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4108                            DAG.getConstant(1, MVT::i32));
4109
4110   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4111   // captures the result into a carry flag.
4112   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4113   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
4114
4115   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4116   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4117
4118   // Merge the pieces into a single i64 value.
4119  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4120 }
4121
4122 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4123   SDValue TmpOp0, TmpOp1;
4124   bool Invert = false;
4125   bool Swap = false;
4126   unsigned Opc = 0;
4127
4128   SDValue Op0 = Op.getOperand(0);
4129   SDValue Op1 = Op.getOperand(1);
4130   SDValue CC = Op.getOperand(2);
4131   EVT VT = Op.getValueType();
4132   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4133   SDLoc dl(Op);
4134
4135   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4136     switch (SetCCOpcode) {
4137     default: llvm_unreachable("Illegal FP comparison");
4138     case ISD::SETUNE:
4139     case ISD::SETNE:  Invert = true; // Fallthrough
4140     case ISD::SETOEQ:
4141     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4142     case ISD::SETOLT:
4143     case ISD::SETLT: Swap = true; // Fallthrough
4144     case ISD::SETOGT:
4145     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4146     case ISD::SETOLE:
4147     case ISD::SETLE:  Swap = true; // Fallthrough
4148     case ISD::SETOGE:
4149     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4150     case ISD::SETUGE: Swap = true; // Fallthrough
4151     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4152     case ISD::SETUGT: Swap = true; // Fallthrough
4153     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4154     case ISD::SETUEQ: Invert = true; // Fallthrough
4155     case ISD::SETONE:
4156       // Expand this to (OLT | OGT).
4157       TmpOp0 = Op0;
4158       TmpOp1 = Op1;
4159       Opc = ISD::OR;
4160       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4161       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4162       break;
4163     case ISD::SETUO: Invert = true; // Fallthrough
4164     case ISD::SETO:
4165       // Expand this to (OLT | OGE).
4166       TmpOp0 = Op0;
4167       TmpOp1 = Op1;
4168       Opc = ISD::OR;
4169       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4170       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4171       break;
4172     }
4173   } else {
4174     // Integer comparisons.
4175     switch (SetCCOpcode) {
4176     default: llvm_unreachable("Illegal integer comparison");
4177     case ISD::SETNE:  Invert = true;
4178     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4179     case ISD::SETLT:  Swap = true;
4180     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4181     case ISD::SETLE:  Swap = true;
4182     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4183     case ISD::SETULT: Swap = true;
4184     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4185     case ISD::SETULE: Swap = true;
4186     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4187     }
4188
4189     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4190     if (Opc == ARMISD::VCEQ) {
4191
4192       SDValue AndOp;
4193       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4194         AndOp = Op0;
4195       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4196         AndOp = Op1;
4197
4198       // Ignore bitconvert.
4199       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4200         AndOp = AndOp.getOperand(0);
4201
4202       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4203         Opc = ARMISD::VTST;
4204         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4205         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4206         Invert = !Invert;
4207       }
4208     }
4209   }
4210
4211   if (Swap)
4212     std::swap(Op0, Op1);
4213
4214   // If one of the operands is a constant vector zero, attempt to fold the
4215   // comparison to a specialized compare-against-zero form.
4216   SDValue SingleOp;
4217   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4218     SingleOp = Op0;
4219   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4220     if (Opc == ARMISD::VCGE)
4221       Opc = ARMISD::VCLEZ;
4222     else if (Opc == ARMISD::VCGT)
4223       Opc = ARMISD::VCLTZ;
4224     SingleOp = Op1;
4225   }
4226
4227   SDValue Result;
4228   if (SingleOp.getNode()) {
4229     switch (Opc) {
4230     case ARMISD::VCEQ:
4231       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4232     case ARMISD::VCGE:
4233       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4234     case ARMISD::VCLEZ:
4235       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4236     case ARMISD::VCGT:
4237       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4238     case ARMISD::VCLTZ:
4239       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4240     default:
4241       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4242     }
4243   } else {
4244      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4245   }
4246
4247   if (Invert)
4248     Result = DAG.getNOT(dl, Result, VT);
4249
4250   return Result;
4251 }
4252
4253 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4254 /// valid vector constant for a NEON instruction with a "modified immediate"
4255 /// operand (e.g., VMOV).  If so, return the encoded value.
4256 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4257                                  unsigned SplatBitSize, SelectionDAG &DAG,
4258                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4259   unsigned OpCmode, Imm;
4260
4261   // SplatBitSize is set to the smallest size that splats the vector, so a
4262   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4263   // immediate instructions others than VMOV do not support the 8-bit encoding
4264   // of a zero vector, and the default encoding of zero is supposed to be the
4265   // 32-bit version.
4266   if (SplatBits == 0)
4267     SplatBitSize = 32;
4268
4269   switch (SplatBitSize) {
4270   case 8:
4271     if (type != VMOVModImm)
4272       return SDValue();
4273     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4274     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4275     OpCmode = 0xe;
4276     Imm = SplatBits;
4277     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4278     break;
4279
4280   case 16:
4281     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4282     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4283     if ((SplatBits & ~0xff) == 0) {
4284       // Value = 0x00nn: Op=x, Cmode=100x.
4285       OpCmode = 0x8;
4286       Imm = SplatBits;
4287       break;
4288     }
4289     if ((SplatBits & ~0xff00) == 0) {
4290       // Value = 0xnn00: Op=x, Cmode=101x.
4291       OpCmode = 0xa;
4292       Imm = SplatBits >> 8;
4293       break;
4294     }
4295     return SDValue();
4296
4297   case 32:
4298     // NEON's 32-bit VMOV supports splat values where:
4299     // * only one byte is nonzero, or
4300     // * the least significant byte is 0xff and the second byte is nonzero, or
4301     // * the least significant 2 bytes are 0xff and the third is nonzero.
4302     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4303     if ((SplatBits & ~0xff) == 0) {
4304       // Value = 0x000000nn: Op=x, Cmode=000x.
4305       OpCmode = 0;
4306       Imm = SplatBits;
4307       break;
4308     }
4309     if ((SplatBits & ~0xff00) == 0) {
4310       // Value = 0x0000nn00: Op=x, Cmode=001x.
4311       OpCmode = 0x2;
4312       Imm = SplatBits >> 8;
4313       break;
4314     }
4315     if ((SplatBits & ~0xff0000) == 0) {
4316       // Value = 0x00nn0000: Op=x, Cmode=010x.
4317       OpCmode = 0x4;
4318       Imm = SplatBits >> 16;
4319       break;
4320     }
4321     if ((SplatBits & ~0xff000000) == 0) {
4322       // Value = 0xnn000000: Op=x, Cmode=011x.
4323       OpCmode = 0x6;
4324       Imm = SplatBits >> 24;
4325       break;
4326     }
4327
4328     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4329     if (type == OtherModImm) return SDValue();
4330
4331     if ((SplatBits & ~0xffff) == 0 &&
4332         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4333       // Value = 0x0000nnff: Op=x, Cmode=1100.
4334       OpCmode = 0xc;
4335       Imm = SplatBits >> 8;
4336       SplatBits |= 0xff;
4337       break;
4338     }
4339
4340     if ((SplatBits & ~0xffffff) == 0 &&
4341         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4342       // Value = 0x00nnffff: Op=x, Cmode=1101.
4343       OpCmode = 0xd;
4344       Imm = SplatBits >> 16;
4345       SplatBits |= 0xffff;
4346       break;
4347     }
4348
4349     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4350     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4351     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4352     // and fall through here to test for a valid 64-bit splat.  But, then the
4353     // caller would also need to check and handle the change in size.
4354     return SDValue();
4355
4356   case 64: {
4357     if (type != VMOVModImm)
4358       return SDValue();
4359     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4360     uint64_t BitMask = 0xff;
4361     uint64_t Val = 0;
4362     unsigned ImmMask = 1;
4363     Imm = 0;
4364     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4365       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4366         Val |= BitMask;
4367         Imm |= ImmMask;
4368       } else if ((SplatBits & BitMask) != 0) {
4369         return SDValue();
4370       }
4371       BitMask <<= 8;
4372       ImmMask <<= 1;
4373     }
4374     // Op=1, Cmode=1110.
4375     OpCmode = 0x1e;
4376     SplatBits = Val;
4377     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4378     break;
4379   }
4380
4381   default:
4382     llvm_unreachable("unexpected size for isNEONModifiedImm");
4383   }
4384
4385   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4386   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4387 }
4388
4389 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4390                                            const ARMSubtarget *ST) const {
4391   if (!ST->hasVFP3())
4392     return SDValue();
4393
4394   bool IsDouble = Op.getValueType() == MVT::f64;
4395   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4396
4397   // Try splatting with a VMOV.f32...
4398   APFloat FPVal = CFP->getValueAPF();
4399   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4400
4401   if (ImmVal != -1) {
4402     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4403       // We have code in place to select a valid ConstantFP already, no need to
4404       // do any mangling.
4405       return Op;
4406     }
4407
4408     // It's a float and we are trying to use NEON operations where
4409     // possible. Lower it to a splat followed by an extract.
4410     SDLoc DL(Op);
4411     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4412     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4413                                       NewVal);
4414     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4415                        DAG.getConstant(0, MVT::i32));
4416   }
4417
4418   // The rest of our options are NEON only, make sure that's allowed before
4419   // proceeding..
4420   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4421     return SDValue();
4422
4423   EVT VMovVT;
4424   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4425
4426   // It wouldn't really be worth bothering for doubles except for one very
4427   // important value, which does happen to match: 0.0. So make sure we don't do
4428   // anything stupid.
4429   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4430     return SDValue();
4431
4432   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4433   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4434                                      false, VMOVModImm);
4435   if (NewVal != SDValue()) {
4436     SDLoc DL(Op);
4437     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4438                                       NewVal);
4439     if (IsDouble)
4440       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4441
4442     // It's a float: cast and extract a vector element.
4443     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4444                                        VecConstant);
4445     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4446                        DAG.getConstant(0, MVT::i32));
4447   }
4448
4449   // Finally, try a VMVN.i32
4450   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4451                              false, VMVNModImm);
4452   if (NewVal != SDValue()) {
4453     SDLoc DL(Op);
4454     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4455
4456     if (IsDouble)
4457       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4458
4459     // It's a float: cast and extract a vector element.
4460     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4461                                        VecConstant);
4462     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4463                        DAG.getConstant(0, MVT::i32));
4464   }
4465
4466   return SDValue();
4467 }
4468
4469 // check if an VEXT instruction can handle the shuffle mask when the
4470 // vector sources of the shuffle are the same.
4471 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4472   unsigned NumElts = VT.getVectorNumElements();
4473
4474   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4475   if (M[0] < 0)
4476     return false;
4477
4478   Imm = M[0];
4479
4480   // If this is a VEXT shuffle, the immediate value is the index of the first
4481   // element.  The other shuffle indices must be the successive elements after
4482   // the first one.
4483   unsigned ExpectedElt = Imm;
4484   for (unsigned i = 1; i < NumElts; ++i) {
4485     // Increment the expected index.  If it wraps around, just follow it
4486     // back to index zero and keep going.
4487     ++ExpectedElt;
4488     if (ExpectedElt == NumElts)
4489       ExpectedElt = 0;
4490
4491     if (M[i] < 0) continue; // ignore UNDEF indices
4492     if (ExpectedElt != static_cast<unsigned>(M[i]))
4493       return false;
4494   }
4495
4496   return true;
4497 }
4498
4499
4500 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4501                        bool &ReverseVEXT, unsigned &Imm) {
4502   unsigned NumElts = VT.getVectorNumElements();
4503   ReverseVEXT = false;
4504
4505   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4506   if (M[0] < 0)
4507     return false;
4508
4509   Imm = M[0];
4510
4511   // If this is a VEXT shuffle, the immediate value is the index of the first
4512   // element.  The other shuffle indices must be the successive elements after
4513   // the first one.
4514   unsigned ExpectedElt = Imm;
4515   for (unsigned i = 1; i < NumElts; ++i) {
4516     // Increment the expected index.  If it wraps around, it may still be
4517     // a VEXT but the source vectors must be swapped.
4518     ExpectedElt += 1;
4519     if (ExpectedElt == NumElts * 2) {
4520       ExpectedElt = 0;
4521       ReverseVEXT = true;
4522     }
4523
4524     if (M[i] < 0) continue; // ignore UNDEF indices
4525     if (ExpectedElt != static_cast<unsigned>(M[i]))
4526       return false;
4527   }
4528
4529   // Adjust the index value if the source operands will be swapped.
4530   if (ReverseVEXT)
4531     Imm -= NumElts;
4532
4533   return true;
4534 }
4535
4536 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4537 /// instruction with the specified blocksize.  (The order of the elements
4538 /// within each block of the vector is reversed.)
4539 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4540   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4541          "Only possible block sizes for VREV are: 16, 32, 64");
4542
4543   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4544   if (EltSz == 64)
4545     return false;
4546
4547   unsigned NumElts = VT.getVectorNumElements();
4548   unsigned BlockElts = M[0] + 1;
4549   // If the first shuffle index is UNDEF, be optimistic.
4550   if (M[0] < 0)
4551     BlockElts = BlockSize / EltSz;
4552
4553   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4554     return false;
4555
4556   for (unsigned i = 0; i < NumElts; ++i) {
4557     if (M[i] < 0) continue; // ignore UNDEF indices
4558     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4559       return false;
4560   }
4561
4562   return true;
4563 }
4564
4565 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4566   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4567   // range, then 0 is placed into the resulting vector. So pretty much any mask
4568   // of 8 elements can work here.
4569   return VT == MVT::v8i8 && M.size() == 8;
4570 }
4571
4572 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4573   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4574   if (EltSz == 64)
4575     return false;
4576
4577   unsigned NumElts = VT.getVectorNumElements();
4578   WhichResult = (M[0] == 0 ? 0 : 1);
4579   for (unsigned i = 0; i < NumElts; i += 2) {
4580     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4581         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4582       return false;
4583   }
4584   return true;
4585 }
4586
4587 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4588 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4589 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4590 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4591   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4592   if (EltSz == 64)
4593     return false;
4594
4595   unsigned NumElts = VT.getVectorNumElements();
4596   WhichResult = (M[0] == 0 ? 0 : 1);
4597   for (unsigned i = 0; i < NumElts; i += 2) {
4598     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4599         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4600       return false;
4601   }
4602   return true;
4603 }
4604
4605 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4606   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4607   if (EltSz == 64)
4608     return false;
4609
4610   unsigned NumElts = VT.getVectorNumElements();
4611   WhichResult = (M[0] == 0 ? 0 : 1);
4612   for (unsigned i = 0; i != NumElts; ++i) {
4613     if (M[i] < 0) continue; // ignore UNDEF indices
4614     if ((unsigned) M[i] != 2 * i + WhichResult)
4615       return false;
4616   }
4617
4618   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4619   if (VT.is64BitVector() && EltSz == 32)
4620     return false;
4621
4622   return true;
4623 }
4624
4625 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4626 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4627 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4628 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4629   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4630   if (EltSz == 64)
4631     return false;
4632
4633   unsigned Half = VT.getVectorNumElements() / 2;
4634   WhichResult = (M[0] == 0 ? 0 : 1);
4635   for (unsigned j = 0; j != 2; ++j) {
4636     unsigned Idx = WhichResult;
4637     for (unsigned i = 0; i != Half; ++i) {
4638       int MIdx = M[i + j * Half];
4639       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4640         return false;
4641       Idx += 2;
4642     }
4643   }
4644
4645   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4646   if (VT.is64BitVector() && EltSz == 32)
4647     return false;
4648
4649   return true;
4650 }
4651
4652 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4653   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4654   if (EltSz == 64)
4655     return false;
4656
4657   unsigned NumElts = VT.getVectorNumElements();
4658   WhichResult = (M[0] == 0 ? 0 : 1);
4659   unsigned Idx = WhichResult * NumElts / 2;
4660   for (unsigned i = 0; i != NumElts; i += 2) {
4661     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4662         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4663       return false;
4664     Idx += 1;
4665   }
4666
4667   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4668   if (VT.is64BitVector() && EltSz == 32)
4669     return false;
4670
4671   return true;
4672 }
4673
4674 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4675 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4676 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4677 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4678   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4679   if (EltSz == 64)
4680     return false;
4681
4682   unsigned NumElts = VT.getVectorNumElements();
4683   WhichResult = (M[0] == 0 ? 0 : 1);
4684   unsigned Idx = WhichResult * NumElts / 2;
4685   for (unsigned i = 0; i != NumElts; i += 2) {
4686     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4687         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4688       return false;
4689     Idx += 1;
4690   }
4691
4692   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4693   if (VT.is64BitVector() && EltSz == 32)
4694     return false;
4695
4696   return true;
4697 }
4698
4699 /// \return true if this is a reverse operation on an vector.
4700 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4701   unsigned NumElts = VT.getVectorNumElements();
4702   // Make sure the mask has the right size.
4703   if (NumElts != M.size())
4704       return false;
4705
4706   // Look for <15, ..., 3, -1, 1, 0>.
4707   for (unsigned i = 0; i != NumElts; ++i)
4708     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4709       return false;
4710
4711   return true;
4712 }
4713
4714 // If N is an integer constant that can be moved into a register in one
4715 // instruction, return an SDValue of such a constant (will become a MOV
4716 // instruction).  Otherwise return null.
4717 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4718                                      const ARMSubtarget *ST, SDLoc dl) {
4719   uint64_t Val;
4720   if (!isa<ConstantSDNode>(N))
4721     return SDValue();
4722   Val = cast<ConstantSDNode>(N)->getZExtValue();
4723
4724   if (ST->isThumb1Only()) {
4725     if (Val <= 255 || ~Val <= 255)
4726       return DAG.getConstant(Val, MVT::i32);
4727   } else {
4728     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4729       return DAG.getConstant(Val, MVT::i32);
4730   }
4731   return SDValue();
4732 }
4733
4734 // If this is a case we can't handle, return null and let the default
4735 // expansion code take care of it.
4736 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4737                                              const ARMSubtarget *ST) const {
4738   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4739   SDLoc dl(Op);
4740   EVT VT = Op.getValueType();
4741
4742   APInt SplatBits, SplatUndef;
4743   unsigned SplatBitSize;
4744   bool HasAnyUndefs;
4745   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4746     if (SplatBitSize <= 64) {
4747       // Check if an immediate VMOV works.
4748       EVT VmovVT;
4749       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4750                                       SplatUndef.getZExtValue(), SplatBitSize,
4751                                       DAG, VmovVT, VT.is128BitVector(),
4752                                       VMOVModImm);
4753       if (Val.getNode()) {
4754         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4755         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4756       }
4757
4758       // Try an immediate VMVN.
4759       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4760       Val = isNEONModifiedImm(NegatedImm,
4761                                       SplatUndef.getZExtValue(), SplatBitSize,
4762                                       DAG, VmovVT, VT.is128BitVector(),
4763                                       VMVNModImm);
4764       if (Val.getNode()) {
4765         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4766         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4767       }
4768
4769       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4770       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4771         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4772         if (ImmVal != -1) {
4773           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4774           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4775         }
4776       }
4777     }
4778   }
4779
4780   // Scan through the operands to see if only one value is used.
4781   //
4782   // As an optimisation, even if more than one value is used it may be more
4783   // profitable to splat with one value then change some lanes.
4784   //
4785   // Heuristically we decide to do this if the vector has a "dominant" value,
4786   // defined as splatted to more than half of the lanes.
4787   unsigned NumElts = VT.getVectorNumElements();
4788   bool isOnlyLowElement = true;
4789   bool usesOnlyOneValue = true;
4790   bool hasDominantValue = false;
4791   bool isConstant = true;
4792
4793   // Map of the number of times a particular SDValue appears in the
4794   // element list.
4795   DenseMap<SDValue, unsigned> ValueCounts;
4796   SDValue Value;
4797   for (unsigned i = 0; i < NumElts; ++i) {
4798     SDValue V = Op.getOperand(i);
4799     if (V.getOpcode() == ISD::UNDEF)
4800       continue;
4801     if (i > 0)
4802       isOnlyLowElement = false;
4803     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4804       isConstant = false;
4805
4806     ValueCounts.insert(std::make_pair(V, 0));
4807     unsigned &Count = ValueCounts[V];
4808
4809     // Is this value dominant? (takes up more than half of the lanes)
4810     if (++Count > (NumElts / 2)) {
4811       hasDominantValue = true;
4812       Value = V;
4813     }
4814   }
4815   if (ValueCounts.size() != 1)
4816     usesOnlyOneValue = false;
4817   if (!Value.getNode() && ValueCounts.size() > 0)
4818     Value = ValueCounts.begin()->first;
4819
4820   if (ValueCounts.size() == 0)
4821     return DAG.getUNDEF(VT);
4822
4823   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
4824   // Keep going if we are hitting this case.
4825   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
4826     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4827
4828   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4829
4830   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4831   // i32 and try again.
4832   if (hasDominantValue && EltSize <= 32) {
4833     if (!isConstant) {
4834       SDValue N;
4835
4836       // If we are VDUPing a value that comes directly from a vector, that will
4837       // cause an unnecessary move to and from a GPR, where instead we could
4838       // just use VDUPLANE. We can only do this if the lane being extracted
4839       // is at a constant index, as the VDUP from lane instructions only have
4840       // constant-index forms.
4841       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4842           isa<ConstantSDNode>(Value->getOperand(1))) {
4843         // We need to create a new undef vector to use for the VDUPLANE if the
4844         // size of the vector from which we get the value is different than the
4845         // size of the vector that we need to create. We will insert the element
4846         // such that the register coalescer will remove unnecessary copies.
4847         if (VT != Value->getOperand(0).getValueType()) {
4848           ConstantSDNode *constIndex;
4849           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4850           assert(constIndex && "The index is not a constant!");
4851           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4852                              VT.getVectorNumElements();
4853           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4854                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4855                         Value, DAG.getConstant(index, MVT::i32)),
4856                            DAG.getConstant(index, MVT::i32));
4857         } else
4858           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4859                         Value->getOperand(0), Value->getOperand(1));
4860       } else
4861         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4862
4863       if (!usesOnlyOneValue) {
4864         // The dominant value was splatted as 'N', but we now have to insert
4865         // all differing elements.
4866         for (unsigned I = 0; I < NumElts; ++I) {
4867           if (Op.getOperand(I) == Value)
4868             continue;
4869           SmallVector<SDValue, 3> Ops;
4870           Ops.push_back(N);
4871           Ops.push_back(Op.getOperand(I));
4872           Ops.push_back(DAG.getConstant(I, MVT::i32));
4873           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4874         }
4875       }
4876       return N;
4877     }
4878     if (VT.getVectorElementType().isFloatingPoint()) {
4879       SmallVector<SDValue, 8> Ops;
4880       for (unsigned i = 0; i < NumElts; ++i)
4881         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4882                                   Op.getOperand(i)));
4883       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4884       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4885       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4886       if (Val.getNode())
4887         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4888     }
4889     if (usesOnlyOneValue) {
4890       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4891       if (isConstant && Val.getNode())
4892         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4893     }
4894   }
4895
4896   // If all elements are constants and the case above didn't get hit, fall back
4897   // to the default expansion, which will generate a load from the constant
4898   // pool.
4899   if (isConstant)
4900     return SDValue();
4901
4902   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4903   if (NumElts >= 4) {
4904     SDValue shuffle = ReconstructShuffle(Op, DAG);
4905     if (shuffle != SDValue())
4906       return shuffle;
4907   }
4908
4909   // Vectors with 32- or 64-bit elements can be built by directly assigning
4910   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4911   // will be legalized.
4912   if (EltSize >= 32) {
4913     // Do the expansion with floating-point types, since that is what the VFP
4914     // registers are defined to use, and since i64 is not legal.
4915     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4916     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4917     SmallVector<SDValue, 8> Ops;
4918     for (unsigned i = 0; i < NumElts; ++i)
4919       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4920     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4921     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4922   }
4923
4924   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
4925   // know the default expansion would otherwise fall back on something even
4926   // worse. For a vector with one or two non-undef values, that's
4927   // scalar_to_vector for the elements followed by a shuffle (provided the
4928   // shuffle is valid for the target) and materialization element by element
4929   // on the stack followed by a load for everything else.
4930   if (!isConstant && !usesOnlyOneValue) {
4931     SDValue Vec = DAG.getUNDEF(VT);
4932     for (unsigned i = 0 ; i < NumElts; ++i) {
4933       SDValue V = Op.getOperand(i);
4934       if (V.getOpcode() == ISD::UNDEF)
4935         continue;
4936       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
4937       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
4938     }
4939     return Vec;
4940   }
4941
4942   return SDValue();
4943 }
4944
4945 // Gather data to see if the operation can be modelled as a
4946 // shuffle in combination with VEXTs.
4947 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4948                                               SelectionDAG &DAG) const {
4949   SDLoc dl(Op);
4950   EVT VT = Op.getValueType();
4951   unsigned NumElts = VT.getVectorNumElements();
4952
4953   SmallVector<SDValue, 2> SourceVecs;
4954   SmallVector<unsigned, 2> MinElts;
4955   SmallVector<unsigned, 2> MaxElts;
4956
4957   for (unsigned i = 0; i < NumElts; ++i) {
4958     SDValue V = Op.getOperand(i);
4959     if (V.getOpcode() == ISD::UNDEF)
4960       continue;
4961     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4962       // A shuffle can only come from building a vector from various
4963       // elements of other vectors.
4964       return SDValue();
4965     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4966                VT.getVectorElementType()) {
4967       // This code doesn't know how to handle shuffles where the vector
4968       // element types do not match (this happens because type legalization
4969       // promotes the return type of EXTRACT_VECTOR_ELT).
4970       // FIXME: It might be appropriate to extend this code to handle
4971       // mismatched types.
4972       return SDValue();
4973     }
4974
4975     // Record this extraction against the appropriate vector if possible...
4976     SDValue SourceVec = V.getOperand(0);
4977     // If the element number isn't a constant, we can't effectively
4978     // analyze what's going on.
4979     if (!isa<ConstantSDNode>(V.getOperand(1)))
4980       return SDValue();
4981     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4982     bool FoundSource = false;
4983     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4984       if (SourceVecs[j] == SourceVec) {
4985         if (MinElts[j] > EltNo)
4986           MinElts[j] = EltNo;
4987         if (MaxElts[j] < EltNo)
4988           MaxElts[j] = EltNo;
4989         FoundSource = true;
4990         break;
4991       }
4992     }
4993
4994     // Or record a new source if not...
4995     if (!FoundSource) {
4996       SourceVecs.push_back(SourceVec);
4997       MinElts.push_back(EltNo);
4998       MaxElts.push_back(EltNo);
4999     }
5000   }
5001
5002   // Currently only do something sane when at most two source vectors
5003   // involved.
5004   if (SourceVecs.size() > 2)
5005     return SDValue();
5006
5007   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5008   int VEXTOffsets[2] = {0, 0};
5009
5010   // This loop extracts the usage patterns of the source vectors
5011   // and prepares appropriate SDValues for a shuffle if possible.
5012   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5013     if (SourceVecs[i].getValueType() == VT) {
5014       // No VEXT necessary
5015       ShuffleSrcs[i] = SourceVecs[i];
5016       VEXTOffsets[i] = 0;
5017       continue;
5018     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5019       // It probably isn't worth padding out a smaller vector just to
5020       // break it down again in a shuffle.
5021       return SDValue();
5022     }
5023
5024     // Since only 64-bit and 128-bit vectors are legal on ARM and
5025     // we've eliminated the other cases...
5026     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5027            "unexpected vector sizes in ReconstructShuffle");
5028
5029     if (MaxElts[i] - MinElts[i] >= NumElts) {
5030       // Span too large for a VEXT to cope
5031       return SDValue();
5032     }
5033
5034     if (MinElts[i] >= NumElts) {
5035       // The extraction can just take the second half
5036       VEXTOffsets[i] = NumElts;
5037       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5038                                    SourceVecs[i],
5039                                    DAG.getIntPtrConstant(NumElts));
5040     } else if (MaxElts[i] < NumElts) {
5041       // The extraction can just take the first half
5042       VEXTOffsets[i] = 0;
5043       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5044                                    SourceVecs[i],
5045                                    DAG.getIntPtrConstant(0));
5046     } else {
5047       // An actual VEXT is needed
5048       VEXTOffsets[i] = MinElts[i];
5049       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5050                                      SourceVecs[i],
5051                                      DAG.getIntPtrConstant(0));
5052       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5053                                      SourceVecs[i],
5054                                      DAG.getIntPtrConstant(NumElts));
5055       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5056                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5057     }
5058   }
5059
5060   SmallVector<int, 8> Mask;
5061
5062   for (unsigned i = 0; i < NumElts; ++i) {
5063     SDValue Entry = Op.getOperand(i);
5064     if (Entry.getOpcode() == ISD::UNDEF) {
5065       Mask.push_back(-1);
5066       continue;
5067     }
5068
5069     SDValue ExtractVec = Entry.getOperand(0);
5070     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5071                                           .getOperand(1))->getSExtValue();
5072     if (ExtractVec == SourceVecs[0]) {
5073       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5074     } else {
5075       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5076     }
5077   }
5078
5079   // Final check before we try to produce nonsense...
5080   if (isShuffleMaskLegal(Mask, VT))
5081     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5082                                 &Mask[0]);
5083
5084   return SDValue();
5085 }
5086
5087 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5088 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5089 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5090 /// are assumed to be legal.
5091 bool
5092 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5093                                       EVT VT) const {
5094   if (VT.getVectorNumElements() == 4 &&
5095       (VT.is128BitVector() || VT.is64BitVector())) {
5096     unsigned PFIndexes[4];
5097     for (unsigned i = 0; i != 4; ++i) {
5098       if (M[i] < 0)
5099         PFIndexes[i] = 8;
5100       else
5101         PFIndexes[i] = M[i];
5102     }
5103
5104     // Compute the index in the perfect shuffle table.
5105     unsigned PFTableIndex =
5106       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5107     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5108     unsigned Cost = (PFEntry >> 30);
5109
5110     if (Cost <= 4)
5111       return true;
5112   }
5113
5114   bool ReverseVEXT;
5115   unsigned Imm, WhichResult;
5116
5117   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5118   return (EltSize >= 32 ||
5119           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5120           isVREVMask(M, VT, 64) ||
5121           isVREVMask(M, VT, 32) ||
5122           isVREVMask(M, VT, 16) ||
5123           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5124           isVTBLMask(M, VT) ||
5125           isVTRNMask(M, VT, WhichResult) ||
5126           isVUZPMask(M, VT, WhichResult) ||
5127           isVZIPMask(M, VT, WhichResult) ||
5128           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5129           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5130           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5131           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5132 }
5133
5134 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5135 /// the specified operations to build the shuffle.
5136 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5137                                       SDValue RHS, SelectionDAG &DAG,
5138                                       SDLoc dl) {
5139   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5140   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5141   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5142
5143   enum {
5144     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5145     OP_VREV,
5146     OP_VDUP0,
5147     OP_VDUP1,
5148     OP_VDUP2,
5149     OP_VDUP3,
5150     OP_VEXT1,
5151     OP_VEXT2,
5152     OP_VEXT3,
5153     OP_VUZPL, // VUZP, left result
5154     OP_VUZPR, // VUZP, right result
5155     OP_VZIPL, // VZIP, left result
5156     OP_VZIPR, // VZIP, right result
5157     OP_VTRNL, // VTRN, left result
5158     OP_VTRNR  // VTRN, right result
5159   };
5160
5161   if (OpNum == OP_COPY) {
5162     if (LHSID == (1*9+2)*9+3) return LHS;
5163     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5164     return RHS;
5165   }
5166
5167   SDValue OpLHS, OpRHS;
5168   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5169   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5170   EVT VT = OpLHS.getValueType();
5171
5172   switch (OpNum) {
5173   default: llvm_unreachable("Unknown shuffle opcode!");
5174   case OP_VREV:
5175     // VREV divides the vector in half and swaps within the half.
5176     if (VT.getVectorElementType() == MVT::i32 ||
5177         VT.getVectorElementType() == MVT::f32)
5178       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5179     // vrev <4 x i16> -> VREV32
5180     if (VT.getVectorElementType() == MVT::i16)
5181       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5182     // vrev <4 x i8> -> VREV16
5183     assert(VT.getVectorElementType() == MVT::i8);
5184     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5185   case OP_VDUP0:
5186   case OP_VDUP1:
5187   case OP_VDUP2:
5188   case OP_VDUP3:
5189     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5190                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5191   case OP_VEXT1:
5192   case OP_VEXT2:
5193   case OP_VEXT3:
5194     return DAG.getNode(ARMISD::VEXT, dl, VT,
5195                        OpLHS, OpRHS,
5196                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5197   case OP_VUZPL:
5198   case OP_VUZPR:
5199     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5200                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5201   case OP_VZIPL:
5202   case OP_VZIPR:
5203     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5204                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5205   case OP_VTRNL:
5206   case OP_VTRNR:
5207     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5208                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5209   }
5210 }
5211
5212 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5213                                        ArrayRef<int> ShuffleMask,
5214                                        SelectionDAG &DAG) {
5215   // Check to see if we can use the VTBL instruction.
5216   SDValue V1 = Op.getOperand(0);
5217   SDValue V2 = Op.getOperand(1);
5218   SDLoc DL(Op);
5219
5220   SmallVector<SDValue, 8> VTBLMask;
5221   for (ArrayRef<int>::iterator
5222          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5223     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5224
5225   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5226     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5227                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5228                                    &VTBLMask[0], 8));
5229
5230   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5231                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5232                                  &VTBLMask[0], 8));
5233 }
5234
5235 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5236                                                       SelectionDAG &DAG) {
5237   SDLoc DL(Op);
5238   SDValue OpLHS = Op.getOperand(0);
5239   EVT VT = OpLHS.getValueType();
5240
5241   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5242          "Expect an v8i16/v16i8 type");
5243   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5244   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5245   // extract the first 8 bytes into the top double word and the last 8 bytes
5246   // into the bottom double word. The v8i16 case is similar.
5247   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5248   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5249                      DAG.getConstant(ExtractNum, MVT::i32));
5250 }
5251
5252 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5253   SDValue V1 = Op.getOperand(0);
5254   SDValue V2 = Op.getOperand(1);
5255   SDLoc dl(Op);
5256   EVT VT = Op.getValueType();
5257   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5258
5259   // Convert shuffles that are directly supported on NEON to target-specific
5260   // DAG nodes, instead of keeping them as shuffles and matching them again
5261   // during code selection.  This is more efficient and avoids the possibility
5262   // of inconsistencies between legalization and selection.
5263   // FIXME: floating-point vectors should be canonicalized to integer vectors
5264   // of the same time so that they get CSEd properly.
5265   ArrayRef<int> ShuffleMask = SVN->getMask();
5266
5267   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5268   if (EltSize <= 32) {
5269     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5270       int Lane = SVN->getSplatIndex();
5271       // If this is undef splat, generate it via "just" vdup, if possible.
5272       if (Lane == -1) Lane = 0;
5273
5274       // Test if V1 is a SCALAR_TO_VECTOR.
5275       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5276         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5277       }
5278       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5279       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5280       // reaches it).
5281       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5282           !isa<ConstantSDNode>(V1.getOperand(0))) {
5283         bool IsScalarToVector = true;
5284         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5285           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5286             IsScalarToVector = false;
5287             break;
5288           }
5289         if (IsScalarToVector)
5290           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5291       }
5292       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5293                          DAG.getConstant(Lane, MVT::i32));
5294     }
5295
5296     bool ReverseVEXT;
5297     unsigned Imm;
5298     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5299       if (ReverseVEXT)
5300         std::swap(V1, V2);
5301       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5302                          DAG.getConstant(Imm, MVT::i32));
5303     }
5304
5305     if (isVREVMask(ShuffleMask, VT, 64))
5306       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5307     if (isVREVMask(ShuffleMask, VT, 32))
5308       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5309     if (isVREVMask(ShuffleMask, VT, 16))
5310       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5311
5312     if (V2->getOpcode() == ISD::UNDEF &&
5313         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5314       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5315                          DAG.getConstant(Imm, MVT::i32));
5316     }
5317
5318     // Check for Neon shuffles that modify both input vectors in place.
5319     // If both results are used, i.e., if there are two shuffles with the same
5320     // source operands and with masks corresponding to both results of one of
5321     // these operations, DAG memoization will ensure that a single node is
5322     // used for both shuffles.
5323     unsigned WhichResult;
5324     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5325       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5326                          V1, V2).getValue(WhichResult);
5327     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5328       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5329                          V1, V2).getValue(WhichResult);
5330     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5331       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5332                          V1, V2).getValue(WhichResult);
5333
5334     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5335       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5336                          V1, V1).getValue(WhichResult);
5337     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5338       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5339                          V1, V1).getValue(WhichResult);
5340     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5341       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5342                          V1, V1).getValue(WhichResult);
5343   }
5344
5345   // If the shuffle is not directly supported and it has 4 elements, use
5346   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5347   unsigned NumElts = VT.getVectorNumElements();
5348   if (NumElts == 4) {
5349     unsigned PFIndexes[4];
5350     for (unsigned i = 0; i != 4; ++i) {
5351       if (ShuffleMask[i] < 0)
5352         PFIndexes[i] = 8;
5353       else
5354         PFIndexes[i] = ShuffleMask[i];
5355     }
5356
5357     // Compute the index in the perfect shuffle table.
5358     unsigned PFTableIndex =
5359       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5360     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5361     unsigned Cost = (PFEntry >> 30);
5362
5363     if (Cost <= 4)
5364       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5365   }
5366
5367   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5368   if (EltSize >= 32) {
5369     // Do the expansion with floating-point types, since that is what the VFP
5370     // registers are defined to use, and since i64 is not legal.
5371     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5372     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5373     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5374     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5375     SmallVector<SDValue, 8> Ops;
5376     for (unsigned i = 0; i < NumElts; ++i) {
5377       if (ShuffleMask[i] < 0)
5378         Ops.push_back(DAG.getUNDEF(EltVT));
5379       else
5380         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5381                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5382                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5383                                                   MVT::i32)));
5384     }
5385     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5386     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5387   }
5388
5389   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5390     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5391
5392   if (VT == MVT::v8i8) {
5393     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5394     if (NewOp.getNode())
5395       return NewOp;
5396   }
5397
5398   return SDValue();
5399 }
5400
5401 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5402   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5403   SDValue Lane = Op.getOperand(2);
5404   if (!isa<ConstantSDNode>(Lane))
5405     return SDValue();
5406
5407   return Op;
5408 }
5409
5410 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5411   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5412   SDValue Lane = Op.getOperand(1);
5413   if (!isa<ConstantSDNode>(Lane))
5414     return SDValue();
5415
5416   SDValue Vec = Op.getOperand(0);
5417   if (Op.getValueType() == MVT::i32 &&
5418       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5419     SDLoc dl(Op);
5420     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5421   }
5422
5423   return Op;
5424 }
5425
5426 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5427   // The only time a CONCAT_VECTORS operation can have legal types is when
5428   // two 64-bit vectors are concatenated to a 128-bit vector.
5429   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5430          "unexpected CONCAT_VECTORS");
5431   SDLoc dl(Op);
5432   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5433   SDValue Op0 = Op.getOperand(0);
5434   SDValue Op1 = Op.getOperand(1);
5435   if (Op0.getOpcode() != ISD::UNDEF)
5436     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5437                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5438                       DAG.getIntPtrConstant(0));
5439   if (Op1.getOpcode() != ISD::UNDEF)
5440     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5441                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5442                       DAG.getIntPtrConstant(1));
5443   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5444 }
5445
5446 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5447 /// element has been zero/sign-extended, depending on the isSigned parameter,
5448 /// from an integer type half its size.
5449 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5450                                    bool isSigned) {
5451   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5452   EVT VT = N->getValueType(0);
5453   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5454     SDNode *BVN = N->getOperand(0).getNode();
5455     if (BVN->getValueType(0) != MVT::v4i32 ||
5456         BVN->getOpcode() != ISD::BUILD_VECTOR)
5457       return false;
5458     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5459     unsigned HiElt = 1 - LoElt;
5460     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5461     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5462     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5463     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5464     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5465       return false;
5466     if (isSigned) {
5467       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5468           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5469         return true;
5470     } else {
5471       if (Hi0->isNullValue() && Hi1->isNullValue())
5472         return true;
5473     }
5474     return false;
5475   }
5476
5477   if (N->getOpcode() != ISD::BUILD_VECTOR)
5478     return false;
5479
5480   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5481     SDNode *Elt = N->getOperand(i).getNode();
5482     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5483       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5484       unsigned HalfSize = EltSize / 2;
5485       if (isSigned) {
5486         if (!isIntN(HalfSize, C->getSExtValue()))
5487           return false;
5488       } else {
5489         if (!isUIntN(HalfSize, C->getZExtValue()))
5490           return false;
5491       }
5492       continue;
5493     }
5494     return false;
5495   }
5496
5497   return true;
5498 }
5499
5500 /// isSignExtended - Check if a node is a vector value that is sign-extended
5501 /// or a constant BUILD_VECTOR with sign-extended elements.
5502 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5503   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5504     return true;
5505   if (isExtendedBUILD_VECTOR(N, DAG, true))
5506     return true;
5507   return false;
5508 }
5509
5510 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5511 /// or a constant BUILD_VECTOR with zero-extended elements.
5512 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5513   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5514     return true;
5515   if (isExtendedBUILD_VECTOR(N, DAG, false))
5516     return true;
5517   return false;
5518 }
5519
5520 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5521   if (OrigVT.getSizeInBits() >= 64)
5522     return OrigVT;
5523
5524   assert(OrigVT.isSimple() && "Expecting a simple value type");
5525
5526   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5527   switch (OrigSimpleTy) {
5528   default: llvm_unreachable("Unexpected Vector Type");
5529   case MVT::v2i8:
5530   case MVT::v2i16:
5531      return MVT::v2i32;
5532   case MVT::v4i8:
5533     return  MVT::v4i16;
5534   }
5535 }
5536
5537 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5538 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5539 /// We insert the required extension here to get the vector to fill a D register.
5540 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5541                                             const EVT &OrigTy,
5542                                             const EVT &ExtTy,
5543                                             unsigned ExtOpcode) {
5544   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5545   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5546   // 64-bits we need to insert a new extension so that it will be 64-bits.
5547   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5548   if (OrigTy.getSizeInBits() >= 64)
5549     return N;
5550
5551   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5552   EVT NewVT = getExtensionTo64Bits(OrigTy);
5553
5554   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5555 }
5556
5557 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5558 /// does not do any sign/zero extension. If the original vector is less
5559 /// than 64 bits, an appropriate extension will be added after the load to
5560 /// reach a total size of 64 bits. We have to add the extension separately
5561 /// because ARM does not have a sign/zero extending load for vectors.
5562 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5563   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5564
5565   // The load already has the right type.
5566   if (ExtendedTy == LD->getMemoryVT())
5567     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5568                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5569                 LD->isNonTemporal(), LD->isInvariant(),
5570                 LD->getAlignment());
5571
5572   // We need to create a zextload/sextload. We cannot just create a load
5573   // followed by a zext/zext node because LowerMUL is also run during normal
5574   // operation legalization where we can't create illegal types.
5575   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5576                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5577                         LD->getMemoryVT(), LD->isVolatile(),
5578                         LD->isNonTemporal(), LD->getAlignment());
5579 }
5580
5581 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5582 /// extending load, or BUILD_VECTOR with extended elements, return the
5583 /// unextended value. The unextended vector should be 64 bits so that it can
5584 /// be used as an operand to a VMULL instruction. If the original vector size
5585 /// before extension is less than 64 bits we add a an extension to resize
5586 /// the vector to 64 bits.
5587 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5588   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5589     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5590                                         N->getOperand(0)->getValueType(0),
5591                                         N->getValueType(0),
5592                                         N->getOpcode());
5593
5594   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5595     return SkipLoadExtensionForVMULL(LD, DAG);
5596
5597   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5598   // have been legalized as a BITCAST from v4i32.
5599   if (N->getOpcode() == ISD::BITCAST) {
5600     SDNode *BVN = N->getOperand(0).getNode();
5601     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5602            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5603     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5604     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5605                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5606   }
5607   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5608   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5609   EVT VT = N->getValueType(0);
5610   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5611   unsigned NumElts = VT.getVectorNumElements();
5612   MVT TruncVT = MVT::getIntegerVT(EltSize);
5613   SmallVector<SDValue, 8> Ops;
5614   for (unsigned i = 0; i != NumElts; ++i) {
5615     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5616     const APInt &CInt = C->getAPIntValue();
5617     // Element types smaller than 32 bits are not legal, so use i32 elements.
5618     // The values are implicitly truncated so sext vs. zext doesn't matter.
5619     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5620   }
5621   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5622                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5623 }
5624
5625 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5626   unsigned Opcode = N->getOpcode();
5627   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5628     SDNode *N0 = N->getOperand(0).getNode();
5629     SDNode *N1 = N->getOperand(1).getNode();
5630     return N0->hasOneUse() && N1->hasOneUse() &&
5631       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5632   }
5633   return false;
5634 }
5635
5636 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5637   unsigned Opcode = N->getOpcode();
5638   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5639     SDNode *N0 = N->getOperand(0).getNode();
5640     SDNode *N1 = N->getOperand(1).getNode();
5641     return N0->hasOneUse() && N1->hasOneUse() &&
5642       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5643   }
5644   return false;
5645 }
5646
5647 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5648   // Multiplications are only custom-lowered for 128-bit vectors so that
5649   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5650   EVT VT = Op.getValueType();
5651   assert(VT.is128BitVector() && VT.isInteger() &&
5652          "unexpected type for custom-lowering ISD::MUL");
5653   SDNode *N0 = Op.getOperand(0).getNode();
5654   SDNode *N1 = Op.getOperand(1).getNode();
5655   unsigned NewOpc = 0;
5656   bool isMLA = false;
5657   bool isN0SExt = isSignExtended(N0, DAG);
5658   bool isN1SExt = isSignExtended(N1, DAG);
5659   if (isN0SExt && isN1SExt)
5660     NewOpc = ARMISD::VMULLs;
5661   else {
5662     bool isN0ZExt = isZeroExtended(N0, DAG);
5663     bool isN1ZExt = isZeroExtended(N1, DAG);
5664     if (isN0ZExt && isN1ZExt)
5665       NewOpc = ARMISD::VMULLu;
5666     else if (isN1SExt || isN1ZExt) {
5667       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5668       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5669       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5670         NewOpc = ARMISD::VMULLs;
5671         isMLA = true;
5672       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5673         NewOpc = ARMISD::VMULLu;
5674         isMLA = true;
5675       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5676         std::swap(N0, N1);
5677         NewOpc = ARMISD::VMULLu;
5678         isMLA = true;
5679       }
5680     }
5681
5682     if (!NewOpc) {
5683       if (VT == MVT::v2i64)
5684         // Fall through to expand this.  It is not legal.
5685         return SDValue();
5686       else
5687         // Other vector multiplications are legal.
5688         return Op;
5689     }
5690   }
5691
5692   // Legalize to a VMULL instruction.
5693   SDLoc DL(Op);
5694   SDValue Op0;
5695   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5696   if (!isMLA) {
5697     Op0 = SkipExtensionForVMULL(N0, DAG);
5698     assert(Op0.getValueType().is64BitVector() &&
5699            Op1.getValueType().is64BitVector() &&
5700            "unexpected types for extended operands to VMULL");
5701     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5702   }
5703
5704   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5705   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5706   //   vmull q0, d4, d6
5707   //   vmlal q0, d5, d6
5708   // is faster than
5709   //   vaddl q0, d4, d5
5710   //   vmovl q1, d6
5711   //   vmul  q0, q0, q1
5712   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5713   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5714   EVT Op1VT = Op1.getValueType();
5715   return DAG.getNode(N0->getOpcode(), DL, VT,
5716                      DAG.getNode(NewOpc, DL, VT,
5717                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5718                      DAG.getNode(NewOpc, DL, VT,
5719                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5720 }
5721
5722 static SDValue
5723 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5724   // Convert to float
5725   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5726   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5727   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5728   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5729   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5730   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5731   // Get reciprocal estimate.
5732   // float4 recip = vrecpeq_f32(yf);
5733   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5734                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5735   // Because char has a smaller range than uchar, we can actually get away
5736   // without any newton steps.  This requires that we use a weird bias
5737   // of 0xb000, however (again, this has been exhaustively tested).
5738   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5739   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5740   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5741   Y = DAG.getConstant(0xb000, MVT::i32);
5742   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5743   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5744   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5745   // Convert back to short.
5746   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5747   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5748   return X;
5749 }
5750
5751 static SDValue
5752 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5753   SDValue N2;
5754   // Convert to float.
5755   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5756   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5757   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5758   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5759   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5760   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5761
5762   // Use reciprocal estimate and one refinement step.
5763   // float4 recip = vrecpeq_f32(yf);
5764   // recip *= vrecpsq_f32(yf, recip);
5765   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5766                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5767   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5768                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5769                    N1, N2);
5770   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5771   // Because short has a smaller range than ushort, we can actually get away
5772   // with only a single newton step.  This requires that we use a weird bias
5773   // of 89, however (again, this has been exhaustively tested).
5774   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5775   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5776   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5777   N1 = DAG.getConstant(0x89, MVT::i32);
5778   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5779   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5780   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5781   // Convert back to integer and return.
5782   // return vmovn_s32(vcvt_s32_f32(result));
5783   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5784   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5785   return N0;
5786 }
5787
5788 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5789   EVT VT = Op.getValueType();
5790   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5791          "unexpected type for custom-lowering ISD::SDIV");
5792
5793   SDLoc dl(Op);
5794   SDValue N0 = Op.getOperand(0);
5795   SDValue N1 = Op.getOperand(1);
5796   SDValue N2, N3;
5797
5798   if (VT == MVT::v8i8) {
5799     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5800     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5801
5802     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5803                      DAG.getIntPtrConstant(4));
5804     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5805                      DAG.getIntPtrConstant(4));
5806     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5807                      DAG.getIntPtrConstant(0));
5808     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5809                      DAG.getIntPtrConstant(0));
5810
5811     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5812     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5813
5814     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5815     N0 = LowerCONCAT_VECTORS(N0, DAG);
5816
5817     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5818     return N0;
5819   }
5820   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5821 }
5822
5823 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5824   EVT VT = Op.getValueType();
5825   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5826          "unexpected type for custom-lowering ISD::UDIV");
5827
5828   SDLoc dl(Op);
5829   SDValue N0 = Op.getOperand(0);
5830   SDValue N1 = Op.getOperand(1);
5831   SDValue N2, N3;
5832
5833   if (VT == MVT::v8i8) {
5834     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5835     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5836
5837     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5838                      DAG.getIntPtrConstant(4));
5839     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5840                      DAG.getIntPtrConstant(4));
5841     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5842                      DAG.getIntPtrConstant(0));
5843     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5844                      DAG.getIntPtrConstant(0));
5845
5846     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5847     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5848
5849     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5850     N0 = LowerCONCAT_VECTORS(N0, DAG);
5851
5852     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5853                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5854                      N0);
5855     return N0;
5856   }
5857
5858   // v4i16 sdiv ... Convert to float.
5859   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5860   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5861   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5862   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5863   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5864   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5865
5866   // Use reciprocal estimate and two refinement steps.
5867   // float4 recip = vrecpeq_f32(yf);
5868   // recip *= vrecpsq_f32(yf, recip);
5869   // recip *= vrecpsq_f32(yf, recip);
5870   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5871                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5872   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5873                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5874                    BN1, N2);
5875   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5876   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5877                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5878                    BN1, N2);
5879   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5880   // Simply multiplying by the reciprocal estimate can leave us a few ulps
5881   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5882   // and that it will never cause us to return an answer too large).
5883   // float4 result = as_float4(as_int4(xf*recip) + 2);
5884   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5885   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5886   N1 = DAG.getConstant(2, MVT::i32);
5887   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5888   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5889   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5890   // Convert back to integer and return.
5891   // return vmovn_u32(vcvt_s32_f32(result));
5892   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5893   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5894   return N0;
5895 }
5896
5897 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5898   EVT VT = Op.getNode()->getValueType(0);
5899   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5900
5901   unsigned Opc;
5902   bool ExtraOp = false;
5903   switch (Op.getOpcode()) {
5904   default: llvm_unreachable("Invalid code");
5905   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5906   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5907   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5908   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5909   }
5910
5911   if (!ExtraOp)
5912     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5913                        Op.getOperand(1));
5914   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5915                      Op.getOperand(1), Op.getOperand(2));
5916 }
5917
5918 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
5919   assert(Subtarget->isTargetDarwin());
5920
5921   // For iOS, we want to call an alternative entry point: __sincos_stret,
5922   // return values are passed via sret.
5923   SDLoc dl(Op);
5924   SDValue Arg = Op.getOperand(0);
5925   EVT ArgVT = Arg.getValueType();
5926   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
5927
5928   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
5929   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5930
5931   // Pair of floats / doubles used to pass the result.
5932   StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
5933
5934   // Create stack object for sret.
5935   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
5936   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
5937   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
5938   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
5939
5940   ArgListTy Args;
5941   ArgListEntry Entry;
5942
5943   Entry.Node = SRet;
5944   Entry.Ty = RetTy->getPointerTo();
5945   Entry.isSExt = false;
5946   Entry.isZExt = false;
5947   Entry.isSRet = true;
5948   Args.push_back(Entry);
5949
5950   Entry.Node = Arg;
5951   Entry.Ty = ArgTy;
5952   Entry.isSExt = false;
5953   Entry.isZExt = false;
5954   Args.push_back(Entry);
5955
5956   const char *LibcallName  = (ArgVT == MVT::f64)
5957   ? "__sincos_stret" : "__sincosf_stret";
5958   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
5959
5960   TargetLowering::
5961   CallLoweringInfo CLI(DAG.getEntryNode(), Type::getVoidTy(*DAG.getContext()),
5962                        false, false, false, false, 0,
5963                        CallingConv::C, /*isTaillCall=*/false,
5964                        /*doesNotRet=*/false, /*isReturnValueUsed*/false,
5965                        Callee, Args, DAG, dl);
5966   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
5967
5968   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
5969                                 MachinePointerInfo(), false, false, false, 0);
5970
5971   // Address of cos field.
5972   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
5973                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
5974   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
5975                                 MachinePointerInfo(), false, false, false, 0);
5976
5977   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
5978   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
5979                      LoadSin.getValue(0), LoadCos.getValue(0));
5980 }
5981
5982 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5983   // Monotonic load/store is legal for all targets
5984   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5985     return Op;
5986
5987   // Aquire/Release load/store is not legal for targets without a
5988   // dmb or equivalent available.
5989   return SDValue();
5990 }
5991
5992 static void
5993 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5994                     SelectionDAG &DAG) {
5995   SDLoc dl(Node);
5996   assert (Node->getValueType(0) == MVT::i64 &&
5997           "Only know how to expand i64 atomics");
5998   AtomicSDNode *AN = cast<AtomicSDNode>(Node);
5999
6000   SmallVector<SDValue, 6> Ops;
6001   Ops.push_back(Node->getOperand(0)); // Chain
6002   Ops.push_back(Node->getOperand(1)); // Ptr
6003   for(unsigned i=2; i<Node->getNumOperands(); i++) {
6004     // Low part
6005     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6006                               Node->getOperand(i), DAG.getIntPtrConstant(0)));
6007     // High part
6008     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6009                               Node->getOperand(i), DAG.getIntPtrConstant(1)));
6010   }
6011   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6012   SDValue Result =
6013     DAG.getAtomic(Node->getOpcode(), dl, MVT::i64, Tys, Ops.data(), Ops.size(),
6014                   cast<MemSDNode>(Node)->getMemOperand(), AN->getOrdering(),
6015                   AN->getSynchScope());
6016   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
6017   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6018   Results.push_back(Result.getValue(2));
6019 }
6020
6021 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6022                                     SmallVectorImpl<SDValue> &Results,
6023                                     SelectionDAG &DAG,
6024                                     const ARMSubtarget *Subtarget) {
6025   SDLoc DL(N);
6026   SDValue Cycles32, OutChain;
6027
6028   if (Subtarget->hasPerfMon()) {
6029     // Under Power Management extensions, the cycle-count is:
6030     //    mrc p15, #0, <Rt>, c9, c13, #0
6031     SDValue Ops[] = { N->getOperand(0), // Chain
6032                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6033                       DAG.getConstant(15, MVT::i32),
6034                       DAG.getConstant(0, MVT::i32),
6035                       DAG.getConstant(9, MVT::i32),
6036                       DAG.getConstant(13, MVT::i32),
6037                       DAG.getConstant(0, MVT::i32)
6038     };
6039
6040     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6041                            DAG.getVTList(MVT::i32, MVT::Other), &Ops[0],
6042                            array_lengthof(Ops));
6043     OutChain = Cycles32.getValue(1);
6044   } else {
6045     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6046     // there are older ARM CPUs that have implementation-specific ways of
6047     // obtaining this information (FIXME!).
6048     Cycles32 = DAG.getConstant(0, MVT::i32);
6049     OutChain = DAG.getEntryNode();
6050   }
6051
6052
6053   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6054                                  Cycles32, DAG.getConstant(0, MVT::i32));
6055   Results.push_back(Cycles64);
6056   Results.push_back(OutChain);
6057 }
6058
6059 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6060   switch (Op.getOpcode()) {
6061   default: llvm_unreachable("Don't know how to custom lower this!");
6062   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6063   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6064   case ISD::GlobalAddress:
6065     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
6066       LowerGlobalAddressELF(Op, DAG);
6067   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6068   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6069   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6070   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6071   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6072   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6073   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6074   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6075   case ISD::SINT_TO_FP:
6076   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6077   case ISD::FP_TO_SINT:
6078   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6079   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6080   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6081   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6082   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6083   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6084   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6085   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6086                                                                Subtarget);
6087   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6088   case ISD::SHL:
6089   case ISD::SRL:
6090   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6091   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6092   case ISD::SRL_PARTS:
6093   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6094   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6095   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6096   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6097   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6098   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6099   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6100   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6101   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6102   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6103   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6104   case ISD::MUL:           return LowerMUL(Op, DAG);
6105   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6106   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6107   case ISD::ADDC:
6108   case ISD::ADDE:
6109   case ISD::SUBC:
6110   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6111   case ISD::ATOMIC_LOAD:
6112   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6113   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6114   case ISD::SDIVREM:
6115   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6116   }
6117 }
6118
6119 /// ReplaceNodeResults - Replace the results of node with an illegal result
6120 /// type with new values built out of custom code.
6121 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6122                                            SmallVectorImpl<SDValue>&Results,
6123                                            SelectionDAG &DAG) const {
6124   SDValue Res;
6125   switch (N->getOpcode()) {
6126   default:
6127     llvm_unreachable("Don't know how to custom expand this!");
6128   case ISD::BITCAST:
6129     Res = ExpandBITCAST(N, DAG);
6130     break;
6131   case ISD::SRL:
6132   case ISD::SRA:
6133     Res = Expand64BitShift(N, DAG, Subtarget);
6134     break;
6135   case ISD::READCYCLECOUNTER:
6136     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6137     return;
6138   case ISD::ATOMIC_STORE:
6139   case ISD::ATOMIC_LOAD:
6140   case ISD::ATOMIC_LOAD_ADD:
6141   case ISD::ATOMIC_LOAD_AND:
6142   case ISD::ATOMIC_LOAD_NAND:
6143   case ISD::ATOMIC_LOAD_OR:
6144   case ISD::ATOMIC_LOAD_SUB:
6145   case ISD::ATOMIC_LOAD_XOR:
6146   case ISD::ATOMIC_SWAP:
6147   case ISD::ATOMIC_CMP_SWAP:
6148   case ISD::ATOMIC_LOAD_MIN:
6149   case ISD::ATOMIC_LOAD_UMIN:
6150   case ISD::ATOMIC_LOAD_MAX:
6151   case ISD::ATOMIC_LOAD_UMAX:
6152     ReplaceATOMIC_OP_64(N, Results, DAG);
6153     return;
6154   }
6155   if (Res.getNode())
6156     Results.push_back(Res);
6157 }
6158
6159 //===----------------------------------------------------------------------===//
6160 //                           ARM Scheduler Hooks
6161 //===----------------------------------------------------------------------===//
6162
6163 MachineBasicBlock *
6164 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
6165                                      MachineBasicBlock *BB,
6166                                      unsigned Size) const {
6167   unsigned dest    = MI->getOperand(0).getReg();
6168   unsigned ptr     = MI->getOperand(1).getReg();
6169   unsigned oldval  = MI->getOperand(2).getReg();
6170   unsigned newval  = MI->getOperand(3).getReg();
6171   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6172   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(4).getImm());
6173   DebugLoc dl = MI->getDebugLoc();
6174   bool isThumb2 = Subtarget->isThumb2();
6175
6176   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6177   unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
6178     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6179     (const TargetRegisterClass*)&ARM::GPRRegClass);
6180
6181   if (isThumb2) {
6182     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6183     MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
6184     MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
6185   }
6186
6187   unsigned ldrOpc, strOpc;
6188   getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6189
6190   MachineFunction *MF = BB->getParent();
6191   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6192   MachineFunction::iterator It = BB;
6193   ++It; // insert the new blocks after the current block
6194
6195   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6196   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6197   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6198   MF->insert(It, loop1MBB);
6199   MF->insert(It, loop2MBB);
6200   MF->insert(It, exitMBB);
6201
6202   // Transfer the remainder of BB and its successor edges to exitMBB.
6203   exitMBB->splice(exitMBB->begin(), BB,
6204                   llvm::next(MachineBasicBlock::iterator(MI)),
6205                   BB->end());
6206   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6207
6208   //  thisMBB:
6209   //   ...
6210   //   fallthrough --> loop1MBB
6211   BB->addSuccessor(loop1MBB);
6212
6213   // loop1MBB:
6214   //   ldrex dest, [ptr]
6215   //   cmp dest, oldval
6216   //   bne exitMBB
6217   BB = loop1MBB;
6218   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6219   if (ldrOpc == ARM::t2LDREX)
6220     MIB.addImm(0);
6221   AddDefaultPred(MIB);
6222   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6223                  .addReg(dest).addReg(oldval));
6224   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6225     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6226   BB->addSuccessor(loop2MBB);
6227   BB->addSuccessor(exitMBB);
6228
6229   // loop2MBB:
6230   //   strex scratch, newval, [ptr]
6231   //   cmp scratch, #0
6232   //   bne loop1MBB
6233   BB = loop2MBB;
6234   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
6235   if (strOpc == ARM::t2STREX)
6236     MIB.addImm(0);
6237   AddDefaultPred(MIB);
6238   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6239                  .addReg(scratch).addImm(0));
6240   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6241     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6242   BB->addSuccessor(loop1MBB);
6243   BB->addSuccessor(exitMBB);
6244
6245   //  exitMBB:
6246   //   ...
6247   BB = exitMBB;
6248
6249   MI->eraseFromParent();   // The instruction is gone now.
6250
6251   return BB;
6252 }
6253
6254 MachineBasicBlock *
6255 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6256                                     unsigned Size, unsigned BinOpcode) const {
6257   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6258   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6259
6260   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6261   MachineFunction *MF = BB->getParent();
6262   MachineFunction::iterator It = BB;
6263   ++It;
6264
6265   unsigned dest = MI->getOperand(0).getReg();
6266   unsigned ptr = MI->getOperand(1).getReg();
6267   unsigned incr = MI->getOperand(2).getReg();
6268   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6269   DebugLoc dl = MI->getDebugLoc();
6270   bool isThumb2 = Subtarget->isThumb2();
6271
6272   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6273   if (isThumb2) {
6274     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6275     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6276     MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6277   }
6278
6279   unsigned ldrOpc, strOpc;
6280   getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6281
6282   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6283   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6284   MF->insert(It, loopMBB);
6285   MF->insert(It, exitMBB);
6286
6287   // Transfer the remainder of BB and its successor edges to exitMBB.
6288   exitMBB->splice(exitMBB->begin(), BB,
6289                   llvm::next(MachineBasicBlock::iterator(MI)),
6290                   BB->end());
6291   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6292
6293   const TargetRegisterClass *TRC = isThumb2 ?
6294     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6295     (const TargetRegisterClass*)&ARM::GPRRegClass;
6296   unsigned scratch = MRI.createVirtualRegister(TRC);
6297   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
6298
6299   //  thisMBB:
6300   //   ...
6301   //   fallthrough --> loopMBB
6302   BB->addSuccessor(loopMBB);
6303
6304   //  loopMBB:
6305   //   ldrex dest, ptr
6306   //   <binop> scratch2, dest, incr
6307   //   strex scratch, scratch2, ptr
6308   //   cmp scratch, #0
6309   //   bne- loopMBB
6310   //   fallthrough --> exitMBB
6311   BB = loopMBB;
6312   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6313   if (ldrOpc == ARM::t2LDREX)
6314     MIB.addImm(0);
6315   AddDefaultPred(MIB);
6316   if (BinOpcode) {
6317     // operand order needs to go the other way for NAND
6318     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
6319       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6320                      addReg(incr).addReg(dest)).addReg(0);
6321     else
6322       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6323                      addReg(dest).addReg(incr)).addReg(0);
6324   }
6325
6326   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6327   if (strOpc == ARM::t2STREX)
6328     MIB.addImm(0);
6329   AddDefaultPred(MIB);
6330   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6331                  .addReg(scratch).addImm(0));
6332   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6333     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6334
6335   BB->addSuccessor(loopMBB);
6336   BB->addSuccessor(exitMBB);
6337
6338   //  exitMBB:
6339   //   ...
6340   BB = exitMBB;
6341
6342   MI->eraseFromParent();   // The instruction is gone now.
6343
6344   return BB;
6345 }
6346
6347 MachineBasicBlock *
6348 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
6349                                           MachineBasicBlock *BB,
6350                                           unsigned Size,
6351                                           bool signExtend,
6352                                           ARMCC::CondCodes Cond) const {
6353   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6354
6355   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6356   MachineFunction *MF = BB->getParent();
6357   MachineFunction::iterator It = BB;
6358   ++It;
6359
6360   unsigned dest = MI->getOperand(0).getReg();
6361   unsigned ptr = MI->getOperand(1).getReg();
6362   unsigned incr = MI->getOperand(2).getReg();
6363   unsigned oldval = dest;
6364   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6365   DebugLoc dl = MI->getDebugLoc();
6366   bool isThumb2 = Subtarget->isThumb2();
6367
6368   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6369   if (isThumb2) {
6370     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6371     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6372     MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6373   }
6374
6375   unsigned ldrOpc, strOpc, extendOpc;
6376   getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6377   switch (Size) {
6378   default: llvm_unreachable("unsupported size for AtomicBinaryMinMax!");
6379   case 1:
6380     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
6381     break;
6382   case 2:
6383     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
6384     break;
6385   case 4:
6386     extendOpc = 0;
6387     break;
6388   }
6389
6390   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6391   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6392   MF->insert(It, loopMBB);
6393   MF->insert(It, exitMBB);
6394
6395   // Transfer the remainder of BB and its successor edges to exitMBB.
6396   exitMBB->splice(exitMBB->begin(), BB,
6397                   llvm::next(MachineBasicBlock::iterator(MI)),
6398                   BB->end());
6399   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6400
6401   const TargetRegisterClass *TRC = isThumb2 ?
6402     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6403     (const TargetRegisterClass*)&ARM::GPRRegClass;
6404   unsigned scratch = MRI.createVirtualRegister(TRC);
6405   unsigned scratch2 = MRI.createVirtualRegister(TRC);
6406
6407   //  thisMBB:
6408   //   ...
6409   //   fallthrough --> loopMBB
6410   BB->addSuccessor(loopMBB);
6411
6412   //  loopMBB:
6413   //   ldrex dest, ptr
6414   //   (sign extend dest, if required)
6415   //   cmp dest, incr
6416   //   cmov.cond scratch2, incr, dest
6417   //   strex scratch, scratch2, ptr
6418   //   cmp scratch, #0
6419   //   bne- loopMBB
6420   //   fallthrough --> exitMBB
6421   BB = loopMBB;
6422   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6423   if (ldrOpc == ARM::t2LDREX)
6424     MIB.addImm(0);
6425   AddDefaultPred(MIB);
6426
6427   // Sign extend the value, if necessary.
6428   if (signExtend && extendOpc) {
6429     oldval = MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass
6430                                                 : &ARM::GPRnopcRegClass);
6431     if (!isThumb2)
6432       MRI.constrainRegClass(dest, &ARM::GPRnopcRegClass);
6433     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
6434                      .addReg(dest)
6435                      .addImm(0));
6436   }
6437
6438   // Build compare and cmov instructions.
6439   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6440                  .addReg(oldval).addReg(incr));
6441   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
6442          .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
6443
6444   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6445   if (strOpc == ARM::t2STREX)
6446     MIB.addImm(0);
6447   AddDefaultPred(MIB);
6448   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6449                  .addReg(scratch).addImm(0));
6450   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6451     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6452
6453   BB->addSuccessor(loopMBB);
6454   BB->addSuccessor(exitMBB);
6455
6456   //  exitMBB:
6457   //   ...
6458   BB = exitMBB;
6459
6460   MI->eraseFromParent();   // The instruction is gone now.
6461
6462   return BB;
6463 }
6464
6465 MachineBasicBlock *
6466 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
6467                                       unsigned Op1, unsigned Op2,
6468                                       bool NeedsCarry, bool IsCmpxchg,
6469                                       bool IsMinMax, ARMCC::CondCodes CC) const {
6470   // This also handles ATOMIC_SWAP and ATOMIC_STORE, indicated by Op1==0.
6471   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6472
6473   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6474   MachineFunction *MF = BB->getParent();
6475   MachineFunction::iterator It = BB;
6476   ++It;
6477
6478   bool isStore = (MI->getOpcode() == ARM::ATOMIC_STORE_I64);
6479   unsigned offset = (isStore ? -2 : 0);
6480   unsigned destlo = MI->getOperand(0).getReg();
6481   unsigned desthi = MI->getOperand(1).getReg();
6482   unsigned ptr = MI->getOperand(offset+2).getReg();
6483   unsigned vallo = MI->getOperand(offset+3).getReg();
6484   unsigned valhi = MI->getOperand(offset+4).getReg();
6485   unsigned OrdIdx = offset + (IsCmpxchg ? 7 : 5);
6486   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(OrdIdx).getImm());
6487   DebugLoc dl = MI->getDebugLoc();
6488   bool isThumb2 = Subtarget->isThumb2();
6489
6490   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6491   if (isThumb2) {
6492     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6493     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6494     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6495     MRI.constrainRegClass(vallo, &ARM::rGPRRegClass);
6496     MRI.constrainRegClass(valhi, &ARM::rGPRRegClass);
6497   }
6498
6499   unsigned ldrOpc, strOpc;
6500   getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6501
6502   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6503   MachineBasicBlock *contBB = 0, *cont2BB = 0;
6504   if (IsCmpxchg || IsMinMax)
6505     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
6506   if (IsCmpxchg)
6507     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
6508   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6509
6510   MF->insert(It, loopMBB);
6511   if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6512   if (IsCmpxchg) MF->insert(It, cont2BB);
6513   MF->insert(It, exitMBB);
6514
6515   // Transfer the remainder of BB and its successor edges to exitMBB.
6516   exitMBB->splice(exitMBB->begin(), BB,
6517                   llvm::next(MachineBasicBlock::iterator(MI)),
6518                   BB->end());
6519   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6520
6521   const TargetRegisterClass *TRC = isThumb2 ?
6522     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6523     (const TargetRegisterClass*)&ARM::GPRRegClass;
6524   unsigned storesuccess = MRI.createVirtualRegister(TRC);
6525
6526   //  thisMBB:
6527   //   ...
6528   //   fallthrough --> loopMBB
6529   BB->addSuccessor(loopMBB);
6530
6531   //  loopMBB:
6532   //   ldrexd r2, r3, ptr
6533   //   <binopa> r0, r2, incr
6534   //   <binopb> r1, r3, incr
6535   //   strexd storesuccess, r0, r1, ptr
6536   //   cmp storesuccess, #0
6537   //   bne- loopMBB
6538   //   fallthrough --> exitMBB
6539   BB = loopMBB;
6540
6541   if (!isStore) {
6542     // Load
6543     if (isThumb2) {
6544       AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6545                      .addReg(destlo, RegState::Define)
6546                      .addReg(desthi, RegState::Define)
6547                      .addReg(ptr));
6548     } else {
6549       unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6550       AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6551                      .addReg(GPRPair0, RegState::Define).addReg(ptr));
6552       // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
6553       BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6554         .addReg(GPRPair0, 0, ARM::gsub_0);
6555       BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6556         .addReg(GPRPair0, 0, ARM::gsub_1);
6557     }
6558   }
6559
6560   unsigned StoreLo, StoreHi;
6561   if (IsCmpxchg) {
6562     // Add early exit
6563     for (unsigned i = 0; i < 2; i++) {
6564       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6565                                                          ARM::CMPrr))
6566                      .addReg(i == 0 ? destlo : desthi)
6567                      .addReg(i == 0 ? vallo : valhi));
6568       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6569         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6570       BB->addSuccessor(exitMBB);
6571       BB->addSuccessor(i == 0 ? contBB : cont2BB);
6572       BB = (i == 0 ? contBB : cont2BB);
6573     }
6574
6575     // Copy to physregs for strexd
6576     StoreLo = MI->getOperand(5).getReg();
6577     StoreHi = MI->getOperand(6).getReg();
6578   } else if (Op1) {
6579     // Perform binary operation
6580     unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6581     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6582                    .addReg(destlo).addReg(vallo))
6583         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6584     unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6585     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6586                    .addReg(desthi).addReg(valhi))
6587         .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6588
6589     StoreLo = tmpRegLo;
6590     StoreHi = tmpRegHi;
6591   } else {
6592     // Copy to physregs for strexd
6593     StoreLo = vallo;
6594     StoreHi = valhi;
6595   }
6596   if (IsMinMax) {
6597     // Compare and branch to exit block.
6598     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6599       .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6600     BB->addSuccessor(exitMBB);
6601     BB->addSuccessor(contBB);
6602     BB = contBB;
6603     StoreLo = vallo;
6604     StoreHi = valhi;
6605   }
6606
6607   // Store
6608   if (isThumb2) {
6609     MRI.constrainRegClass(StoreLo, &ARM::rGPRRegClass);
6610     MRI.constrainRegClass(StoreHi, &ARM::rGPRRegClass);
6611     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6612                    .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6613   } else {
6614     // Marshal a pair...
6615     unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6616     unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6617     unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6618     BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6619     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6620       .addReg(UndefPair)
6621       .addReg(StoreLo)
6622       .addImm(ARM::gsub_0);
6623     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6624       .addReg(r1)
6625       .addReg(StoreHi)
6626       .addImm(ARM::gsub_1);
6627
6628     // ...and store it
6629     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6630                    .addReg(StorePair).addReg(ptr));
6631   }
6632   // Cmp+jump
6633   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6634                  .addReg(storesuccess).addImm(0));
6635   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6636     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6637
6638   BB->addSuccessor(loopMBB);
6639   BB->addSuccessor(exitMBB);
6640
6641   //  exitMBB:
6642   //   ...
6643   BB = exitMBB;
6644
6645   MI->eraseFromParent();   // The instruction is gone now.
6646
6647   return BB;
6648 }
6649
6650 MachineBasicBlock *
6651 ARMTargetLowering::EmitAtomicLoad64(MachineInstr *MI, MachineBasicBlock *BB) const {
6652
6653   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6654
6655   unsigned destlo = MI->getOperand(0).getReg();
6656   unsigned desthi = MI->getOperand(1).getReg();
6657   unsigned ptr = MI->getOperand(2).getReg();
6658   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6659   DebugLoc dl = MI->getDebugLoc();
6660   bool isThumb2 = Subtarget->isThumb2();
6661
6662   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6663   if (isThumb2) {
6664     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6665     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6666     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6667   }
6668   unsigned ldrOpc, strOpc;
6669   getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6670
6671   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(ldrOpc));
6672
6673   if (isThumb2) {
6674     MIB.addReg(destlo, RegState::Define)
6675        .addReg(desthi, RegState::Define)
6676        .addReg(ptr);
6677
6678   } else {
6679     unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6680     MIB.addReg(GPRPair0, RegState::Define).addReg(ptr);
6681
6682     // Copy GPRPair0 into dest.  (This copy will normally be coalesced.)
6683     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), destlo)
6684       .addReg(GPRPair0, 0, ARM::gsub_0);
6685     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), desthi)
6686       .addReg(GPRPair0, 0, ARM::gsub_1);
6687   }
6688   AddDefaultPred(MIB);
6689
6690   MI->eraseFromParent();   // The instruction is gone now.
6691
6692   return BB;
6693 }
6694
6695 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6696 /// registers the function context.
6697 void ARMTargetLowering::
6698 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6699                        MachineBasicBlock *DispatchBB, int FI) const {
6700   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6701   DebugLoc dl = MI->getDebugLoc();
6702   MachineFunction *MF = MBB->getParent();
6703   MachineRegisterInfo *MRI = &MF->getRegInfo();
6704   MachineConstantPool *MCP = MF->getConstantPool();
6705   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6706   const Function *F = MF->getFunction();
6707
6708   bool isThumb = Subtarget->isThumb();
6709   bool isThumb2 = Subtarget->isThumb2();
6710
6711   unsigned PCLabelId = AFI->createPICLabelUId();
6712   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6713   ARMConstantPoolValue *CPV =
6714     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6715   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6716
6717   const TargetRegisterClass *TRC = isThumb ?
6718     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6719     (const TargetRegisterClass*)&ARM::GPRRegClass;
6720
6721   // Grab constant pool and fixed stack memory operands.
6722   MachineMemOperand *CPMMO =
6723     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6724                              MachineMemOperand::MOLoad, 4, 4);
6725
6726   MachineMemOperand *FIMMOSt =
6727     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6728                              MachineMemOperand::MOStore, 4, 4);
6729
6730   // Load the address of the dispatch MBB into the jump buffer.
6731   if (isThumb2) {
6732     // Incoming value: jbuf
6733     //   ldr.n  r5, LCPI1_1
6734     //   orr    r5, r5, #1
6735     //   add    r5, pc
6736     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6737     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6738     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6739                    .addConstantPoolIndex(CPI)
6740                    .addMemOperand(CPMMO));
6741     // Set the low bit because of thumb mode.
6742     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6743     AddDefaultCC(
6744       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6745                      .addReg(NewVReg1, RegState::Kill)
6746                      .addImm(0x01)));
6747     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6748     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6749       .addReg(NewVReg2, RegState::Kill)
6750       .addImm(PCLabelId);
6751     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6752                    .addReg(NewVReg3, RegState::Kill)
6753                    .addFrameIndex(FI)
6754                    .addImm(36)  // &jbuf[1] :: pc
6755                    .addMemOperand(FIMMOSt));
6756   } else if (isThumb) {
6757     // Incoming value: jbuf
6758     //   ldr.n  r1, LCPI1_4
6759     //   add    r1, pc
6760     //   mov    r2, #1
6761     //   orrs   r1, r2
6762     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6763     //   str    r1, [r2]
6764     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6765     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6766                    .addConstantPoolIndex(CPI)
6767                    .addMemOperand(CPMMO));
6768     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6769     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6770       .addReg(NewVReg1, RegState::Kill)
6771       .addImm(PCLabelId);
6772     // Set the low bit because of thumb mode.
6773     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6774     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6775                    .addReg(ARM::CPSR, RegState::Define)
6776                    .addImm(1));
6777     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6778     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6779                    .addReg(ARM::CPSR, RegState::Define)
6780                    .addReg(NewVReg2, RegState::Kill)
6781                    .addReg(NewVReg3, RegState::Kill));
6782     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6783     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6784                    .addFrameIndex(FI)
6785                    .addImm(36)); // &jbuf[1] :: pc
6786     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6787                    .addReg(NewVReg4, RegState::Kill)
6788                    .addReg(NewVReg5, RegState::Kill)
6789                    .addImm(0)
6790                    .addMemOperand(FIMMOSt));
6791   } else {
6792     // Incoming value: jbuf
6793     //   ldr  r1, LCPI1_1
6794     //   add  r1, pc, r1
6795     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6796     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6797     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6798                    .addConstantPoolIndex(CPI)
6799                    .addImm(0)
6800                    .addMemOperand(CPMMO));
6801     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6802     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6803                    .addReg(NewVReg1, RegState::Kill)
6804                    .addImm(PCLabelId));
6805     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6806                    .addReg(NewVReg2, RegState::Kill)
6807                    .addFrameIndex(FI)
6808                    .addImm(36)  // &jbuf[1] :: pc
6809                    .addMemOperand(FIMMOSt));
6810   }
6811 }
6812
6813 MachineBasicBlock *ARMTargetLowering::
6814 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6815   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6816   DebugLoc dl = MI->getDebugLoc();
6817   MachineFunction *MF = MBB->getParent();
6818   MachineRegisterInfo *MRI = &MF->getRegInfo();
6819   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6820   MachineFrameInfo *MFI = MF->getFrameInfo();
6821   int FI = MFI->getFunctionContextIndex();
6822
6823   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6824     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6825     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6826
6827   // Get a mapping of the call site numbers to all of the landing pads they're
6828   // associated with.
6829   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6830   unsigned MaxCSNum = 0;
6831   MachineModuleInfo &MMI = MF->getMMI();
6832   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6833        ++BB) {
6834     if (!BB->isLandingPad()) continue;
6835
6836     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6837     // pad.
6838     for (MachineBasicBlock::iterator
6839            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6840       if (!II->isEHLabel()) continue;
6841
6842       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6843       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6844
6845       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6846       for (SmallVectorImpl<unsigned>::iterator
6847              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6848            CSI != CSE; ++CSI) {
6849         CallSiteNumToLPad[*CSI].push_back(BB);
6850         MaxCSNum = std::max(MaxCSNum, *CSI);
6851       }
6852       break;
6853     }
6854   }
6855
6856   // Get an ordered list of the machine basic blocks for the jump table.
6857   std::vector<MachineBasicBlock*> LPadList;
6858   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6859   LPadList.reserve(CallSiteNumToLPad.size());
6860   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6861     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6862     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6863            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6864       LPadList.push_back(*II);
6865       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6866     }
6867   }
6868
6869   assert(!LPadList.empty() &&
6870          "No landing pad destinations for the dispatch jump table!");
6871
6872   // Create the jump table and associated information.
6873   MachineJumpTableInfo *JTI =
6874     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6875   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6876   unsigned UId = AFI->createJumpTableUId();
6877   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6878
6879   // Create the MBBs for the dispatch code.
6880
6881   // Shove the dispatch's address into the return slot in the function context.
6882   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6883   DispatchBB->setIsLandingPad();
6884
6885   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6886   unsigned trap_opcode;
6887   if (Subtarget->isThumb())
6888     trap_opcode = ARM::tTRAP;
6889   else
6890     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6891
6892   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6893   DispatchBB->addSuccessor(TrapBB);
6894
6895   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6896   DispatchBB->addSuccessor(DispContBB);
6897
6898   // Insert and MBBs.
6899   MF->insert(MF->end(), DispatchBB);
6900   MF->insert(MF->end(), DispContBB);
6901   MF->insert(MF->end(), TrapBB);
6902
6903   // Insert code into the entry block that creates and registers the function
6904   // context.
6905   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6906
6907   MachineMemOperand *FIMMOLd =
6908     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6909                              MachineMemOperand::MOLoad |
6910                              MachineMemOperand::MOVolatile, 4, 4);
6911
6912   MachineInstrBuilder MIB;
6913   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6914
6915   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6916   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6917
6918   // Add a register mask with no preserved registers.  This results in all
6919   // registers being marked as clobbered.
6920   MIB.addRegMask(RI.getNoPreservedMask());
6921
6922   unsigned NumLPads = LPadList.size();
6923   if (Subtarget->isThumb2()) {
6924     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6925     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6926                    .addFrameIndex(FI)
6927                    .addImm(4)
6928                    .addMemOperand(FIMMOLd));
6929
6930     if (NumLPads < 256) {
6931       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6932                      .addReg(NewVReg1)
6933                      .addImm(LPadList.size()));
6934     } else {
6935       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6936       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6937                      .addImm(NumLPads & 0xFFFF));
6938
6939       unsigned VReg2 = VReg1;
6940       if ((NumLPads & 0xFFFF0000) != 0) {
6941         VReg2 = MRI->createVirtualRegister(TRC);
6942         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6943                        .addReg(VReg1)
6944                        .addImm(NumLPads >> 16));
6945       }
6946
6947       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6948                      .addReg(NewVReg1)
6949                      .addReg(VReg2));
6950     }
6951
6952     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6953       .addMBB(TrapBB)
6954       .addImm(ARMCC::HI)
6955       .addReg(ARM::CPSR);
6956
6957     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6958     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6959                    .addJumpTableIndex(MJTI)
6960                    .addImm(UId));
6961
6962     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6963     AddDefaultCC(
6964       AddDefaultPred(
6965         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6966         .addReg(NewVReg3, RegState::Kill)
6967         .addReg(NewVReg1)
6968         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6969
6970     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6971       .addReg(NewVReg4, RegState::Kill)
6972       .addReg(NewVReg1)
6973       .addJumpTableIndex(MJTI)
6974       .addImm(UId);
6975   } else if (Subtarget->isThumb()) {
6976     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6977     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6978                    .addFrameIndex(FI)
6979                    .addImm(1)
6980                    .addMemOperand(FIMMOLd));
6981
6982     if (NumLPads < 256) {
6983       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6984                      .addReg(NewVReg1)
6985                      .addImm(NumLPads));
6986     } else {
6987       MachineConstantPool *ConstantPool = MF->getConstantPool();
6988       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6989       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6990
6991       // MachineConstantPool wants an explicit alignment.
6992       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6993       if (Align == 0)
6994         Align = getDataLayout()->getTypeAllocSize(C->getType());
6995       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6996
6997       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6998       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6999                      .addReg(VReg1, RegState::Define)
7000                      .addConstantPoolIndex(Idx));
7001       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7002                      .addReg(NewVReg1)
7003                      .addReg(VReg1));
7004     }
7005
7006     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7007       .addMBB(TrapBB)
7008       .addImm(ARMCC::HI)
7009       .addReg(ARM::CPSR);
7010
7011     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7012     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7013                    .addReg(ARM::CPSR, RegState::Define)
7014                    .addReg(NewVReg1)
7015                    .addImm(2));
7016
7017     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7018     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7019                    .addJumpTableIndex(MJTI)
7020                    .addImm(UId));
7021
7022     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7023     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7024                    .addReg(ARM::CPSR, RegState::Define)
7025                    .addReg(NewVReg2, RegState::Kill)
7026                    .addReg(NewVReg3));
7027
7028     MachineMemOperand *JTMMOLd =
7029       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7030                                MachineMemOperand::MOLoad, 4, 4);
7031
7032     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7033     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7034                    .addReg(NewVReg4, RegState::Kill)
7035                    .addImm(0)
7036                    .addMemOperand(JTMMOLd));
7037
7038     unsigned NewVReg6 = NewVReg5;
7039     if (RelocM == Reloc::PIC_) {
7040       NewVReg6 = MRI->createVirtualRegister(TRC);
7041       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7042                      .addReg(ARM::CPSR, RegState::Define)
7043                      .addReg(NewVReg5, RegState::Kill)
7044                      .addReg(NewVReg3));
7045     }
7046
7047     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7048       .addReg(NewVReg6, RegState::Kill)
7049       .addJumpTableIndex(MJTI)
7050       .addImm(UId);
7051   } else {
7052     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7053     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7054                    .addFrameIndex(FI)
7055                    .addImm(4)
7056                    .addMemOperand(FIMMOLd));
7057
7058     if (NumLPads < 256) {
7059       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7060                      .addReg(NewVReg1)
7061                      .addImm(NumLPads));
7062     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7063       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7064       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7065                      .addImm(NumLPads & 0xFFFF));
7066
7067       unsigned VReg2 = VReg1;
7068       if ((NumLPads & 0xFFFF0000) != 0) {
7069         VReg2 = MRI->createVirtualRegister(TRC);
7070         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7071                        .addReg(VReg1)
7072                        .addImm(NumLPads >> 16));
7073       }
7074
7075       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7076                      .addReg(NewVReg1)
7077                      .addReg(VReg2));
7078     } else {
7079       MachineConstantPool *ConstantPool = MF->getConstantPool();
7080       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7081       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7082
7083       // MachineConstantPool wants an explicit alignment.
7084       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7085       if (Align == 0)
7086         Align = getDataLayout()->getTypeAllocSize(C->getType());
7087       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7088
7089       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7090       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7091                      .addReg(VReg1, RegState::Define)
7092                      .addConstantPoolIndex(Idx)
7093                      .addImm(0));
7094       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7095                      .addReg(NewVReg1)
7096                      .addReg(VReg1, RegState::Kill));
7097     }
7098
7099     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7100       .addMBB(TrapBB)
7101       .addImm(ARMCC::HI)
7102       .addReg(ARM::CPSR);
7103
7104     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7105     AddDefaultCC(
7106       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7107                      .addReg(NewVReg1)
7108                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7109     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7110     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7111                    .addJumpTableIndex(MJTI)
7112                    .addImm(UId));
7113
7114     MachineMemOperand *JTMMOLd =
7115       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7116                                MachineMemOperand::MOLoad, 4, 4);
7117     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7118     AddDefaultPred(
7119       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7120       .addReg(NewVReg3, RegState::Kill)
7121       .addReg(NewVReg4)
7122       .addImm(0)
7123       .addMemOperand(JTMMOLd));
7124
7125     if (RelocM == Reloc::PIC_) {
7126       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7127         .addReg(NewVReg5, RegState::Kill)
7128         .addReg(NewVReg4)
7129         .addJumpTableIndex(MJTI)
7130         .addImm(UId);
7131     } else {
7132       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7133         .addReg(NewVReg5, RegState::Kill)
7134         .addJumpTableIndex(MJTI)
7135         .addImm(UId);
7136     }
7137   }
7138
7139   // Add the jump table entries as successors to the MBB.
7140   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7141   for (std::vector<MachineBasicBlock*>::iterator
7142          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7143     MachineBasicBlock *CurMBB = *I;
7144     if (SeenMBBs.insert(CurMBB))
7145       DispContBB->addSuccessor(CurMBB);
7146   }
7147
7148   // N.B. the order the invoke BBs are processed in doesn't matter here.
7149   const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
7150   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7151   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
7152          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
7153     MachineBasicBlock *BB = *I;
7154
7155     // Remove the landing pad successor from the invoke block and replace it
7156     // with the new dispatch block.
7157     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7158                                                   BB->succ_end());
7159     while (!Successors.empty()) {
7160       MachineBasicBlock *SMBB = Successors.pop_back_val();
7161       if (SMBB->isLandingPad()) {
7162         BB->removeSuccessor(SMBB);
7163         MBBLPads.push_back(SMBB);
7164       }
7165     }
7166
7167     BB->addSuccessor(DispatchBB);
7168
7169     // Find the invoke call and mark all of the callee-saved registers as
7170     // 'implicit defined' so that they're spilled. This prevents code from
7171     // moving instructions to before the EH block, where they will never be
7172     // executed.
7173     for (MachineBasicBlock::reverse_iterator
7174            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7175       if (!II->isCall()) continue;
7176
7177       DenseMap<unsigned, bool> DefRegs;
7178       for (MachineInstr::mop_iterator
7179              OI = II->operands_begin(), OE = II->operands_end();
7180            OI != OE; ++OI) {
7181         if (!OI->isReg()) continue;
7182         DefRegs[OI->getReg()] = true;
7183       }
7184
7185       MachineInstrBuilder MIB(*MF, &*II);
7186
7187       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7188         unsigned Reg = SavedRegs[i];
7189         if (Subtarget->isThumb2() &&
7190             !ARM::tGPRRegClass.contains(Reg) &&
7191             !ARM::hGPRRegClass.contains(Reg))
7192           continue;
7193         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7194           continue;
7195         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7196           continue;
7197         if (!DefRegs[Reg])
7198           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7199       }
7200
7201       break;
7202     }
7203   }
7204
7205   // Mark all former landing pads as non-landing pads. The dispatch is the only
7206   // landing pad now.
7207   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7208          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7209     (*I)->setIsLandingPad(false);
7210
7211   // The instruction is gone now.
7212   MI->eraseFromParent();
7213
7214   return MBB;
7215 }
7216
7217 static
7218 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7219   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7220        E = MBB->succ_end(); I != E; ++I)
7221     if (*I != Succ)
7222       return *I;
7223   llvm_unreachable("Expecting a BB with two successors!");
7224 }
7225
7226 /// Return the load opcode for a given load size. If load size >= 8,
7227 /// neon opcode will be returned.
7228 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7229   if (LdSize >= 8)
7230     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7231                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7232   if (IsThumb1)
7233     return LdSize == 4 ? ARM::tLDRi
7234                        : LdSize == 2 ? ARM::tLDRHi
7235                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7236   if (IsThumb2)
7237     return LdSize == 4 ? ARM::t2LDR_POST
7238                        : LdSize == 2 ? ARM::t2LDRH_POST
7239                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7240   return LdSize == 4 ? ARM::LDR_POST_IMM
7241                      : LdSize == 2 ? ARM::LDRH_POST
7242                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7243 }
7244
7245 /// Return the store opcode for a given store size. If store size >= 8,
7246 /// neon opcode will be returned.
7247 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7248   if (StSize >= 8)
7249     return StSize == 16 ? ARM::VST1q32wb_fixed
7250                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7251   if (IsThumb1)
7252     return StSize == 4 ? ARM::tSTRi
7253                        : StSize == 2 ? ARM::tSTRHi
7254                                      : StSize == 1 ? ARM::tSTRBi : 0;
7255   if (IsThumb2)
7256     return StSize == 4 ? ARM::t2STR_POST
7257                        : StSize == 2 ? ARM::t2STRH_POST
7258                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7259   return StSize == 4 ? ARM::STR_POST_IMM
7260                      : StSize == 2 ? ARM::STRH_POST
7261                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7262 }
7263
7264 /// Emit a post-increment load operation with given size. The instructions
7265 /// will be added to BB at Pos.
7266 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7267                        const TargetInstrInfo *TII, DebugLoc dl,
7268                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7269                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7270   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7271   assert(LdOpc != 0 && "Should have a load opcode");
7272   if (LdSize >= 8) {
7273     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7274                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7275                        .addImm(0));
7276   } else if (IsThumb1) {
7277     // load + update AddrIn
7278     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7279                        .addReg(AddrIn).addImm(0));
7280     MachineInstrBuilder MIB =
7281         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7282     MIB = AddDefaultT1CC(MIB);
7283     MIB.addReg(AddrIn).addImm(LdSize);
7284     AddDefaultPred(MIB);
7285   } else if (IsThumb2) {
7286     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7287                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7288                        .addImm(LdSize));
7289   } else { // arm
7290     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7291                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7292                        .addReg(0).addImm(LdSize));
7293   }
7294 }
7295
7296 /// Emit a post-increment store operation with given size. The instructions
7297 /// will be added to BB at Pos.
7298 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7299                        const TargetInstrInfo *TII, DebugLoc dl,
7300                        unsigned StSize, unsigned Data, unsigned AddrIn,
7301                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7302   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7303   assert(StOpc != 0 && "Should have a store opcode");
7304   if (StSize >= 8) {
7305     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7306                        .addReg(AddrIn).addImm(0).addReg(Data));
7307   } else if (IsThumb1) {
7308     // store + update AddrIn
7309     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7310                        .addReg(AddrIn).addImm(0));
7311     MachineInstrBuilder MIB =
7312         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7313     MIB = AddDefaultT1CC(MIB);
7314     MIB.addReg(AddrIn).addImm(StSize);
7315     AddDefaultPred(MIB);
7316   } else if (IsThumb2) {
7317     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7318                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7319   } else { // arm
7320     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7321                        .addReg(Data).addReg(AddrIn).addReg(0)
7322                        .addImm(StSize));
7323   }
7324 }
7325
7326 MachineBasicBlock *
7327 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7328                                    MachineBasicBlock *BB) const {
7329   // This pseudo instruction has 3 operands: dst, src, size
7330   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7331   // Otherwise, we will generate unrolled scalar copies.
7332   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7333   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7334   MachineFunction::iterator It = BB;
7335   ++It;
7336
7337   unsigned dest = MI->getOperand(0).getReg();
7338   unsigned src = MI->getOperand(1).getReg();
7339   unsigned SizeVal = MI->getOperand(2).getImm();
7340   unsigned Align = MI->getOperand(3).getImm();
7341   DebugLoc dl = MI->getDebugLoc();
7342
7343   MachineFunction *MF = BB->getParent();
7344   MachineRegisterInfo &MRI = MF->getRegInfo();
7345   unsigned UnitSize = 0;
7346   const TargetRegisterClass *TRC = 0;
7347   const TargetRegisterClass *VecTRC = 0;
7348
7349   bool IsThumb1 = Subtarget->isThumb1Only();
7350   bool IsThumb2 = Subtarget->isThumb2();
7351
7352   if (Align & 1) {
7353     UnitSize = 1;
7354   } else if (Align & 2) {
7355     UnitSize = 2;
7356   } else {
7357     // Check whether we can use NEON instructions.
7358     if (!MF->getFunction()->getAttributes().
7359           hasAttribute(AttributeSet::FunctionIndex,
7360                        Attribute::NoImplicitFloat) &&
7361         Subtarget->hasNEON()) {
7362       if ((Align % 16 == 0) && SizeVal >= 16)
7363         UnitSize = 16;
7364       else if ((Align % 8 == 0) && SizeVal >= 8)
7365         UnitSize = 8;
7366     }
7367     // Can't use NEON instructions.
7368     if (UnitSize == 0)
7369       UnitSize = 4;
7370   }
7371
7372   // Select the correct opcode and register class for unit size load/store
7373   bool IsNeon = UnitSize >= 8;
7374   TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
7375                                : (const TargetRegisterClass *)&ARM::GPRRegClass;
7376   if (IsNeon)
7377     VecTRC = UnitSize == 16
7378                  ? (const TargetRegisterClass *)&ARM::DPairRegClass
7379                  : UnitSize == 8
7380                        ? (const TargetRegisterClass *)&ARM::DPRRegClass
7381                        : 0;
7382
7383   unsigned BytesLeft = SizeVal % UnitSize;
7384   unsigned LoopSize = SizeVal - BytesLeft;
7385
7386   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7387     // Use LDR and STR to copy.
7388     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7389     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7390     unsigned srcIn = src;
7391     unsigned destIn = dest;
7392     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7393       unsigned srcOut = MRI.createVirtualRegister(TRC);
7394       unsigned destOut = MRI.createVirtualRegister(TRC);
7395       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7396       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7397                  IsThumb1, IsThumb2);
7398       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7399                  IsThumb1, IsThumb2);
7400       srcIn = srcOut;
7401       destIn = destOut;
7402     }
7403
7404     // Handle the leftover bytes with LDRB and STRB.
7405     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7406     // [destOut] = STRB_POST(scratch, destIn, 1)
7407     for (unsigned i = 0; i < BytesLeft; i++) {
7408       unsigned srcOut = MRI.createVirtualRegister(TRC);
7409       unsigned destOut = MRI.createVirtualRegister(TRC);
7410       unsigned scratch = MRI.createVirtualRegister(TRC);
7411       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7412                  IsThumb1, IsThumb2);
7413       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7414                  IsThumb1, IsThumb2);
7415       srcIn = srcOut;
7416       destIn = destOut;
7417     }
7418     MI->eraseFromParent();   // The instruction is gone now.
7419     return BB;
7420   }
7421
7422   // Expand the pseudo op to a loop.
7423   // thisMBB:
7424   //   ...
7425   //   movw varEnd, # --> with thumb2
7426   //   movt varEnd, #
7427   //   ldrcp varEnd, idx --> without thumb2
7428   //   fallthrough --> loopMBB
7429   // loopMBB:
7430   //   PHI varPhi, varEnd, varLoop
7431   //   PHI srcPhi, src, srcLoop
7432   //   PHI destPhi, dst, destLoop
7433   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7434   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7435   //   subs varLoop, varPhi, #UnitSize
7436   //   bne loopMBB
7437   //   fallthrough --> exitMBB
7438   // exitMBB:
7439   //   epilogue to handle left-over bytes
7440   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7441   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7442   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7443   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7444   MF->insert(It, loopMBB);
7445   MF->insert(It, exitMBB);
7446
7447   // Transfer the remainder of BB and its successor edges to exitMBB.
7448   exitMBB->splice(exitMBB->begin(), BB,
7449                   llvm::next(MachineBasicBlock::iterator(MI)),
7450                   BB->end());
7451   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7452
7453   // Load an immediate to varEnd.
7454   unsigned varEnd = MRI.createVirtualRegister(TRC);
7455   if (IsThumb2) {
7456     unsigned Vtmp = varEnd;
7457     if ((LoopSize & 0xFFFF0000) != 0)
7458       Vtmp = MRI.createVirtualRegister(TRC);
7459     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7460                        .addImm(LoopSize & 0xFFFF));
7461
7462     if ((LoopSize & 0xFFFF0000) != 0)
7463       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7464                          .addReg(Vtmp).addImm(LoopSize >> 16));
7465   } else {
7466     MachineConstantPool *ConstantPool = MF->getConstantPool();
7467     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7468     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7469
7470     // MachineConstantPool wants an explicit alignment.
7471     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7472     if (Align == 0)
7473       Align = getDataLayout()->getTypeAllocSize(C->getType());
7474     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7475
7476     if (IsThumb1)
7477       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7478           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7479     else
7480       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7481           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7482   }
7483   BB->addSuccessor(loopMBB);
7484
7485   // Generate the loop body:
7486   //   varPhi = PHI(varLoop, varEnd)
7487   //   srcPhi = PHI(srcLoop, src)
7488   //   destPhi = PHI(destLoop, dst)
7489   MachineBasicBlock *entryBB = BB;
7490   BB = loopMBB;
7491   unsigned varLoop = MRI.createVirtualRegister(TRC);
7492   unsigned varPhi = MRI.createVirtualRegister(TRC);
7493   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7494   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7495   unsigned destLoop = MRI.createVirtualRegister(TRC);
7496   unsigned destPhi = MRI.createVirtualRegister(TRC);
7497
7498   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7499     .addReg(varLoop).addMBB(loopMBB)
7500     .addReg(varEnd).addMBB(entryBB);
7501   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7502     .addReg(srcLoop).addMBB(loopMBB)
7503     .addReg(src).addMBB(entryBB);
7504   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7505     .addReg(destLoop).addMBB(loopMBB)
7506     .addReg(dest).addMBB(entryBB);
7507
7508   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7509   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7510   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7511   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7512              IsThumb1, IsThumb2);
7513   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7514              IsThumb1, IsThumb2);
7515
7516   // Decrement loop variable by UnitSize.
7517   if (IsThumb1) {
7518     MachineInstrBuilder MIB =
7519         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7520     MIB = AddDefaultT1CC(MIB);
7521     MIB.addReg(varPhi).addImm(UnitSize);
7522     AddDefaultPred(MIB);
7523   } else {
7524     MachineInstrBuilder MIB =
7525         BuildMI(*BB, BB->end(), dl,
7526                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7527     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7528     MIB->getOperand(5).setReg(ARM::CPSR);
7529     MIB->getOperand(5).setIsDef(true);
7530   }
7531   BuildMI(*BB, BB->end(), dl,
7532           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7533       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7534
7535   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7536   BB->addSuccessor(loopMBB);
7537   BB->addSuccessor(exitMBB);
7538
7539   // Add epilogue to handle BytesLeft.
7540   BB = exitMBB;
7541   MachineInstr *StartOfExit = exitMBB->begin();
7542
7543   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7544   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7545   unsigned srcIn = srcLoop;
7546   unsigned destIn = destLoop;
7547   for (unsigned i = 0; i < BytesLeft; i++) {
7548     unsigned srcOut = MRI.createVirtualRegister(TRC);
7549     unsigned destOut = MRI.createVirtualRegister(TRC);
7550     unsigned scratch = MRI.createVirtualRegister(TRC);
7551     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7552                IsThumb1, IsThumb2);
7553     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7554                IsThumb1, IsThumb2);
7555     srcIn = srcOut;
7556     destIn = destOut;
7557   }
7558
7559   MI->eraseFromParent();   // The instruction is gone now.
7560   return BB;
7561 }
7562
7563 MachineBasicBlock *
7564 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7565                                                MachineBasicBlock *BB) const {
7566   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7567   DebugLoc dl = MI->getDebugLoc();
7568   bool isThumb2 = Subtarget->isThumb2();
7569   switch (MI->getOpcode()) {
7570   default: {
7571     MI->dump();
7572     llvm_unreachable("Unexpected instr type to insert");
7573   }
7574   // The Thumb2 pre-indexed stores have the same MI operands, they just
7575   // define them differently in the .td files from the isel patterns, so
7576   // they need pseudos.
7577   case ARM::t2STR_preidx:
7578     MI->setDesc(TII->get(ARM::t2STR_PRE));
7579     return BB;
7580   case ARM::t2STRB_preidx:
7581     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7582     return BB;
7583   case ARM::t2STRH_preidx:
7584     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7585     return BB;
7586
7587   case ARM::STRi_preidx:
7588   case ARM::STRBi_preidx: {
7589     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7590       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7591     // Decode the offset.
7592     unsigned Offset = MI->getOperand(4).getImm();
7593     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7594     Offset = ARM_AM::getAM2Offset(Offset);
7595     if (isSub)
7596       Offset = -Offset;
7597
7598     MachineMemOperand *MMO = *MI->memoperands_begin();
7599     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7600       .addOperand(MI->getOperand(0))  // Rn_wb
7601       .addOperand(MI->getOperand(1))  // Rt
7602       .addOperand(MI->getOperand(2))  // Rn
7603       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7604       .addOperand(MI->getOperand(5))  // pred
7605       .addOperand(MI->getOperand(6))
7606       .addMemOperand(MMO);
7607     MI->eraseFromParent();
7608     return BB;
7609   }
7610   case ARM::STRr_preidx:
7611   case ARM::STRBr_preidx:
7612   case ARM::STRH_preidx: {
7613     unsigned NewOpc;
7614     switch (MI->getOpcode()) {
7615     default: llvm_unreachable("unexpected opcode!");
7616     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7617     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7618     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7619     }
7620     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7621     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7622       MIB.addOperand(MI->getOperand(i));
7623     MI->eraseFromParent();
7624     return BB;
7625   }
7626   case ARM::ATOMIC_LOAD_ADD_I8:
7627      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7628   case ARM::ATOMIC_LOAD_ADD_I16:
7629      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7630   case ARM::ATOMIC_LOAD_ADD_I32:
7631      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7632
7633   case ARM::ATOMIC_LOAD_AND_I8:
7634      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7635   case ARM::ATOMIC_LOAD_AND_I16:
7636      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7637   case ARM::ATOMIC_LOAD_AND_I32:
7638      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7639
7640   case ARM::ATOMIC_LOAD_OR_I8:
7641      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7642   case ARM::ATOMIC_LOAD_OR_I16:
7643      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7644   case ARM::ATOMIC_LOAD_OR_I32:
7645      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7646
7647   case ARM::ATOMIC_LOAD_XOR_I8:
7648      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7649   case ARM::ATOMIC_LOAD_XOR_I16:
7650      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7651   case ARM::ATOMIC_LOAD_XOR_I32:
7652      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7653
7654   case ARM::ATOMIC_LOAD_NAND_I8:
7655      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7656   case ARM::ATOMIC_LOAD_NAND_I16:
7657      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7658   case ARM::ATOMIC_LOAD_NAND_I32:
7659      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7660
7661   case ARM::ATOMIC_LOAD_SUB_I8:
7662      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7663   case ARM::ATOMIC_LOAD_SUB_I16:
7664      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7665   case ARM::ATOMIC_LOAD_SUB_I32:
7666      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7667
7668   case ARM::ATOMIC_LOAD_MIN_I8:
7669      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7670   case ARM::ATOMIC_LOAD_MIN_I16:
7671      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7672   case ARM::ATOMIC_LOAD_MIN_I32:
7673      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7674
7675   case ARM::ATOMIC_LOAD_MAX_I8:
7676      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7677   case ARM::ATOMIC_LOAD_MAX_I16:
7678      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7679   case ARM::ATOMIC_LOAD_MAX_I32:
7680      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7681
7682   case ARM::ATOMIC_LOAD_UMIN_I8:
7683      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7684   case ARM::ATOMIC_LOAD_UMIN_I16:
7685      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7686   case ARM::ATOMIC_LOAD_UMIN_I32:
7687      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7688
7689   case ARM::ATOMIC_LOAD_UMAX_I8:
7690      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7691   case ARM::ATOMIC_LOAD_UMAX_I16:
7692      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7693   case ARM::ATOMIC_LOAD_UMAX_I32:
7694      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7695
7696   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
7697   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7698   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7699
7700   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
7701   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7702   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7703
7704   case ARM::ATOMIC_LOAD_I64:
7705     return EmitAtomicLoad64(MI, BB);
7706
7707   case ARM::ATOMIC_LOAD_ADD_I64:
7708     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7709                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7710                               /*NeedsCarry*/ true);
7711   case ARM::ATOMIC_LOAD_SUB_I64:
7712     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7713                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7714                               /*NeedsCarry*/ true);
7715   case ARM::ATOMIC_LOAD_OR_I64:
7716     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7717                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7718   case ARM::ATOMIC_LOAD_XOR_I64:
7719     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7720                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7721   case ARM::ATOMIC_LOAD_AND_I64:
7722     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7723                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7724   case ARM::ATOMIC_STORE_I64:
7725   case ARM::ATOMIC_SWAP_I64:
7726     return EmitAtomicBinary64(MI, BB, 0, 0, false);
7727   case ARM::ATOMIC_CMP_SWAP_I64:
7728     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7729                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7730                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7731   case ARM::ATOMIC_LOAD_MIN_I64:
7732     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7733                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7734                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7735                               /*IsMinMax*/ true, ARMCC::LT);
7736   case ARM::ATOMIC_LOAD_MAX_I64:
7737     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7738                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7739                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7740                               /*IsMinMax*/ true, ARMCC::GE);
7741   case ARM::ATOMIC_LOAD_UMIN_I64:
7742     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7743                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7744                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7745                               /*IsMinMax*/ true, ARMCC::LO);
7746   case ARM::ATOMIC_LOAD_UMAX_I64:
7747     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7748                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7749                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7750                               /*IsMinMax*/ true, ARMCC::HS);
7751
7752   case ARM::tMOVCCr_pseudo: {
7753     // To "insert" a SELECT_CC instruction, we actually have to insert the
7754     // diamond control-flow pattern.  The incoming instruction knows the
7755     // destination vreg to set, the condition code register to branch on, the
7756     // true/false values to select between, and a branch opcode to use.
7757     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7758     MachineFunction::iterator It = BB;
7759     ++It;
7760
7761     //  thisMBB:
7762     //  ...
7763     //   TrueVal = ...
7764     //   cmpTY ccX, r1, r2
7765     //   bCC copy1MBB
7766     //   fallthrough --> copy0MBB
7767     MachineBasicBlock *thisMBB  = BB;
7768     MachineFunction *F = BB->getParent();
7769     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7770     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7771     F->insert(It, copy0MBB);
7772     F->insert(It, sinkMBB);
7773
7774     // Transfer the remainder of BB and its successor edges to sinkMBB.
7775     sinkMBB->splice(sinkMBB->begin(), BB,
7776                     llvm::next(MachineBasicBlock::iterator(MI)),
7777                     BB->end());
7778     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7779
7780     BB->addSuccessor(copy0MBB);
7781     BB->addSuccessor(sinkMBB);
7782
7783     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7784       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7785
7786     //  copy0MBB:
7787     //   %FalseValue = ...
7788     //   # fallthrough to sinkMBB
7789     BB = copy0MBB;
7790
7791     // Update machine-CFG edges
7792     BB->addSuccessor(sinkMBB);
7793
7794     //  sinkMBB:
7795     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7796     //  ...
7797     BB = sinkMBB;
7798     BuildMI(*BB, BB->begin(), dl,
7799             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7800       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7801       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7802
7803     MI->eraseFromParent();   // The pseudo instruction is gone now.
7804     return BB;
7805   }
7806
7807   case ARM::BCCi64:
7808   case ARM::BCCZi64: {
7809     // If there is an unconditional branch to the other successor, remove it.
7810     BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
7811
7812     // Compare both parts that make up the double comparison separately for
7813     // equality.
7814     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7815
7816     unsigned LHS1 = MI->getOperand(1).getReg();
7817     unsigned LHS2 = MI->getOperand(2).getReg();
7818     if (RHSisZero) {
7819       AddDefaultPred(BuildMI(BB, dl,
7820                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7821                      .addReg(LHS1).addImm(0));
7822       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7823         .addReg(LHS2).addImm(0)
7824         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7825     } else {
7826       unsigned RHS1 = MI->getOperand(3).getReg();
7827       unsigned RHS2 = MI->getOperand(4).getReg();
7828       AddDefaultPred(BuildMI(BB, dl,
7829                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7830                      .addReg(LHS1).addReg(RHS1));
7831       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7832         .addReg(LHS2).addReg(RHS2)
7833         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7834     }
7835
7836     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7837     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7838     if (MI->getOperand(0).getImm() == ARMCC::NE)
7839       std::swap(destMBB, exitMBB);
7840
7841     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7842       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7843     if (isThumb2)
7844       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7845     else
7846       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7847
7848     MI->eraseFromParent();   // The pseudo instruction is gone now.
7849     return BB;
7850   }
7851
7852   case ARM::Int_eh_sjlj_setjmp:
7853   case ARM::Int_eh_sjlj_setjmp_nofp:
7854   case ARM::tInt_eh_sjlj_setjmp:
7855   case ARM::t2Int_eh_sjlj_setjmp:
7856   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7857     EmitSjLjDispatchBlock(MI, BB);
7858     return BB;
7859
7860   case ARM::ABS:
7861   case ARM::t2ABS: {
7862     // To insert an ABS instruction, we have to insert the
7863     // diamond control-flow pattern.  The incoming instruction knows the
7864     // source vreg to test against 0, the destination vreg to set,
7865     // the condition code register to branch on, the
7866     // true/false values to select between, and a branch opcode to use.
7867     // It transforms
7868     //     V1 = ABS V0
7869     // into
7870     //     V2 = MOVS V0
7871     //     BCC                      (branch to SinkBB if V0 >= 0)
7872     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7873     //     SinkBB: V1 = PHI(V2, V3)
7874     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7875     MachineFunction::iterator BBI = BB;
7876     ++BBI;
7877     MachineFunction *Fn = BB->getParent();
7878     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7879     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7880     Fn->insert(BBI, RSBBB);
7881     Fn->insert(BBI, SinkBB);
7882
7883     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7884     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7885     bool isThumb2 = Subtarget->isThumb2();
7886     MachineRegisterInfo &MRI = Fn->getRegInfo();
7887     // In Thumb mode S must not be specified if source register is the SP or
7888     // PC and if destination register is the SP, so restrict register class
7889     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7890       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7891       (const TargetRegisterClass*)&ARM::GPRRegClass);
7892
7893     // Transfer the remainder of BB and its successor edges to sinkMBB.
7894     SinkBB->splice(SinkBB->begin(), BB,
7895       llvm::next(MachineBasicBlock::iterator(MI)),
7896       BB->end());
7897     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7898
7899     BB->addSuccessor(RSBBB);
7900     BB->addSuccessor(SinkBB);
7901
7902     // fall through to SinkMBB
7903     RSBBB->addSuccessor(SinkBB);
7904
7905     // insert a cmp at the end of BB
7906     AddDefaultPred(BuildMI(BB, dl,
7907                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7908                    .addReg(ABSSrcReg).addImm(0));
7909
7910     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7911     BuildMI(BB, dl,
7912       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7913       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7914
7915     // insert rsbri in RSBBB
7916     // Note: BCC and rsbri will be converted into predicated rsbmi
7917     // by if-conversion pass
7918     BuildMI(*RSBBB, RSBBB->begin(), dl,
7919       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7920       .addReg(ABSSrcReg, RegState::Kill)
7921       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7922
7923     // insert PHI in SinkBB,
7924     // reuse ABSDstReg to not change uses of ABS instruction
7925     BuildMI(*SinkBB, SinkBB->begin(), dl,
7926       TII->get(ARM::PHI), ABSDstReg)
7927       .addReg(NewRsbDstReg).addMBB(RSBBB)
7928       .addReg(ABSSrcReg).addMBB(BB);
7929
7930     // remove ABS instruction
7931     MI->eraseFromParent();
7932
7933     // return last added BB
7934     return SinkBB;
7935   }
7936   case ARM::COPY_STRUCT_BYVAL_I32:
7937     ++NumLoopByVals;
7938     return EmitStructByval(MI, BB);
7939   }
7940 }
7941
7942 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7943                                                       SDNode *Node) const {
7944   if (!MI->hasPostISelHook()) {
7945     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7946            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7947     return;
7948   }
7949
7950   const MCInstrDesc *MCID = &MI->getDesc();
7951   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7952   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7953   // operand is still set to noreg. If needed, set the optional operand's
7954   // register to CPSR, and remove the redundant implicit def.
7955   //
7956   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7957
7958   // Rename pseudo opcodes.
7959   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7960   if (NewOpc) {
7961     const ARMBaseInstrInfo *TII =
7962       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7963     MCID = &TII->get(NewOpc);
7964
7965     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7966            "converted opcode should be the same except for cc_out");
7967
7968     MI->setDesc(*MCID);
7969
7970     // Add the optional cc_out operand
7971     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7972   }
7973   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7974
7975   // Any ARM instruction that sets the 's' bit should specify an optional
7976   // "cc_out" operand in the last operand position.
7977   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7978     assert(!NewOpc && "Optional cc_out operand required");
7979     return;
7980   }
7981   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7982   // since we already have an optional CPSR def.
7983   bool definesCPSR = false;
7984   bool deadCPSR = false;
7985   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7986        i != e; ++i) {
7987     const MachineOperand &MO = MI->getOperand(i);
7988     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7989       definesCPSR = true;
7990       if (MO.isDead())
7991         deadCPSR = true;
7992       MI->RemoveOperand(i);
7993       break;
7994     }
7995   }
7996   if (!definesCPSR) {
7997     assert(!NewOpc && "Optional cc_out operand required");
7998     return;
7999   }
8000   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8001   if (deadCPSR) {
8002     assert(!MI->getOperand(ccOutIdx).getReg() &&
8003            "expect uninitialized optional cc_out operand");
8004     return;
8005   }
8006
8007   // If this instruction was defined with an optional CPSR def and its dag node
8008   // had a live implicit CPSR def, then activate the optional CPSR def.
8009   MachineOperand &MO = MI->getOperand(ccOutIdx);
8010   MO.setReg(ARM::CPSR);
8011   MO.setIsDef(true);
8012 }
8013
8014 //===----------------------------------------------------------------------===//
8015 //                           ARM Optimization Hooks
8016 //===----------------------------------------------------------------------===//
8017
8018 // Helper function that checks if N is a null or all ones constant.
8019 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8020   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8021   if (!C)
8022     return false;
8023   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8024 }
8025
8026 // Return true if N is conditionally 0 or all ones.
8027 // Detects these expressions where cc is an i1 value:
8028 //
8029 //   (select cc 0, y)   [AllOnes=0]
8030 //   (select cc y, 0)   [AllOnes=0]
8031 //   (zext cc)          [AllOnes=0]
8032 //   (sext cc)          [AllOnes=0/1]
8033 //   (select cc -1, y)  [AllOnes=1]
8034 //   (select cc y, -1)  [AllOnes=1]
8035 //
8036 // Invert is set when N is the null/all ones constant when CC is false.
8037 // OtherOp is set to the alternative value of N.
8038 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8039                                        SDValue &CC, bool &Invert,
8040                                        SDValue &OtherOp,
8041                                        SelectionDAG &DAG) {
8042   switch (N->getOpcode()) {
8043   default: return false;
8044   case ISD::SELECT: {
8045     CC = N->getOperand(0);
8046     SDValue N1 = N->getOperand(1);
8047     SDValue N2 = N->getOperand(2);
8048     if (isZeroOrAllOnes(N1, AllOnes)) {
8049       Invert = false;
8050       OtherOp = N2;
8051       return true;
8052     }
8053     if (isZeroOrAllOnes(N2, AllOnes)) {
8054       Invert = true;
8055       OtherOp = N1;
8056       return true;
8057     }
8058     return false;
8059   }
8060   case ISD::ZERO_EXTEND:
8061     // (zext cc) can never be the all ones value.
8062     if (AllOnes)
8063       return false;
8064     // Fall through.
8065   case ISD::SIGN_EXTEND: {
8066     EVT VT = N->getValueType(0);
8067     CC = N->getOperand(0);
8068     if (CC.getValueType() != MVT::i1)
8069       return false;
8070     Invert = !AllOnes;
8071     if (AllOnes)
8072       // When looking for an AllOnes constant, N is an sext, and the 'other'
8073       // value is 0.
8074       OtherOp = DAG.getConstant(0, VT);
8075     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8076       // When looking for a 0 constant, N can be zext or sext.
8077       OtherOp = DAG.getConstant(1, VT);
8078     else
8079       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
8080     return true;
8081   }
8082   }
8083 }
8084
8085 // Combine a constant select operand into its use:
8086 //
8087 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
8088 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
8089 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
8090 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
8091 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
8092 //
8093 // The transform is rejected if the select doesn't have a constant operand that
8094 // is null, or all ones when AllOnes is set.
8095 //
8096 // Also recognize sext/zext from i1:
8097 //
8098 //   (add (zext cc), x) -> (select cc (add x, 1), x)
8099 //   (add (sext cc), x) -> (select cc (add x, -1), x)
8100 //
8101 // These transformations eventually create predicated instructions.
8102 //
8103 // @param N       The node to transform.
8104 // @param Slct    The N operand that is a select.
8105 // @param OtherOp The other N operand (x above).
8106 // @param DCI     Context.
8107 // @param AllOnes Require the select constant to be all ones instead of null.
8108 // @returns The new node, or SDValue() on failure.
8109 static
8110 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8111                             TargetLowering::DAGCombinerInfo &DCI,
8112                             bool AllOnes = false) {
8113   SelectionDAG &DAG = DCI.DAG;
8114   EVT VT = N->getValueType(0);
8115   SDValue NonConstantVal;
8116   SDValue CCOp;
8117   bool SwapSelectOps;
8118   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8119                                   NonConstantVal, DAG))
8120     return SDValue();
8121
8122   // Slct is now know to be the desired identity constant when CC is true.
8123   SDValue TrueVal = OtherOp;
8124   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8125                                  OtherOp, NonConstantVal);
8126   // Unless SwapSelectOps says CC should be false.
8127   if (SwapSelectOps)
8128     std::swap(TrueVal, FalseVal);
8129
8130   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8131                      CCOp, TrueVal, FalseVal);
8132 }
8133
8134 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8135 static
8136 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8137                                        TargetLowering::DAGCombinerInfo &DCI) {
8138   SDValue N0 = N->getOperand(0);
8139   SDValue N1 = N->getOperand(1);
8140   if (N0.getNode()->hasOneUse()) {
8141     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8142     if (Result.getNode())
8143       return Result;
8144   }
8145   if (N1.getNode()->hasOneUse()) {
8146     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8147     if (Result.getNode())
8148       return Result;
8149   }
8150   return SDValue();
8151 }
8152
8153 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8154 // (only after legalization).
8155 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8156                                  TargetLowering::DAGCombinerInfo &DCI,
8157                                  const ARMSubtarget *Subtarget) {
8158
8159   // Only perform optimization if after legalize, and if NEON is available. We
8160   // also expected both operands to be BUILD_VECTORs.
8161   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8162       || N0.getOpcode() != ISD::BUILD_VECTOR
8163       || N1.getOpcode() != ISD::BUILD_VECTOR)
8164     return SDValue();
8165
8166   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8167   EVT VT = N->getValueType(0);
8168   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8169     return SDValue();
8170
8171   // Check that the vector operands are of the right form.
8172   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8173   // operands, where N is the size of the formed vector.
8174   // Each EXTRACT_VECTOR should have the same input vector and odd or even
8175   // index such that we have a pair wise add pattern.
8176
8177   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8178   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8179     return SDValue();
8180   SDValue Vec = N0->getOperand(0)->getOperand(0);
8181   SDNode *V = Vec.getNode();
8182   unsigned nextIndex = 0;
8183
8184   // For each operands to the ADD which are BUILD_VECTORs,
8185   // check to see if each of their operands are an EXTRACT_VECTOR with
8186   // the same vector and appropriate index.
8187   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8188     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8189         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8190
8191       SDValue ExtVec0 = N0->getOperand(i);
8192       SDValue ExtVec1 = N1->getOperand(i);
8193
8194       // First operand is the vector, verify its the same.
8195       if (V != ExtVec0->getOperand(0).getNode() ||
8196           V != ExtVec1->getOperand(0).getNode())
8197         return SDValue();
8198
8199       // Second is the constant, verify its correct.
8200       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8201       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8202
8203       // For the constant, we want to see all the even or all the odd.
8204       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8205           || C1->getZExtValue() != nextIndex+1)
8206         return SDValue();
8207
8208       // Increment index.
8209       nextIndex+=2;
8210     } else
8211       return SDValue();
8212   }
8213
8214   // Create VPADDL node.
8215   SelectionDAG &DAG = DCI.DAG;
8216   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8217
8218   // Build operand list.
8219   SmallVector<SDValue, 8> Ops;
8220   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
8221                                 TLI.getPointerTy()));
8222
8223   // Input is the vector.
8224   Ops.push_back(Vec);
8225
8226   // Get widened type and narrowed type.
8227   MVT widenType;
8228   unsigned numElem = VT.getVectorNumElements();
8229   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8230     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8231     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8232     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8233     default:
8234       llvm_unreachable("Invalid vector element type for padd optimization.");
8235   }
8236
8237   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
8238                             widenType, &Ops[0], Ops.size());
8239   return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, tmp);
8240 }
8241
8242 static SDValue findMUL_LOHI(SDValue V) {
8243   if (V->getOpcode() == ISD::UMUL_LOHI ||
8244       V->getOpcode() == ISD::SMUL_LOHI)
8245     return V;
8246   return SDValue();
8247 }
8248
8249 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8250                                      TargetLowering::DAGCombinerInfo &DCI,
8251                                      const ARMSubtarget *Subtarget) {
8252
8253   if (Subtarget->isThumb1Only()) return SDValue();
8254
8255   // Only perform the checks after legalize when the pattern is available.
8256   if (DCI.isBeforeLegalize()) return SDValue();
8257
8258   // Look for multiply add opportunities.
8259   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8260   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8261   // a glue link from the first add to the second add.
8262   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8263   // a S/UMLAL instruction.
8264   //          loAdd   UMUL_LOHI
8265   //            \    / :lo    \ :hi
8266   //             \  /          \          [no multiline comment]
8267   //              ADDC         |  hiAdd
8268   //                 \ :glue  /  /
8269   //                  \      /  /
8270   //                    ADDE
8271   //
8272   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8273   SDValue AddcOp0 = AddcNode->getOperand(0);
8274   SDValue AddcOp1 = AddcNode->getOperand(1);
8275
8276   // Check if the two operands are from the same mul_lohi node.
8277   if (AddcOp0.getNode() == AddcOp1.getNode())
8278     return SDValue();
8279
8280   assert(AddcNode->getNumValues() == 2 &&
8281          AddcNode->getValueType(0) == MVT::i32 &&
8282          "Expect ADDC with two result values. First: i32");
8283
8284   // Check that we have a glued ADDC node.
8285   if (AddcNode->getValueType(1) != MVT::Glue)
8286     return SDValue();
8287
8288   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8289   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8290       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8291       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8292       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8293     return SDValue();
8294
8295   // Look for the glued ADDE.
8296   SDNode* AddeNode = AddcNode->getGluedUser();
8297   if (AddeNode == NULL)
8298     return SDValue();
8299
8300   // Make sure it is really an ADDE.
8301   if (AddeNode->getOpcode() != ISD::ADDE)
8302     return SDValue();
8303
8304   assert(AddeNode->getNumOperands() == 3 &&
8305          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8306          "ADDE node has the wrong inputs");
8307
8308   // Check for the triangle shape.
8309   SDValue AddeOp0 = AddeNode->getOperand(0);
8310   SDValue AddeOp1 = AddeNode->getOperand(1);
8311
8312   // Make sure that the ADDE operands are not coming from the same node.
8313   if (AddeOp0.getNode() == AddeOp1.getNode())
8314     return SDValue();
8315
8316   // Find the MUL_LOHI node walking up ADDE's operands.
8317   bool IsLeftOperandMUL = false;
8318   SDValue MULOp = findMUL_LOHI(AddeOp0);
8319   if (MULOp == SDValue())
8320    MULOp = findMUL_LOHI(AddeOp1);
8321   else
8322     IsLeftOperandMUL = true;
8323   if (MULOp == SDValue())
8324      return SDValue();
8325
8326   // Figure out the right opcode.
8327   unsigned Opc = MULOp->getOpcode();
8328   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8329
8330   // Figure out the high and low input values to the MLAL node.
8331   SDValue* HiMul = &MULOp;
8332   SDValue* HiAdd = NULL;
8333   SDValue* LoMul = NULL;
8334   SDValue* LowAdd = NULL;
8335
8336   if (IsLeftOperandMUL)
8337     HiAdd = &AddeOp1;
8338   else
8339     HiAdd = &AddeOp0;
8340
8341
8342   if (AddcOp0->getOpcode() == Opc) {
8343     LoMul = &AddcOp0;
8344     LowAdd = &AddcOp1;
8345   }
8346   if (AddcOp1->getOpcode() == Opc) {
8347     LoMul = &AddcOp1;
8348     LowAdd = &AddcOp0;
8349   }
8350
8351   if (LoMul == NULL)
8352     return SDValue();
8353
8354   if (LoMul->getNode() != HiMul->getNode())
8355     return SDValue();
8356
8357   // Create the merged node.
8358   SelectionDAG &DAG = DCI.DAG;
8359
8360   // Build operand list.
8361   SmallVector<SDValue, 8> Ops;
8362   Ops.push_back(LoMul->getOperand(0));
8363   Ops.push_back(LoMul->getOperand(1));
8364   Ops.push_back(*LowAdd);
8365   Ops.push_back(*HiAdd);
8366
8367   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8368                                  DAG.getVTList(MVT::i32, MVT::i32),
8369                                  &Ops[0], Ops.size());
8370
8371   // Replace the ADDs' nodes uses by the MLA node's values.
8372   SDValue HiMLALResult(MLALNode.getNode(), 1);
8373   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8374
8375   SDValue LoMLALResult(MLALNode.getNode(), 0);
8376   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8377
8378   // Return original node to notify the driver to stop replacing.
8379   SDValue resNode(AddcNode, 0);
8380   return resNode;
8381 }
8382
8383 /// PerformADDCCombine - Target-specific dag combine transform from
8384 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8385 static SDValue PerformADDCCombine(SDNode *N,
8386                                  TargetLowering::DAGCombinerInfo &DCI,
8387                                  const ARMSubtarget *Subtarget) {
8388
8389   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8390
8391 }
8392
8393 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8394 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8395 /// called with the default operands, and if that fails, with commuted
8396 /// operands.
8397 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8398                                           TargetLowering::DAGCombinerInfo &DCI,
8399                                           const ARMSubtarget *Subtarget){
8400
8401   // Attempt to create vpaddl for this add.
8402   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8403   if (Result.getNode())
8404     return Result;
8405
8406   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8407   if (N0.getNode()->hasOneUse()) {
8408     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8409     if (Result.getNode()) return Result;
8410   }
8411   return SDValue();
8412 }
8413
8414 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8415 ///
8416 static SDValue PerformADDCombine(SDNode *N,
8417                                  TargetLowering::DAGCombinerInfo &DCI,
8418                                  const ARMSubtarget *Subtarget) {
8419   SDValue N0 = N->getOperand(0);
8420   SDValue N1 = N->getOperand(1);
8421
8422   // First try with the default operand order.
8423   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8424   if (Result.getNode())
8425     return Result;
8426
8427   // If that didn't work, try again with the operands commuted.
8428   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8429 }
8430
8431 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8432 ///
8433 static SDValue PerformSUBCombine(SDNode *N,
8434                                  TargetLowering::DAGCombinerInfo &DCI) {
8435   SDValue N0 = N->getOperand(0);
8436   SDValue N1 = N->getOperand(1);
8437
8438   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8439   if (N1.getNode()->hasOneUse()) {
8440     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8441     if (Result.getNode()) return Result;
8442   }
8443
8444   return SDValue();
8445 }
8446
8447 /// PerformVMULCombine
8448 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8449 /// special multiplier accumulator forwarding.
8450 ///   vmul d3, d0, d2
8451 ///   vmla d3, d1, d2
8452 /// is faster than
8453 ///   vadd d3, d0, d1
8454 ///   vmul d3, d3, d2
8455 //  However, for (A + B) * (A + B),
8456 //    vadd d2, d0, d1
8457 //    vmul d3, d0, d2
8458 //    vmla d3, d1, d2
8459 //  is slower than
8460 //    vadd d2, d0, d1
8461 //    vmul d3, d2, d2
8462 static SDValue PerformVMULCombine(SDNode *N,
8463                                   TargetLowering::DAGCombinerInfo &DCI,
8464                                   const ARMSubtarget *Subtarget) {
8465   if (!Subtarget->hasVMLxForwarding())
8466     return SDValue();
8467
8468   SelectionDAG &DAG = DCI.DAG;
8469   SDValue N0 = N->getOperand(0);
8470   SDValue N1 = N->getOperand(1);
8471   unsigned Opcode = N0.getOpcode();
8472   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8473       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8474     Opcode = N1.getOpcode();
8475     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8476         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8477       return SDValue();
8478     std::swap(N0, N1);
8479   }
8480
8481   if (N0 == N1)
8482     return SDValue();
8483
8484   EVT VT = N->getValueType(0);
8485   SDLoc DL(N);
8486   SDValue N00 = N0->getOperand(0);
8487   SDValue N01 = N0->getOperand(1);
8488   return DAG.getNode(Opcode, DL, VT,
8489                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8490                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8491 }
8492
8493 static SDValue PerformMULCombine(SDNode *N,
8494                                  TargetLowering::DAGCombinerInfo &DCI,
8495                                  const ARMSubtarget *Subtarget) {
8496   SelectionDAG &DAG = DCI.DAG;
8497
8498   if (Subtarget->isThumb1Only())
8499     return SDValue();
8500
8501   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8502     return SDValue();
8503
8504   EVT VT = N->getValueType(0);
8505   if (VT.is64BitVector() || VT.is128BitVector())
8506     return PerformVMULCombine(N, DCI, Subtarget);
8507   if (VT != MVT::i32)
8508     return SDValue();
8509
8510   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8511   if (!C)
8512     return SDValue();
8513
8514   int64_t MulAmt = C->getSExtValue();
8515   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8516
8517   ShiftAmt = ShiftAmt & (32 - 1);
8518   SDValue V = N->getOperand(0);
8519   SDLoc DL(N);
8520
8521   SDValue Res;
8522   MulAmt >>= ShiftAmt;
8523
8524   if (MulAmt >= 0) {
8525     if (isPowerOf2_32(MulAmt - 1)) {
8526       // (mul x, 2^N + 1) => (add (shl x, N), x)
8527       Res = DAG.getNode(ISD::ADD, DL, VT,
8528                         V,
8529                         DAG.getNode(ISD::SHL, DL, VT,
8530                                     V,
8531                                     DAG.getConstant(Log2_32(MulAmt - 1),
8532                                                     MVT::i32)));
8533     } else if (isPowerOf2_32(MulAmt + 1)) {
8534       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8535       Res = DAG.getNode(ISD::SUB, DL, VT,
8536                         DAG.getNode(ISD::SHL, DL, VT,
8537                                     V,
8538                                     DAG.getConstant(Log2_32(MulAmt + 1),
8539                                                     MVT::i32)),
8540                         V);
8541     } else
8542       return SDValue();
8543   } else {
8544     uint64_t MulAmtAbs = -MulAmt;
8545     if (isPowerOf2_32(MulAmtAbs + 1)) {
8546       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8547       Res = DAG.getNode(ISD::SUB, DL, VT,
8548                         V,
8549                         DAG.getNode(ISD::SHL, DL, VT,
8550                                     V,
8551                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8552                                                     MVT::i32)));
8553     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8554       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8555       Res = DAG.getNode(ISD::ADD, DL, VT,
8556                         V,
8557                         DAG.getNode(ISD::SHL, DL, VT,
8558                                     V,
8559                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8560                                                     MVT::i32)));
8561       Res = DAG.getNode(ISD::SUB, DL, VT,
8562                         DAG.getConstant(0, MVT::i32),Res);
8563
8564     } else
8565       return SDValue();
8566   }
8567
8568   if (ShiftAmt != 0)
8569     Res = DAG.getNode(ISD::SHL, DL, VT,
8570                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8571
8572   // Do not add new nodes to DAG combiner worklist.
8573   DCI.CombineTo(N, Res, false);
8574   return SDValue();
8575 }
8576
8577 static SDValue PerformANDCombine(SDNode *N,
8578                                  TargetLowering::DAGCombinerInfo &DCI,
8579                                  const ARMSubtarget *Subtarget) {
8580
8581   // Attempt to use immediate-form VBIC
8582   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8583   SDLoc dl(N);
8584   EVT VT = N->getValueType(0);
8585   SelectionDAG &DAG = DCI.DAG;
8586
8587   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8588     return SDValue();
8589
8590   APInt SplatBits, SplatUndef;
8591   unsigned SplatBitSize;
8592   bool HasAnyUndefs;
8593   if (BVN &&
8594       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8595     if (SplatBitSize <= 64) {
8596       EVT VbicVT;
8597       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8598                                       SplatUndef.getZExtValue(), SplatBitSize,
8599                                       DAG, VbicVT, VT.is128BitVector(),
8600                                       OtherModImm);
8601       if (Val.getNode()) {
8602         SDValue Input =
8603           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8604         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8605         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8606       }
8607     }
8608   }
8609
8610   if (!Subtarget->isThumb1Only()) {
8611     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8612     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8613     if (Result.getNode())
8614       return Result;
8615   }
8616
8617   return SDValue();
8618 }
8619
8620 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8621 static SDValue PerformORCombine(SDNode *N,
8622                                 TargetLowering::DAGCombinerInfo &DCI,
8623                                 const ARMSubtarget *Subtarget) {
8624   // Attempt to use immediate-form VORR
8625   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8626   SDLoc dl(N);
8627   EVT VT = N->getValueType(0);
8628   SelectionDAG &DAG = DCI.DAG;
8629
8630   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8631     return SDValue();
8632
8633   APInt SplatBits, SplatUndef;
8634   unsigned SplatBitSize;
8635   bool HasAnyUndefs;
8636   if (BVN && Subtarget->hasNEON() &&
8637       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8638     if (SplatBitSize <= 64) {
8639       EVT VorrVT;
8640       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8641                                       SplatUndef.getZExtValue(), SplatBitSize,
8642                                       DAG, VorrVT, VT.is128BitVector(),
8643                                       OtherModImm);
8644       if (Val.getNode()) {
8645         SDValue Input =
8646           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8647         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8648         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8649       }
8650     }
8651   }
8652
8653   if (!Subtarget->isThumb1Only()) {
8654     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8655     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8656     if (Result.getNode())
8657       return Result;
8658   }
8659
8660   // The code below optimizes (or (and X, Y), Z).
8661   // The AND operand needs to have a single user to make these optimizations
8662   // profitable.
8663   SDValue N0 = N->getOperand(0);
8664   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8665     return SDValue();
8666   SDValue N1 = N->getOperand(1);
8667
8668   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8669   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8670       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8671     APInt SplatUndef;
8672     unsigned SplatBitSize;
8673     bool HasAnyUndefs;
8674
8675     APInt SplatBits0, SplatBits1;
8676     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8677     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8678     // Ensure that the second operand of both ands are constants
8679     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8680                                       HasAnyUndefs) && !HasAnyUndefs) {
8681         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8682                                           HasAnyUndefs) && !HasAnyUndefs) {
8683             // Ensure that the bit width of the constants are the same and that
8684             // the splat arguments are logical inverses as per the pattern we
8685             // are trying to simplify.
8686             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8687                 SplatBits0 == ~SplatBits1) {
8688                 // Canonicalize the vector type to make instruction selection
8689                 // simpler.
8690                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8691                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8692                                              N0->getOperand(1),
8693                                              N0->getOperand(0),
8694                                              N1->getOperand(0));
8695                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8696             }
8697         }
8698     }
8699   }
8700
8701   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8702   // reasonable.
8703
8704   // BFI is only available on V6T2+
8705   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8706     return SDValue();
8707
8708   SDLoc DL(N);
8709   // 1) or (and A, mask), val => ARMbfi A, val, mask
8710   //      iff (val & mask) == val
8711   //
8712   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8713   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8714   //          && mask == ~mask2
8715   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8716   //          && ~mask == mask2
8717   //  (i.e., copy a bitfield value into another bitfield of the same width)
8718
8719   if (VT != MVT::i32)
8720     return SDValue();
8721
8722   SDValue N00 = N0.getOperand(0);
8723
8724   // The value and the mask need to be constants so we can verify this is
8725   // actually a bitfield set. If the mask is 0xffff, we can do better
8726   // via a movt instruction, so don't use BFI in that case.
8727   SDValue MaskOp = N0.getOperand(1);
8728   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8729   if (!MaskC)
8730     return SDValue();
8731   unsigned Mask = MaskC->getZExtValue();
8732   if (Mask == 0xffff)
8733     return SDValue();
8734   SDValue Res;
8735   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8736   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8737   if (N1C) {
8738     unsigned Val = N1C->getZExtValue();
8739     if ((Val & ~Mask) != Val)
8740       return SDValue();
8741
8742     if (ARM::isBitFieldInvertedMask(Mask)) {
8743       Val >>= countTrailingZeros(~Mask);
8744
8745       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8746                         DAG.getConstant(Val, MVT::i32),
8747                         DAG.getConstant(Mask, MVT::i32));
8748
8749       // Do not add new nodes to DAG combiner worklist.
8750       DCI.CombineTo(N, Res, false);
8751       return SDValue();
8752     }
8753   } else if (N1.getOpcode() == ISD::AND) {
8754     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8755     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8756     if (!N11C)
8757       return SDValue();
8758     unsigned Mask2 = N11C->getZExtValue();
8759
8760     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8761     // as is to match.
8762     if (ARM::isBitFieldInvertedMask(Mask) &&
8763         (Mask == ~Mask2)) {
8764       // The pack halfword instruction works better for masks that fit it,
8765       // so use that when it's available.
8766       if (Subtarget->hasT2ExtractPack() &&
8767           (Mask == 0xffff || Mask == 0xffff0000))
8768         return SDValue();
8769       // 2a
8770       unsigned amt = countTrailingZeros(Mask2);
8771       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8772                         DAG.getConstant(amt, MVT::i32));
8773       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8774                         DAG.getConstant(Mask, MVT::i32));
8775       // Do not add new nodes to DAG combiner worklist.
8776       DCI.CombineTo(N, Res, false);
8777       return SDValue();
8778     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8779                (~Mask == Mask2)) {
8780       // The pack halfword instruction works better for masks that fit it,
8781       // so use that when it's available.
8782       if (Subtarget->hasT2ExtractPack() &&
8783           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8784         return SDValue();
8785       // 2b
8786       unsigned lsb = countTrailingZeros(Mask);
8787       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8788                         DAG.getConstant(lsb, MVT::i32));
8789       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8790                         DAG.getConstant(Mask2, MVT::i32));
8791       // Do not add new nodes to DAG combiner worklist.
8792       DCI.CombineTo(N, Res, false);
8793       return SDValue();
8794     }
8795   }
8796
8797   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8798       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8799       ARM::isBitFieldInvertedMask(~Mask)) {
8800     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8801     // where lsb(mask) == #shamt and masked bits of B are known zero.
8802     SDValue ShAmt = N00.getOperand(1);
8803     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8804     unsigned LSB = countTrailingZeros(Mask);
8805     if (ShAmtC != LSB)
8806       return SDValue();
8807
8808     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8809                       DAG.getConstant(~Mask, MVT::i32));
8810
8811     // Do not add new nodes to DAG combiner worklist.
8812     DCI.CombineTo(N, Res, false);
8813   }
8814
8815   return SDValue();
8816 }
8817
8818 static SDValue PerformXORCombine(SDNode *N,
8819                                  TargetLowering::DAGCombinerInfo &DCI,
8820                                  const ARMSubtarget *Subtarget) {
8821   EVT VT = N->getValueType(0);
8822   SelectionDAG &DAG = DCI.DAG;
8823
8824   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8825     return SDValue();
8826
8827   if (!Subtarget->isThumb1Only()) {
8828     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8829     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8830     if (Result.getNode())
8831       return Result;
8832   }
8833
8834   return SDValue();
8835 }
8836
8837 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8838 /// the bits being cleared by the AND are not demanded by the BFI.
8839 static SDValue PerformBFICombine(SDNode *N,
8840                                  TargetLowering::DAGCombinerInfo &DCI) {
8841   SDValue N1 = N->getOperand(1);
8842   if (N1.getOpcode() == ISD::AND) {
8843     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8844     if (!N11C)
8845       return SDValue();
8846     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8847     unsigned LSB = countTrailingZeros(~InvMask);
8848     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8849     unsigned Mask = (1 << Width)-1;
8850     unsigned Mask2 = N11C->getZExtValue();
8851     if ((Mask & (~Mask2)) == 0)
8852       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8853                              N->getOperand(0), N1.getOperand(0),
8854                              N->getOperand(2));
8855   }
8856   return SDValue();
8857 }
8858
8859 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8860 /// ARMISD::VMOVRRD.
8861 static SDValue PerformVMOVRRDCombine(SDNode *N,
8862                                      TargetLowering::DAGCombinerInfo &DCI) {
8863   // vmovrrd(vmovdrr x, y) -> x,y
8864   SDValue InDouble = N->getOperand(0);
8865   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8866     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8867
8868   // vmovrrd(load f64) -> (load i32), (load i32)
8869   SDNode *InNode = InDouble.getNode();
8870   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8871       InNode->getValueType(0) == MVT::f64 &&
8872       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8873       !cast<LoadSDNode>(InNode)->isVolatile()) {
8874     // TODO: Should this be done for non-FrameIndex operands?
8875     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8876
8877     SelectionDAG &DAG = DCI.DAG;
8878     SDLoc DL(LD);
8879     SDValue BasePtr = LD->getBasePtr();
8880     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8881                                  LD->getPointerInfo(), LD->isVolatile(),
8882                                  LD->isNonTemporal(), LD->isInvariant(),
8883                                  LD->getAlignment());
8884
8885     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8886                                     DAG.getConstant(4, MVT::i32));
8887     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8888                                  LD->getPointerInfo(), LD->isVolatile(),
8889                                  LD->isNonTemporal(), LD->isInvariant(),
8890                                  std::min(4U, LD->getAlignment() / 2));
8891
8892     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8893     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8894     DCI.RemoveFromWorklist(LD);
8895     DAG.DeleteNode(LD);
8896     return Result;
8897   }
8898
8899   return SDValue();
8900 }
8901
8902 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8903 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8904 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8905   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8906   SDValue Op0 = N->getOperand(0);
8907   SDValue Op1 = N->getOperand(1);
8908   if (Op0.getOpcode() == ISD::BITCAST)
8909     Op0 = Op0.getOperand(0);
8910   if (Op1.getOpcode() == ISD::BITCAST)
8911     Op1 = Op1.getOperand(0);
8912   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8913       Op0.getNode() == Op1.getNode() &&
8914       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8915     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8916                        N->getValueType(0), Op0.getOperand(0));
8917   return SDValue();
8918 }
8919
8920 /// PerformSTORECombine - Target-specific dag combine xforms for
8921 /// ISD::STORE.
8922 static SDValue PerformSTORECombine(SDNode *N,
8923                                    TargetLowering::DAGCombinerInfo &DCI) {
8924   StoreSDNode *St = cast<StoreSDNode>(N);
8925   if (St->isVolatile())
8926     return SDValue();
8927
8928   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8929   // pack all of the elements in one place.  Next, store to memory in fewer
8930   // chunks.
8931   SDValue StVal = St->getValue();
8932   EVT VT = StVal.getValueType();
8933   if (St->isTruncatingStore() && VT.isVector()) {
8934     SelectionDAG &DAG = DCI.DAG;
8935     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8936     EVT StVT = St->getMemoryVT();
8937     unsigned NumElems = VT.getVectorNumElements();
8938     assert(StVT != VT && "Cannot truncate to the same type");
8939     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8940     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8941
8942     // From, To sizes and ElemCount must be pow of two
8943     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8944
8945     // We are going to use the original vector elt for storing.
8946     // Accumulated smaller vector elements must be a multiple of the store size.
8947     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8948
8949     unsigned SizeRatio  = FromEltSz / ToEltSz;
8950     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8951
8952     // Create a type on which we perform the shuffle.
8953     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8954                                      NumElems*SizeRatio);
8955     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8956
8957     SDLoc DL(St);
8958     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8959     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8960     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8961
8962     // Can't shuffle using an illegal type.
8963     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8964
8965     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8966                                 DAG.getUNDEF(WideVec.getValueType()),
8967                                 ShuffleVec.data());
8968     // At this point all of the data is stored at the bottom of the
8969     // register. We now need to save it to mem.
8970
8971     // Find the largest store unit
8972     MVT StoreType = MVT::i8;
8973     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8974          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8975       MVT Tp = (MVT::SimpleValueType)tp;
8976       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8977         StoreType = Tp;
8978     }
8979     // Didn't find a legal store type.
8980     if (!TLI.isTypeLegal(StoreType))
8981       return SDValue();
8982
8983     // Bitcast the original vector into a vector of store-size units
8984     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8985             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8986     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8987     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8988     SmallVector<SDValue, 8> Chains;
8989     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8990                                         TLI.getPointerTy());
8991     SDValue BasePtr = St->getBasePtr();
8992
8993     // Perform one or more big stores into memory.
8994     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8995     for (unsigned I = 0; I < E; I++) {
8996       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8997                                    StoreType, ShuffWide,
8998                                    DAG.getIntPtrConstant(I));
8999       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9000                                 St->getPointerInfo(), St->isVolatile(),
9001                                 St->isNonTemporal(), St->getAlignment());
9002       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9003                             Increment);
9004       Chains.push_back(Ch);
9005     }
9006     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
9007                        Chains.size());
9008   }
9009
9010   if (!ISD::isNormalStore(St))
9011     return SDValue();
9012
9013   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9014   // ARM stores of arguments in the same cache line.
9015   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9016       StVal.getNode()->hasOneUse()) {
9017     SelectionDAG  &DAG = DCI.DAG;
9018     SDLoc DL(St);
9019     SDValue BasePtr = St->getBasePtr();
9020     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9021                                   StVal.getNode()->getOperand(0), BasePtr,
9022                                   St->getPointerInfo(), St->isVolatile(),
9023                                   St->isNonTemporal(), St->getAlignment());
9024
9025     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9026                                     DAG.getConstant(4, MVT::i32));
9027     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
9028                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9029                         St->isNonTemporal(),
9030                         std::min(4U, St->getAlignment() / 2));
9031   }
9032
9033   if (StVal.getValueType() != MVT::i64 ||
9034       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9035     return SDValue();
9036
9037   // Bitcast an i64 store extracted from a vector to f64.
9038   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9039   SelectionDAG &DAG = DCI.DAG;
9040   SDLoc dl(StVal);
9041   SDValue IntVec = StVal.getOperand(0);
9042   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9043                                  IntVec.getValueType().getVectorNumElements());
9044   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9045   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9046                                Vec, StVal.getOperand(1));
9047   dl = SDLoc(N);
9048   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9049   // Make the DAGCombiner fold the bitcasts.
9050   DCI.AddToWorklist(Vec.getNode());
9051   DCI.AddToWorklist(ExtElt.getNode());
9052   DCI.AddToWorklist(V.getNode());
9053   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9054                       St->getPointerInfo(), St->isVolatile(),
9055                       St->isNonTemporal(), St->getAlignment(),
9056                       St->getTBAAInfo());
9057 }
9058
9059 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9060 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
9061 /// i64 vector to have f64 elements, since the value can then be loaded
9062 /// directly into a VFP register.
9063 static bool hasNormalLoadOperand(SDNode *N) {
9064   unsigned NumElts = N->getValueType(0).getVectorNumElements();
9065   for (unsigned i = 0; i < NumElts; ++i) {
9066     SDNode *Elt = N->getOperand(i).getNode();
9067     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9068       return true;
9069   }
9070   return false;
9071 }
9072
9073 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9074 /// ISD::BUILD_VECTOR.
9075 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9076                                           TargetLowering::DAGCombinerInfo &DCI){
9077   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9078   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
9079   // into a pair of GPRs, which is fine when the value is used as a scalar,
9080   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9081   SelectionDAG &DAG = DCI.DAG;
9082   if (N->getNumOperands() == 2) {
9083     SDValue RV = PerformVMOVDRRCombine(N, DAG);
9084     if (RV.getNode())
9085       return RV;
9086   }
9087
9088   // Load i64 elements as f64 values so that type legalization does not split
9089   // them up into i32 values.
9090   EVT VT = N->getValueType(0);
9091   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9092     return SDValue();
9093   SDLoc dl(N);
9094   SmallVector<SDValue, 8> Ops;
9095   unsigned NumElts = VT.getVectorNumElements();
9096   for (unsigned i = 0; i < NumElts; ++i) {
9097     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9098     Ops.push_back(V);
9099     // Make the DAGCombiner fold the bitcast.
9100     DCI.AddToWorklist(V.getNode());
9101   }
9102   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9103   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
9104   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9105 }
9106
9107 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9108 static SDValue
9109 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9110   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9111   // At that time, we may have inserted bitcasts from integer to float.
9112   // If these bitcasts have survived DAGCombine, change the lowering of this
9113   // BUILD_VECTOR in something more vector friendly, i.e., that does not
9114   // force to use floating point types.
9115
9116   // Make sure we can change the type of the vector.
9117   // This is possible iff:
9118   // 1. The vector is only used in a bitcast to a integer type. I.e.,
9119   //    1.1. Vector is used only once.
9120   //    1.2. Use is a bit convert to an integer type.
9121   // 2. The size of its operands are 32-bits (64-bits are not legal).
9122   EVT VT = N->getValueType(0);
9123   EVT EltVT = VT.getVectorElementType();
9124
9125   // Check 1.1. and 2.
9126   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9127     return SDValue();
9128
9129   // By construction, the input type must be float.
9130   assert(EltVT == MVT::f32 && "Unexpected type!");
9131
9132   // Check 1.2.
9133   SDNode *Use = *N->use_begin();
9134   if (Use->getOpcode() != ISD::BITCAST ||
9135       Use->getValueType(0).isFloatingPoint())
9136     return SDValue();
9137
9138   // Check profitability.
9139   // Model is, if more than half of the relevant operands are bitcast from
9140   // i32, turn the build_vector into a sequence of insert_vector_elt.
9141   // Relevant operands are everything that is not statically
9142   // (i.e., at compile time) bitcasted.
9143   unsigned NumOfBitCastedElts = 0;
9144   unsigned NumElts = VT.getVectorNumElements();
9145   unsigned NumOfRelevantElts = NumElts;
9146   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9147     SDValue Elt = N->getOperand(Idx);
9148     if (Elt->getOpcode() == ISD::BITCAST) {
9149       // Assume only bit cast to i32 will go away.
9150       if (Elt->getOperand(0).getValueType() == MVT::i32)
9151         ++NumOfBitCastedElts;
9152     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9153       // Constants are statically casted, thus do not count them as
9154       // relevant operands.
9155       --NumOfRelevantElts;
9156   }
9157
9158   // Check if more than half of the elements require a non-free bitcast.
9159   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9160     return SDValue();
9161
9162   SelectionDAG &DAG = DCI.DAG;
9163   // Create the new vector type.
9164   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9165   // Check if the type is legal.
9166   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9167   if (!TLI.isTypeLegal(VecVT))
9168     return SDValue();
9169
9170   // Combine:
9171   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9172   // => BITCAST INSERT_VECTOR_ELT
9173   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9174   //                      (BITCAST EN), N.
9175   SDValue Vec = DAG.getUNDEF(VecVT);
9176   SDLoc dl(N);
9177   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9178     SDValue V = N->getOperand(Idx);
9179     if (V.getOpcode() == ISD::UNDEF)
9180       continue;
9181     if (V.getOpcode() == ISD::BITCAST &&
9182         V->getOperand(0).getValueType() == MVT::i32)
9183       // Fold obvious case.
9184       V = V.getOperand(0);
9185     else {
9186       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 
9187       // Make the DAGCombiner fold the bitcasts.
9188       DCI.AddToWorklist(V.getNode());
9189     }
9190     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
9191     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9192   }
9193   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9194   // Make the DAGCombiner fold the bitcasts.
9195   DCI.AddToWorklist(Vec.getNode());
9196   return Vec;
9197 }
9198
9199 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9200 /// ISD::INSERT_VECTOR_ELT.
9201 static SDValue PerformInsertEltCombine(SDNode *N,
9202                                        TargetLowering::DAGCombinerInfo &DCI) {
9203   // Bitcast an i64 load inserted into a vector to f64.
9204   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9205   EVT VT = N->getValueType(0);
9206   SDNode *Elt = N->getOperand(1).getNode();
9207   if (VT.getVectorElementType() != MVT::i64 ||
9208       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9209     return SDValue();
9210
9211   SelectionDAG &DAG = DCI.DAG;
9212   SDLoc dl(N);
9213   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9214                                  VT.getVectorNumElements());
9215   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9216   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9217   // Make the DAGCombiner fold the bitcasts.
9218   DCI.AddToWorklist(Vec.getNode());
9219   DCI.AddToWorklist(V.getNode());
9220   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9221                                Vec, V, N->getOperand(2));
9222   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9223 }
9224
9225 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9226 /// ISD::VECTOR_SHUFFLE.
9227 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9228   // The LLVM shufflevector instruction does not require the shuffle mask
9229   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9230   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
9231   // operands do not match the mask length, they are extended by concatenating
9232   // them with undef vectors.  That is probably the right thing for other
9233   // targets, but for NEON it is better to concatenate two double-register
9234   // size vector operands into a single quad-register size vector.  Do that
9235   // transformation here:
9236   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
9237   //   shuffle(concat(v1, v2), undef)
9238   SDValue Op0 = N->getOperand(0);
9239   SDValue Op1 = N->getOperand(1);
9240   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9241       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9242       Op0.getNumOperands() != 2 ||
9243       Op1.getNumOperands() != 2)
9244     return SDValue();
9245   SDValue Concat0Op1 = Op0.getOperand(1);
9246   SDValue Concat1Op1 = Op1.getOperand(1);
9247   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9248       Concat1Op1.getOpcode() != ISD::UNDEF)
9249     return SDValue();
9250   // Skip the transformation if any of the types are illegal.
9251   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9252   EVT VT = N->getValueType(0);
9253   if (!TLI.isTypeLegal(VT) ||
9254       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9255       !TLI.isTypeLegal(Concat1Op1.getValueType()))
9256     return SDValue();
9257
9258   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9259                                   Op0.getOperand(0), Op1.getOperand(0));
9260   // Translate the shuffle mask.
9261   SmallVector<int, 16> NewMask;
9262   unsigned NumElts = VT.getVectorNumElements();
9263   unsigned HalfElts = NumElts/2;
9264   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9265   for (unsigned n = 0; n < NumElts; ++n) {
9266     int MaskElt = SVN->getMaskElt(n);
9267     int NewElt = -1;
9268     if (MaskElt < (int)HalfElts)
9269       NewElt = MaskElt;
9270     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9271       NewElt = HalfElts + MaskElt - NumElts;
9272     NewMask.push_back(NewElt);
9273   }
9274   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9275                               DAG.getUNDEF(VT), NewMask.data());
9276 }
9277
9278 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
9279 /// NEON load/store intrinsics to merge base address updates.
9280 static SDValue CombineBaseUpdate(SDNode *N,
9281                                  TargetLowering::DAGCombinerInfo &DCI) {
9282   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9283     return SDValue();
9284
9285   SelectionDAG &DAG = DCI.DAG;
9286   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9287                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9288   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
9289   SDValue Addr = N->getOperand(AddrOpIdx);
9290
9291   // Search for a use of the address operand that is an increment.
9292   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9293          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9294     SDNode *User = *UI;
9295     if (User->getOpcode() != ISD::ADD ||
9296         UI.getUse().getResNo() != Addr.getResNo())
9297       continue;
9298
9299     // Check that the add is independent of the load/store.  Otherwise, folding
9300     // it would create a cycle.
9301     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9302       continue;
9303
9304     // Find the new opcode for the updating load/store.
9305     bool isLoad = true;
9306     bool isLaneOp = false;
9307     unsigned NewOpc = 0;
9308     unsigned NumVecs = 0;
9309     if (isIntrinsic) {
9310       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9311       switch (IntNo) {
9312       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9313       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9314         NumVecs = 1; break;
9315       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9316         NumVecs = 2; break;
9317       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9318         NumVecs = 3; break;
9319       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9320         NumVecs = 4; break;
9321       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9322         NumVecs = 2; isLaneOp = true; break;
9323       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9324         NumVecs = 3; isLaneOp = true; break;
9325       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9326         NumVecs = 4; isLaneOp = true; break;
9327       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9328         NumVecs = 1; isLoad = false; break;
9329       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9330         NumVecs = 2; isLoad = false; break;
9331       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9332         NumVecs = 3; isLoad = false; break;
9333       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9334         NumVecs = 4; isLoad = false; break;
9335       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9336         NumVecs = 2; isLoad = false; isLaneOp = true; break;
9337       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9338         NumVecs = 3; isLoad = false; isLaneOp = true; break;
9339       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9340         NumVecs = 4; isLoad = false; isLaneOp = true; break;
9341       }
9342     } else {
9343       isLaneOp = true;
9344       switch (N->getOpcode()) {
9345       default: llvm_unreachable("unexpected opcode for Neon base update");
9346       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9347       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9348       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9349       }
9350     }
9351
9352     // Find the size of memory referenced by the load/store.
9353     EVT VecTy;
9354     if (isLoad)
9355       VecTy = N->getValueType(0);
9356     else
9357       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9358     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9359     if (isLaneOp)
9360       NumBytes /= VecTy.getVectorNumElements();
9361
9362     // If the increment is a constant, it must match the memory ref size.
9363     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9364     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9365       uint64_t IncVal = CInc->getZExtValue();
9366       if (IncVal != NumBytes)
9367         continue;
9368     } else if (NumBytes >= 3 * 16) {
9369       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9370       // separate instructions that make it harder to use a non-constant update.
9371       continue;
9372     }
9373
9374     // Create the new updating load/store node.
9375     EVT Tys[6];
9376     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
9377     unsigned n;
9378     for (n = 0; n < NumResultVecs; ++n)
9379       Tys[n] = VecTy;
9380     Tys[n++] = MVT::i32;
9381     Tys[n] = MVT::Other;
9382     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
9383     SmallVector<SDValue, 8> Ops;
9384     Ops.push_back(N->getOperand(0)); // incoming chain
9385     Ops.push_back(N->getOperand(AddrOpIdx));
9386     Ops.push_back(Inc);
9387     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
9388       Ops.push_back(N->getOperand(i));
9389     }
9390     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9391     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9392                                            Ops.data(), Ops.size(),
9393                                            MemInt->getMemoryVT(),
9394                                            MemInt->getMemOperand());
9395
9396     // Update the uses.
9397     std::vector<SDValue> NewResults;
9398     for (unsigned i = 0; i < NumResultVecs; ++i) {
9399       NewResults.push_back(SDValue(UpdN.getNode(), i));
9400     }
9401     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9402     DCI.CombineTo(N, NewResults);
9403     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9404
9405     break;
9406   }
9407   return SDValue();
9408 }
9409
9410 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9411 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9412 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9413 /// return true.
9414 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9415   SelectionDAG &DAG = DCI.DAG;
9416   EVT VT = N->getValueType(0);
9417   // vldN-dup instructions only support 64-bit vectors for N > 1.
9418   if (!VT.is64BitVector())
9419     return false;
9420
9421   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9422   SDNode *VLD = N->getOperand(0).getNode();
9423   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9424     return false;
9425   unsigned NumVecs = 0;
9426   unsigned NewOpc = 0;
9427   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9428   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9429     NumVecs = 2;
9430     NewOpc = ARMISD::VLD2DUP;
9431   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9432     NumVecs = 3;
9433     NewOpc = ARMISD::VLD3DUP;
9434   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9435     NumVecs = 4;
9436     NewOpc = ARMISD::VLD4DUP;
9437   } else {
9438     return false;
9439   }
9440
9441   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9442   // numbers match the load.
9443   unsigned VLDLaneNo =
9444     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9445   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9446        UI != UE; ++UI) {
9447     // Ignore uses of the chain result.
9448     if (UI.getUse().getResNo() == NumVecs)
9449       continue;
9450     SDNode *User = *UI;
9451     if (User->getOpcode() != ARMISD::VDUPLANE ||
9452         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9453       return false;
9454   }
9455
9456   // Create the vldN-dup node.
9457   EVT Tys[5];
9458   unsigned n;
9459   for (n = 0; n < NumVecs; ++n)
9460     Tys[n] = VT;
9461   Tys[n] = MVT::Other;
9462   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
9463   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9464   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9465   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9466                                            Ops, 2, VLDMemInt->getMemoryVT(),
9467                                            VLDMemInt->getMemOperand());
9468
9469   // Update the uses.
9470   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9471        UI != UE; ++UI) {
9472     unsigned ResNo = UI.getUse().getResNo();
9473     // Ignore uses of the chain result.
9474     if (ResNo == NumVecs)
9475       continue;
9476     SDNode *User = *UI;
9477     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9478   }
9479
9480   // Now the vldN-lane intrinsic is dead except for its chain result.
9481   // Update uses of the chain.
9482   std::vector<SDValue> VLDDupResults;
9483   for (unsigned n = 0; n < NumVecs; ++n)
9484     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9485   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9486   DCI.CombineTo(VLD, VLDDupResults);
9487
9488   return true;
9489 }
9490
9491 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9492 /// ARMISD::VDUPLANE.
9493 static SDValue PerformVDUPLANECombine(SDNode *N,
9494                                       TargetLowering::DAGCombinerInfo &DCI) {
9495   SDValue Op = N->getOperand(0);
9496
9497   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9498   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9499   if (CombineVLDDUP(N, DCI))
9500     return SDValue(N, 0);
9501
9502   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9503   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9504   while (Op.getOpcode() == ISD::BITCAST)
9505     Op = Op.getOperand(0);
9506   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9507     return SDValue();
9508
9509   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9510   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9511   // The canonical VMOV for a zero vector uses a 32-bit element size.
9512   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9513   unsigned EltBits;
9514   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9515     EltSize = 8;
9516   EVT VT = N->getValueType(0);
9517   if (EltSize > VT.getVectorElementType().getSizeInBits())
9518     return SDValue();
9519
9520   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9521 }
9522
9523 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9524 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9525 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9526 {
9527   integerPart cN;
9528   integerPart c0 = 0;
9529   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9530        I != E; I++) {
9531     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9532     if (!C)
9533       return false;
9534
9535     bool isExact;
9536     APFloat APF = C->getValueAPF();
9537     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9538         != APFloat::opOK || !isExact)
9539       return false;
9540
9541     c0 = (I == 0) ? cN : c0;
9542     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9543       return false;
9544   }
9545   C = c0;
9546   return true;
9547 }
9548
9549 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9550 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9551 /// when the VMUL has a constant operand that is a power of 2.
9552 ///
9553 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9554 ///  vmul.f32        d16, d17, d16
9555 ///  vcvt.s32.f32    d16, d16
9556 /// becomes:
9557 ///  vcvt.s32.f32    d16, d16, #3
9558 static SDValue PerformVCVTCombine(SDNode *N,
9559                                   TargetLowering::DAGCombinerInfo &DCI,
9560                                   const ARMSubtarget *Subtarget) {
9561   SelectionDAG &DAG = DCI.DAG;
9562   SDValue Op = N->getOperand(0);
9563
9564   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9565       Op.getOpcode() != ISD::FMUL)
9566     return SDValue();
9567
9568   uint64_t C;
9569   SDValue N0 = Op->getOperand(0);
9570   SDValue ConstVec = Op->getOperand(1);
9571   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9572
9573   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9574       !isConstVecPow2(ConstVec, isSigned, C))
9575     return SDValue();
9576
9577   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9578   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9579   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9580     // These instructions only exist converting from f32 to i32. We can handle
9581     // smaller integers by generating an extra truncate, but larger ones would
9582     // be lossy.
9583     return SDValue();
9584   }
9585
9586   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9587     Intrinsic::arm_neon_vcvtfp2fxu;
9588   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9589   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9590                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9591                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9592                                  DAG.getConstant(Log2_64(C), MVT::i32));
9593
9594   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9595     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9596
9597   return FixConv;
9598 }
9599
9600 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9601 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9602 /// when the VDIV has a constant operand that is a power of 2.
9603 ///
9604 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9605 ///  vcvt.f32.s32    d16, d16
9606 ///  vdiv.f32        d16, d17, d16
9607 /// becomes:
9608 ///  vcvt.f32.s32    d16, d16, #3
9609 static SDValue PerformVDIVCombine(SDNode *N,
9610                                   TargetLowering::DAGCombinerInfo &DCI,
9611                                   const ARMSubtarget *Subtarget) {
9612   SelectionDAG &DAG = DCI.DAG;
9613   SDValue Op = N->getOperand(0);
9614   unsigned OpOpcode = Op.getNode()->getOpcode();
9615
9616   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9617       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9618     return SDValue();
9619
9620   uint64_t C;
9621   SDValue ConstVec = N->getOperand(1);
9622   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9623
9624   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9625       !isConstVecPow2(ConstVec, isSigned, C))
9626     return SDValue();
9627
9628   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9629   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9630   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9631     // These instructions only exist converting from i32 to f32. We can handle
9632     // smaller integers by generating an extra extend, but larger ones would
9633     // be lossy.
9634     return SDValue();
9635   }
9636
9637   SDValue ConvInput = Op.getOperand(0);
9638   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9639   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9640     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9641                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9642                             ConvInput);
9643
9644   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9645     Intrinsic::arm_neon_vcvtfxu2fp;
9646   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9647                      Op.getValueType(),
9648                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9649                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9650 }
9651
9652 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9653 /// operand of a vector shift operation, where all the elements of the
9654 /// build_vector must have the same constant integer value.
9655 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9656   // Ignore bit_converts.
9657   while (Op.getOpcode() == ISD::BITCAST)
9658     Op = Op.getOperand(0);
9659   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9660   APInt SplatBits, SplatUndef;
9661   unsigned SplatBitSize;
9662   bool HasAnyUndefs;
9663   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9664                                       HasAnyUndefs, ElementBits) ||
9665       SplatBitSize > ElementBits)
9666     return false;
9667   Cnt = SplatBits.getSExtValue();
9668   return true;
9669 }
9670
9671 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9672 /// operand of a vector shift left operation.  That value must be in the range:
9673 ///   0 <= Value < ElementBits for a left shift; or
9674 ///   0 <= Value <= ElementBits for a long left shift.
9675 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9676   assert(VT.isVector() && "vector shift count is not a vector type");
9677   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9678   if (! getVShiftImm(Op, ElementBits, Cnt))
9679     return false;
9680   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9681 }
9682
9683 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9684 /// operand of a vector shift right operation.  For a shift opcode, the value
9685 /// is positive, but for an intrinsic the value count must be negative. The
9686 /// absolute value must be in the range:
9687 ///   1 <= |Value| <= ElementBits for a right shift; or
9688 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9689 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9690                          int64_t &Cnt) {
9691   assert(VT.isVector() && "vector shift count is not a vector type");
9692   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9693   if (! getVShiftImm(Op, ElementBits, Cnt))
9694     return false;
9695   if (isIntrinsic)
9696     Cnt = -Cnt;
9697   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9698 }
9699
9700 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9701 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9702   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9703   switch (IntNo) {
9704   default:
9705     // Don't do anything for most intrinsics.
9706     break;
9707
9708   // Vector shifts: check for immediate versions and lower them.
9709   // Note: This is done during DAG combining instead of DAG legalizing because
9710   // the build_vectors for 64-bit vector element shift counts are generally
9711   // not legal, and it is hard to see their values after they get legalized to
9712   // loads from a constant pool.
9713   case Intrinsic::arm_neon_vshifts:
9714   case Intrinsic::arm_neon_vshiftu:
9715   case Intrinsic::arm_neon_vshiftls:
9716   case Intrinsic::arm_neon_vshiftlu:
9717   case Intrinsic::arm_neon_vshiftn:
9718   case Intrinsic::arm_neon_vrshifts:
9719   case Intrinsic::arm_neon_vrshiftu:
9720   case Intrinsic::arm_neon_vrshiftn:
9721   case Intrinsic::arm_neon_vqshifts:
9722   case Intrinsic::arm_neon_vqshiftu:
9723   case Intrinsic::arm_neon_vqshiftsu:
9724   case Intrinsic::arm_neon_vqshiftns:
9725   case Intrinsic::arm_neon_vqshiftnu:
9726   case Intrinsic::arm_neon_vqshiftnsu:
9727   case Intrinsic::arm_neon_vqrshiftns:
9728   case Intrinsic::arm_neon_vqrshiftnu:
9729   case Intrinsic::arm_neon_vqrshiftnsu: {
9730     EVT VT = N->getOperand(1).getValueType();
9731     int64_t Cnt;
9732     unsigned VShiftOpc = 0;
9733
9734     switch (IntNo) {
9735     case Intrinsic::arm_neon_vshifts:
9736     case Intrinsic::arm_neon_vshiftu:
9737       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9738         VShiftOpc = ARMISD::VSHL;
9739         break;
9740       }
9741       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9742         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9743                      ARMISD::VSHRs : ARMISD::VSHRu);
9744         break;
9745       }
9746       return SDValue();
9747
9748     case Intrinsic::arm_neon_vshiftls:
9749     case Intrinsic::arm_neon_vshiftlu:
9750       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
9751         break;
9752       llvm_unreachable("invalid shift count for vshll intrinsic");
9753
9754     case Intrinsic::arm_neon_vrshifts:
9755     case Intrinsic::arm_neon_vrshiftu:
9756       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9757         break;
9758       return SDValue();
9759
9760     case Intrinsic::arm_neon_vqshifts:
9761     case Intrinsic::arm_neon_vqshiftu:
9762       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9763         break;
9764       return SDValue();
9765
9766     case Intrinsic::arm_neon_vqshiftsu:
9767       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9768         break;
9769       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9770
9771     case Intrinsic::arm_neon_vshiftn:
9772     case Intrinsic::arm_neon_vrshiftn:
9773     case Intrinsic::arm_neon_vqshiftns:
9774     case Intrinsic::arm_neon_vqshiftnu:
9775     case Intrinsic::arm_neon_vqshiftnsu:
9776     case Intrinsic::arm_neon_vqrshiftns:
9777     case Intrinsic::arm_neon_vqrshiftnu:
9778     case Intrinsic::arm_neon_vqrshiftnsu:
9779       // Narrowing shifts require an immediate right shift.
9780       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9781         break;
9782       llvm_unreachable("invalid shift count for narrowing vector shift "
9783                        "intrinsic");
9784
9785     default:
9786       llvm_unreachable("unhandled vector shift");
9787     }
9788
9789     switch (IntNo) {
9790     case Intrinsic::arm_neon_vshifts:
9791     case Intrinsic::arm_neon_vshiftu:
9792       // Opcode already set above.
9793       break;
9794     case Intrinsic::arm_neon_vshiftls:
9795     case Intrinsic::arm_neon_vshiftlu:
9796       if (Cnt == VT.getVectorElementType().getSizeInBits())
9797         VShiftOpc = ARMISD::VSHLLi;
9798       else
9799         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
9800                      ARMISD::VSHLLs : ARMISD::VSHLLu);
9801       break;
9802     case Intrinsic::arm_neon_vshiftn:
9803       VShiftOpc = ARMISD::VSHRN; break;
9804     case Intrinsic::arm_neon_vrshifts:
9805       VShiftOpc = ARMISD::VRSHRs; break;
9806     case Intrinsic::arm_neon_vrshiftu:
9807       VShiftOpc = ARMISD::VRSHRu; break;
9808     case Intrinsic::arm_neon_vrshiftn:
9809       VShiftOpc = ARMISD::VRSHRN; break;
9810     case Intrinsic::arm_neon_vqshifts:
9811       VShiftOpc = ARMISD::VQSHLs; break;
9812     case Intrinsic::arm_neon_vqshiftu:
9813       VShiftOpc = ARMISD::VQSHLu; break;
9814     case Intrinsic::arm_neon_vqshiftsu:
9815       VShiftOpc = ARMISD::VQSHLsu; break;
9816     case Intrinsic::arm_neon_vqshiftns:
9817       VShiftOpc = ARMISD::VQSHRNs; break;
9818     case Intrinsic::arm_neon_vqshiftnu:
9819       VShiftOpc = ARMISD::VQSHRNu; break;
9820     case Intrinsic::arm_neon_vqshiftnsu:
9821       VShiftOpc = ARMISD::VQSHRNsu; break;
9822     case Intrinsic::arm_neon_vqrshiftns:
9823       VShiftOpc = ARMISD::VQRSHRNs; break;
9824     case Intrinsic::arm_neon_vqrshiftnu:
9825       VShiftOpc = ARMISD::VQRSHRNu; break;
9826     case Intrinsic::arm_neon_vqrshiftnsu:
9827       VShiftOpc = ARMISD::VQRSHRNsu; break;
9828     }
9829
9830     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9831                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9832   }
9833
9834   case Intrinsic::arm_neon_vshiftins: {
9835     EVT VT = N->getOperand(1).getValueType();
9836     int64_t Cnt;
9837     unsigned VShiftOpc = 0;
9838
9839     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9840       VShiftOpc = ARMISD::VSLI;
9841     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9842       VShiftOpc = ARMISD::VSRI;
9843     else {
9844       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9845     }
9846
9847     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9848                        N->getOperand(1), N->getOperand(2),
9849                        DAG.getConstant(Cnt, MVT::i32));
9850   }
9851
9852   case Intrinsic::arm_neon_vqrshifts:
9853   case Intrinsic::arm_neon_vqrshiftu:
9854     // No immediate versions of these to check for.
9855     break;
9856   }
9857
9858   return SDValue();
9859 }
9860
9861 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9862 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9863 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9864 /// vector element shift counts are generally not legal, and it is hard to see
9865 /// their values after they get legalized to loads from a constant pool.
9866 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9867                                    const ARMSubtarget *ST) {
9868   EVT VT = N->getValueType(0);
9869   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9870     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9871     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9872     SDValue N1 = N->getOperand(1);
9873     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9874       SDValue N0 = N->getOperand(0);
9875       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9876           DAG.MaskedValueIsZero(N0.getOperand(0),
9877                                 APInt::getHighBitsSet(32, 16)))
9878         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9879     }
9880   }
9881
9882   // Nothing to be done for scalar shifts.
9883   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9884   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9885     return SDValue();
9886
9887   assert(ST->hasNEON() && "unexpected vector shift");
9888   int64_t Cnt;
9889
9890   switch (N->getOpcode()) {
9891   default: llvm_unreachable("unexpected shift opcode");
9892
9893   case ISD::SHL:
9894     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9895       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9896                          DAG.getConstant(Cnt, MVT::i32));
9897     break;
9898
9899   case ISD::SRA:
9900   case ISD::SRL:
9901     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9902       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9903                             ARMISD::VSHRs : ARMISD::VSHRu);
9904       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9905                          DAG.getConstant(Cnt, MVT::i32));
9906     }
9907   }
9908   return SDValue();
9909 }
9910
9911 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9912 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9913 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9914                                     const ARMSubtarget *ST) {
9915   SDValue N0 = N->getOperand(0);
9916
9917   // Check for sign- and zero-extensions of vector extract operations of 8-
9918   // and 16-bit vector elements.  NEON supports these directly.  They are
9919   // handled during DAG combining because type legalization will promote them
9920   // to 32-bit types and it is messy to recognize the operations after that.
9921   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9922     SDValue Vec = N0.getOperand(0);
9923     SDValue Lane = N0.getOperand(1);
9924     EVT VT = N->getValueType(0);
9925     EVT EltVT = N0.getValueType();
9926     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9927
9928     if (VT == MVT::i32 &&
9929         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9930         TLI.isTypeLegal(Vec.getValueType()) &&
9931         isa<ConstantSDNode>(Lane)) {
9932
9933       unsigned Opc = 0;
9934       switch (N->getOpcode()) {
9935       default: llvm_unreachable("unexpected opcode");
9936       case ISD::SIGN_EXTEND:
9937         Opc = ARMISD::VGETLANEs;
9938         break;
9939       case ISD::ZERO_EXTEND:
9940       case ISD::ANY_EXTEND:
9941         Opc = ARMISD::VGETLANEu;
9942         break;
9943       }
9944       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9945     }
9946   }
9947
9948   return SDValue();
9949 }
9950
9951 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9952 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9953 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9954                                        const ARMSubtarget *ST) {
9955   // If the target supports NEON, try to use vmax/vmin instructions for f32
9956   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9957   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9958   // a NaN; only do the transformation when it matches that behavior.
9959
9960   // For now only do this when using NEON for FP operations; if using VFP, it
9961   // is not obvious that the benefit outweighs the cost of switching to the
9962   // NEON pipeline.
9963   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9964       N->getValueType(0) != MVT::f32)
9965     return SDValue();
9966
9967   SDValue CondLHS = N->getOperand(0);
9968   SDValue CondRHS = N->getOperand(1);
9969   SDValue LHS = N->getOperand(2);
9970   SDValue RHS = N->getOperand(3);
9971   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9972
9973   unsigned Opcode = 0;
9974   bool IsReversed;
9975   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9976     IsReversed = false; // x CC y ? x : y
9977   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9978     IsReversed = true ; // x CC y ? y : x
9979   } else {
9980     return SDValue();
9981   }
9982
9983   bool IsUnordered;
9984   switch (CC) {
9985   default: break;
9986   case ISD::SETOLT:
9987   case ISD::SETOLE:
9988   case ISD::SETLT:
9989   case ISD::SETLE:
9990   case ISD::SETULT:
9991   case ISD::SETULE:
9992     // If LHS is NaN, an ordered comparison will be false and the result will
9993     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9994     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9995     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9996     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9997       break;
9998     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9999     // will return -0, so vmin can only be used for unsafe math or if one of
10000     // the operands is known to be nonzero.
10001     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
10002         !DAG.getTarget().Options.UnsafeFPMath &&
10003         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10004       break;
10005     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
10006     break;
10007
10008   case ISD::SETOGT:
10009   case ISD::SETOGE:
10010   case ISD::SETGT:
10011   case ISD::SETGE:
10012   case ISD::SETUGT:
10013   case ISD::SETUGE:
10014     // If LHS is NaN, an ordered comparison will be false and the result will
10015     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
10016     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
10017     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
10018     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10019       break;
10020     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
10021     // will return +0, so vmax can only be used for unsafe math or if one of
10022     // the operands is known to be nonzero.
10023     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
10024         !DAG.getTarget().Options.UnsafeFPMath &&
10025         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10026       break;
10027     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
10028     break;
10029   }
10030
10031   if (!Opcode)
10032     return SDValue();
10033   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
10034 }
10035
10036 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10037 SDValue
10038 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10039   SDValue Cmp = N->getOperand(4);
10040   if (Cmp.getOpcode() != ARMISD::CMPZ)
10041     // Only looking at EQ and NE cases.
10042     return SDValue();
10043
10044   EVT VT = N->getValueType(0);
10045   SDLoc dl(N);
10046   SDValue LHS = Cmp.getOperand(0);
10047   SDValue RHS = Cmp.getOperand(1);
10048   SDValue FalseVal = N->getOperand(0);
10049   SDValue TrueVal = N->getOperand(1);
10050   SDValue ARMcc = N->getOperand(2);
10051   ARMCC::CondCodes CC =
10052     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10053
10054   // Simplify
10055   //   mov     r1, r0
10056   //   cmp     r1, x
10057   //   mov     r0, y
10058   //   moveq   r0, x
10059   // to
10060   //   cmp     r0, x
10061   //   movne   r0, y
10062   //
10063   //   mov     r1, r0
10064   //   cmp     r1, x
10065   //   mov     r0, x
10066   //   movne   r0, y
10067   // to
10068   //   cmp     r0, x
10069   //   movne   r0, y
10070   /// FIXME: Turn this into a target neutral optimization?
10071   SDValue Res;
10072   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10073     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10074                       N->getOperand(3), Cmp);
10075   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10076     SDValue ARMcc;
10077     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10078     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10079                       N->getOperand(3), NewCmp);
10080   }
10081
10082   if (Res.getNode()) {
10083     APInt KnownZero, KnownOne;
10084     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
10085     // Capture demanded bits information that would be otherwise lost.
10086     if (KnownZero == 0xfffffffe)
10087       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10088                         DAG.getValueType(MVT::i1));
10089     else if (KnownZero == 0xffffff00)
10090       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10091                         DAG.getValueType(MVT::i8));
10092     else if (KnownZero == 0xffff0000)
10093       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10094                         DAG.getValueType(MVT::i16));
10095   }
10096
10097   return Res;
10098 }
10099
10100 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10101                                              DAGCombinerInfo &DCI) const {
10102   switch (N->getOpcode()) {
10103   default: break;
10104   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
10105   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
10106   case ISD::SUB:        return PerformSUBCombine(N, DCI);
10107   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
10108   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
10109   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
10110   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
10111   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
10112   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
10113   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10114   case ISD::STORE:      return PerformSTORECombine(N, DCI);
10115   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
10116   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10117   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10118   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10119   case ISD::FP_TO_SINT:
10120   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10121   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
10122   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10123   case ISD::SHL:
10124   case ISD::SRA:
10125   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10126   case ISD::SIGN_EXTEND:
10127   case ISD::ZERO_EXTEND:
10128   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10129   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
10130   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10131   case ARMISD::VLD2DUP:
10132   case ARMISD::VLD3DUP:
10133   case ARMISD::VLD4DUP:
10134     return CombineBaseUpdate(N, DCI);
10135   case ARMISD::BUILD_VECTOR:
10136     return PerformARMBUILD_VECTORCombine(N, DCI);
10137   case ISD::INTRINSIC_VOID:
10138   case ISD::INTRINSIC_W_CHAIN:
10139     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10140     case Intrinsic::arm_neon_vld1:
10141     case Intrinsic::arm_neon_vld2:
10142     case Intrinsic::arm_neon_vld3:
10143     case Intrinsic::arm_neon_vld4:
10144     case Intrinsic::arm_neon_vld2lane:
10145     case Intrinsic::arm_neon_vld3lane:
10146     case Intrinsic::arm_neon_vld4lane:
10147     case Intrinsic::arm_neon_vst1:
10148     case Intrinsic::arm_neon_vst2:
10149     case Intrinsic::arm_neon_vst3:
10150     case Intrinsic::arm_neon_vst4:
10151     case Intrinsic::arm_neon_vst2lane:
10152     case Intrinsic::arm_neon_vst3lane:
10153     case Intrinsic::arm_neon_vst4lane:
10154       return CombineBaseUpdate(N, DCI);
10155     default: break;
10156     }
10157     break;
10158   }
10159   return SDValue();
10160 }
10161
10162 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10163                                                           EVT VT) const {
10164   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10165 }
10166
10167 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
10168   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10169   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10170
10171   switch (VT.getSimpleVT().SimpleTy) {
10172   default:
10173     return false;
10174   case MVT::i8:
10175   case MVT::i16:
10176   case MVT::i32: {
10177     // Unaligned access can use (for example) LRDB, LRDH, LDR
10178     if (AllowsUnaligned) {
10179       if (Fast)
10180         *Fast = Subtarget->hasV7Ops();
10181       return true;
10182     }
10183     return false;
10184   }
10185   case MVT::f64:
10186   case MVT::v2f64: {
10187     // For any little-endian targets with neon, we can support unaligned ld/st
10188     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10189     // A big-endian target may also explictly support unaligned accesses
10190     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
10191       if (Fast)
10192         *Fast = true;
10193       return true;
10194     }
10195     return false;
10196   }
10197   }
10198 }
10199
10200 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10201                        unsigned AlignCheck) {
10202   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10203           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10204 }
10205
10206 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10207                                            unsigned DstAlign, unsigned SrcAlign,
10208                                            bool IsMemset, bool ZeroMemset,
10209                                            bool MemcpyStrSrc,
10210                                            MachineFunction &MF) const {
10211   const Function *F = MF.getFunction();
10212
10213   // See if we can use NEON instructions for this...
10214   if ((!IsMemset || ZeroMemset) &&
10215       Subtarget->hasNEON() &&
10216       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
10217                                        Attribute::NoImplicitFloat)) {
10218     bool Fast;
10219     if (Size >= 16 &&
10220         (memOpAlign(SrcAlign, DstAlign, 16) ||
10221          (allowsUnalignedMemoryAccesses(MVT::v2f64, &Fast) && Fast))) {
10222       return MVT::v2f64;
10223     } else if (Size >= 8 &&
10224                (memOpAlign(SrcAlign, DstAlign, 8) ||
10225                 (allowsUnalignedMemoryAccesses(MVT::f64, &Fast) && Fast))) {
10226       return MVT::f64;
10227     }
10228   }
10229
10230   // Lowering to i32/i16 if the size permits.
10231   if (Size >= 4)
10232     return MVT::i32;
10233   else if (Size >= 2)
10234     return MVT::i16;
10235
10236   // Let the target-independent logic figure it out.
10237   return MVT::Other;
10238 }
10239
10240 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10241   if (Val.getOpcode() != ISD::LOAD)
10242     return false;
10243
10244   EVT VT1 = Val.getValueType();
10245   if (!VT1.isSimple() || !VT1.isInteger() ||
10246       !VT2.isSimple() || !VT2.isInteger())
10247     return false;
10248
10249   switch (VT1.getSimpleVT().SimpleTy) {
10250   default: break;
10251   case MVT::i1:
10252   case MVT::i8:
10253   case MVT::i16:
10254     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10255     return true;
10256   }
10257
10258   return false;
10259 }
10260
10261 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10262   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10263     return false;
10264
10265   if (!isTypeLegal(EVT::getEVT(Ty1)))
10266     return false;
10267
10268   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10269
10270   // Assuming the caller doesn't have a zeroext or signext return parameter,
10271   // truncation all the way down to i1 is valid.
10272   return true;
10273 }
10274
10275
10276 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10277   if (V < 0)
10278     return false;
10279
10280   unsigned Scale = 1;
10281   switch (VT.getSimpleVT().SimpleTy) {
10282   default: return false;
10283   case MVT::i1:
10284   case MVT::i8:
10285     // Scale == 1;
10286     break;
10287   case MVT::i16:
10288     // Scale == 2;
10289     Scale = 2;
10290     break;
10291   case MVT::i32:
10292     // Scale == 4;
10293     Scale = 4;
10294     break;
10295   }
10296
10297   if ((V & (Scale - 1)) != 0)
10298     return false;
10299   V /= Scale;
10300   return V == (V & ((1LL << 5) - 1));
10301 }
10302
10303 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10304                                       const ARMSubtarget *Subtarget) {
10305   bool isNeg = false;
10306   if (V < 0) {
10307     isNeg = true;
10308     V = - V;
10309   }
10310
10311   switch (VT.getSimpleVT().SimpleTy) {
10312   default: return false;
10313   case MVT::i1:
10314   case MVT::i8:
10315   case MVT::i16:
10316   case MVT::i32:
10317     // + imm12 or - imm8
10318     if (isNeg)
10319       return V == (V & ((1LL << 8) - 1));
10320     return V == (V & ((1LL << 12) - 1));
10321   case MVT::f32:
10322   case MVT::f64:
10323     // Same as ARM mode. FIXME: NEON?
10324     if (!Subtarget->hasVFP2())
10325       return false;
10326     if ((V & 3) != 0)
10327       return false;
10328     V >>= 2;
10329     return V == (V & ((1LL << 8) - 1));
10330   }
10331 }
10332
10333 /// isLegalAddressImmediate - Return true if the integer value can be used
10334 /// as the offset of the target addressing mode for load / store of the
10335 /// given type.
10336 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10337                                     const ARMSubtarget *Subtarget) {
10338   if (V == 0)
10339     return true;
10340
10341   if (!VT.isSimple())
10342     return false;
10343
10344   if (Subtarget->isThumb1Only())
10345     return isLegalT1AddressImmediate(V, VT);
10346   else if (Subtarget->isThumb2())
10347     return isLegalT2AddressImmediate(V, VT, Subtarget);
10348
10349   // ARM mode.
10350   if (V < 0)
10351     V = - V;
10352   switch (VT.getSimpleVT().SimpleTy) {
10353   default: return false;
10354   case MVT::i1:
10355   case MVT::i8:
10356   case MVT::i32:
10357     // +- imm12
10358     return V == (V & ((1LL << 12) - 1));
10359   case MVT::i16:
10360     // +- imm8
10361     return V == (V & ((1LL << 8) - 1));
10362   case MVT::f32:
10363   case MVT::f64:
10364     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10365       return false;
10366     if ((V & 3) != 0)
10367       return false;
10368     V >>= 2;
10369     return V == (V & ((1LL << 8) - 1));
10370   }
10371 }
10372
10373 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10374                                                       EVT VT) const {
10375   int Scale = AM.Scale;
10376   if (Scale < 0)
10377     return false;
10378
10379   switch (VT.getSimpleVT().SimpleTy) {
10380   default: return false;
10381   case MVT::i1:
10382   case MVT::i8:
10383   case MVT::i16:
10384   case MVT::i32:
10385     if (Scale == 1)
10386       return true;
10387     // r + r << imm
10388     Scale = Scale & ~1;
10389     return Scale == 2 || Scale == 4 || Scale == 8;
10390   case MVT::i64:
10391     // r + r
10392     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10393       return true;
10394     return false;
10395   case MVT::isVoid:
10396     // Note, we allow "void" uses (basically, uses that aren't loads or
10397     // stores), because arm allows folding a scale into many arithmetic
10398     // operations.  This should be made more precise and revisited later.
10399
10400     // Allow r << imm, but the imm has to be a multiple of two.
10401     if (Scale & 1) return false;
10402     return isPowerOf2_32(Scale);
10403   }
10404 }
10405
10406 /// isLegalAddressingMode - Return true if the addressing mode represented
10407 /// by AM is legal for this target, for a load/store of the specified type.
10408 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10409                                               Type *Ty) const {
10410   EVT VT = getValueType(Ty, true);
10411   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10412     return false;
10413
10414   // Can never fold addr of global into load/store.
10415   if (AM.BaseGV)
10416     return false;
10417
10418   switch (AM.Scale) {
10419   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10420     break;
10421   case 1:
10422     if (Subtarget->isThumb1Only())
10423       return false;
10424     // FALL THROUGH.
10425   default:
10426     // ARM doesn't support any R+R*scale+imm addr modes.
10427     if (AM.BaseOffs)
10428       return false;
10429
10430     if (!VT.isSimple())
10431       return false;
10432
10433     if (Subtarget->isThumb2())
10434       return isLegalT2ScaledAddressingMode(AM, VT);
10435
10436     int Scale = AM.Scale;
10437     switch (VT.getSimpleVT().SimpleTy) {
10438     default: return false;
10439     case MVT::i1:
10440     case MVT::i8:
10441     case MVT::i32:
10442       if (Scale < 0) Scale = -Scale;
10443       if (Scale == 1)
10444         return true;
10445       // r + r << imm
10446       return isPowerOf2_32(Scale & ~1);
10447     case MVT::i16:
10448     case MVT::i64:
10449       // r + r
10450       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10451         return true;
10452       return false;
10453
10454     case MVT::isVoid:
10455       // Note, we allow "void" uses (basically, uses that aren't loads or
10456       // stores), because arm allows folding a scale into many arithmetic
10457       // operations.  This should be made more precise and revisited later.
10458
10459       // Allow r << imm, but the imm has to be a multiple of two.
10460       if (Scale & 1) return false;
10461       return isPowerOf2_32(Scale);
10462     }
10463   }
10464   return true;
10465 }
10466
10467 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10468 /// icmp immediate, that is the target has icmp instructions which can compare
10469 /// a register against the immediate without having to materialize the
10470 /// immediate into a register.
10471 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10472   // Thumb2 and ARM modes can use cmn for negative immediates.
10473   if (!Subtarget->isThumb())
10474     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10475   if (Subtarget->isThumb2())
10476     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10477   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10478   return Imm >= 0 && Imm <= 255;
10479 }
10480
10481 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10482 /// *or sub* immediate, that is the target has add or sub instructions which can
10483 /// add a register with the immediate without having to materialize the
10484 /// immediate into a register.
10485 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10486   // Same encoding for add/sub, just flip the sign.
10487   int64_t AbsImm = llvm::abs64(Imm);
10488   if (!Subtarget->isThumb())
10489     return ARM_AM::getSOImmVal(AbsImm) != -1;
10490   if (Subtarget->isThumb2())
10491     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10492   // Thumb1 only has 8-bit unsigned immediate.
10493   return AbsImm >= 0 && AbsImm <= 255;
10494 }
10495
10496 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10497                                       bool isSEXTLoad, SDValue &Base,
10498                                       SDValue &Offset, bool &isInc,
10499                                       SelectionDAG &DAG) {
10500   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10501     return false;
10502
10503   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10504     // AddressingMode 3
10505     Base = Ptr->getOperand(0);
10506     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10507       int RHSC = (int)RHS->getZExtValue();
10508       if (RHSC < 0 && RHSC > -256) {
10509         assert(Ptr->getOpcode() == ISD::ADD);
10510         isInc = false;
10511         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10512         return true;
10513       }
10514     }
10515     isInc = (Ptr->getOpcode() == ISD::ADD);
10516     Offset = Ptr->getOperand(1);
10517     return true;
10518   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10519     // AddressingMode 2
10520     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10521       int RHSC = (int)RHS->getZExtValue();
10522       if (RHSC < 0 && RHSC > -0x1000) {
10523         assert(Ptr->getOpcode() == ISD::ADD);
10524         isInc = false;
10525         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10526         Base = Ptr->getOperand(0);
10527         return true;
10528       }
10529     }
10530
10531     if (Ptr->getOpcode() == ISD::ADD) {
10532       isInc = true;
10533       ARM_AM::ShiftOpc ShOpcVal=
10534         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10535       if (ShOpcVal != ARM_AM::no_shift) {
10536         Base = Ptr->getOperand(1);
10537         Offset = Ptr->getOperand(0);
10538       } else {
10539         Base = Ptr->getOperand(0);
10540         Offset = Ptr->getOperand(1);
10541       }
10542       return true;
10543     }
10544
10545     isInc = (Ptr->getOpcode() == ISD::ADD);
10546     Base = Ptr->getOperand(0);
10547     Offset = Ptr->getOperand(1);
10548     return true;
10549   }
10550
10551   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10552   return false;
10553 }
10554
10555 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10556                                      bool isSEXTLoad, SDValue &Base,
10557                                      SDValue &Offset, bool &isInc,
10558                                      SelectionDAG &DAG) {
10559   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10560     return false;
10561
10562   Base = Ptr->getOperand(0);
10563   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10564     int RHSC = (int)RHS->getZExtValue();
10565     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10566       assert(Ptr->getOpcode() == ISD::ADD);
10567       isInc = false;
10568       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10569       return true;
10570     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10571       isInc = Ptr->getOpcode() == ISD::ADD;
10572       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10573       return true;
10574     }
10575   }
10576
10577   return false;
10578 }
10579
10580 /// getPreIndexedAddressParts - returns true by value, base pointer and
10581 /// offset pointer and addressing mode by reference if the node's address
10582 /// can be legally represented as pre-indexed load / store address.
10583 bool
10584 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10585                                              SDValue &Offset,
10586                                              ISD::MemIndexedMode &AM,
10587                                              SelectionDAG &DAG) const {
10588   if (Subtarget->isThumb1Only())
10589     return false;
10590
10591   EVT VT;
10592   SDValue Ptr;
10593   bool isSEXTLoad = false;
10594   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10595     Ptr = LD->getBasePtr();
10596     VT  = LD->getMemoryVT();
10597     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10598   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10599     Ptr = ST->getBasePtr();
10600     VT  = ST->getMemoryVT();
10601   } else
10602     return false;
10603
10604   bool isInc;
10605   bool isLegal = false;
10606   if (Subtarget->isThumb2())
10607     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10608                                        Offset, isInc, DAG);
10609   else
10610     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10611                                         Offset, isInc, DAG);
10612   if (!isLegal)
10613     return false;
10614
10615   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10616   return true;
10617 }
10618
10619 /// getPostIndexedAddressParts - returns true by value, base pointer and
10620 /// offset pointer and addressing mode by reference if this node can be
10621 /// combined with a load / store to form a post-indexed load / store.
10622 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10623                                                    SDValue &Base,
10624                                                    SDValue &Offset,
10625                                                    ISD::MemIndexedMode &AM,
10626                                                    SelectionDAG &DAG) const {
10627   if (Subtarget->isThumb1Only())
10628     return false;
10629
10630   EVT VT;
10631   SDValue Ptr;
10632   bool isSEXTLoad = false;
10633   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10634     VT  = LD->getMemoryVT();
10635     Ptr = LD->getBasePtr();
10636     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10637   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10638     VT  = ST->getMemoryVT();
10639     Ptr = ST->getBasePtr();
10640   } else
10641     return false;
10642
10643   bool isInc;
10644   bool isLegal = false;
10645   if (Subtarget->isThumb2())
10646     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10647                                        isInc, DAG);
10648   else
10649     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10650                                         isInc, DAG);
10651   if (!isLegal)
10652     return false;
10653
10654   if (Ptr != Base) {
10655     // Swap base ptr and offset to catch more post-index load / store when
10656     // it's legal. In Thumb2 mode, offset must be an immediate.
10657     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10658         !Subtarget->isThumb2())
10659       std::swap(Base, Offset);
10660
10661     // Post-indexed load / store update the base pointer.
10662     if (Ptr != Base)
10663       return false;
10664   }
10665
10666   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10667   return true;
10668 }
10669
10670 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10671                                                        APInt &KnownZero,
10672                                                        APInt &KnownOne,
10673                                                        const SelectionDAG &DAG,
10674                                                        unsigned Depth) const {
10675   unsigned BitWidth = KnownOne.getBitWidth();
10676   KnownZero = KnownOne = APInt(BitWidth, 0);
10677   switch (Op.getOpcode()) {
10678   default: break;
10679   case ARMISD::ADDC:
10680   case ARMISD::ADDE:
10681   case ARMISD::SUBC:
10682   case ARMISD::SUBE:
10683     // These nodes' second result is a boolean
10684     if (Op.getResNo() == 0)
10685       break;
10686     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10687     break;
10688   case ARMISD::CMOV: {
10689     // Bits are known zero/one if known on the LHS and RHS.
10690     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10691     if (KnownZero == 0 && KnownOne == 0) return;
10692
10693     APInt KnownZeroRHS, KnownOneRHS;
10694     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10695     KnownZero &= KnownZeroRHS;
10696     KnownOne  &= KnownOneRHS;
10697     return;
10698   }
10699   }
10700 }
10701
10702 //===----------------------------------------------------------------------===//
10703 //                           ARM Inline Assembly Support
10704 //===----------------------------------------------------------------------===//
10705
10706 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10707   // Looking for "rev" which is V6+.
10708   if (!Subtarget->hasV6Ops())
10709     return false;
10710
10711   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10712   std::string AsmStr = IA->getAsmString();
10713   SmallVector<StringRef, 4> AsmPieces;
10714   SplitString(AsmStr, AsmPieces, ";\n");
10715
10716   switch (AsmPieces.size()) {
10717   default: return false;
10718   case 1:
10719     AsmStr = AsmPieces[0];
10720     AsmPieces.clear();
10721     SplitString(AsmStr, AsmPieces, " \t,");
10722
10723     // rev $0, $1
10724     if (AsmPieces.size() == 3 &&
10725         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10726         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10727       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10728       if (Ty && Ty->getBitWidth() == 32)
10729         return IntrinsicLowering::LowerToByteSwap(CI);
10730     }
10731     break;
10732   }
10733
10734   return false;
10735 }
10736
10737 /// getConstraintType - Given a constraint letter, return the type of
10738 /// constraint it is for this target.
10739 ARMTargetLowering::ConstraintType
10740 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10741   if (Constraint.size() == 1) {
10742     switch (Constraint[0]) {
10743     default:  break;
10744     case 'l': return C_RegisterClass;
10745     case 'w': return C_RegisterClass;
10746     case 'h': return C_RegisterClass;
10747     case 'x': return C_RegisterClass;
10748     case 't': return C_RegisterClass;
10749     case 'j': return C_Other; // Constant for movw.
10750       // An address with a single base register. Due to the way we
10751       // currently handle addresses it is the same as an 'r' memory constraint.
10752     case 'Q': return C_Memory;
10753     }
10754   } else if (Constraint.size() == 2) {
10755     switch (Constraint[0]) {
10756     default: break;
10757     // All 'U+' constraints are addresses.
10758     case 'U': return C_Memory;
10759     }
10760   }
10761   return TargetLowering::getConstraintType(Constraint);
10762 }
10763
10764 /// Examine constraint type and operand type and determine a weight value.
10765 /// This object must already have been set up with the operand type
10766 /// and the current alternative constraint selected.
10767 TargetLowering::ConstraintWeight
10768 ARMTargetLowering::getSingleConstraintMatchWeight(
10769     AsmOperandInfo &info, const char *constraint) const {
10770   ConstraintWeight weight = CW_Invalid;
10771   Value *CallOperandVal = info.CallOperandVal;
10772     // If we don't have a value, we can't do a match,
10773     // but allow it at the lowest weight.
10774   if (CallOperandVal == NULL)
10775     return CW_Default;
10776   Type *type = CallOperandVal->getType();
10777   // Look at the constraint type.
10778   switch (*constraint) {
10779   default:
10780     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10781     break;
10782   case 'l':
10783     if (type->isIntegerTy()) {
10784       if (Subtarget->isThumb())
10785         weight = CW_SpecificReg;
10786       else
10787         weight = CW_Register;
10788     }
10789     break;
10790   case 'w':
10791     if (type->isFloatingPointTy())
10792       weight = CW_Register;
10793     break;
10794   }
10795   return weight;
10796 }
10797
10798 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10799 RCPair
10800 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10801                                                 MVT VT) const {
10802   if (Constraint.size() == 1) {
10803     // GCC ARM Constraint Letters
10804     switch (Constraint[0]) {
10805     case 'l': // Low regs or general regs.
10806       if (Subtarget->isThumb())
10807         return RCPair(0U, &ARM::tGPRRegClass);
10808       return RCPair(0U, &ARM::GPRRegClass);
10809     case 'h': // High regs or no regs.
10810       if (Subtarget->isThumb())
10811         return RCPair(0U, &ARM::hGPRRegClass);
10812       break;
10813     case 'r':
10814       return RCPair(0U, &ARM::GPRRegClass);
10815     case 'w':
10816       if (VT == MVT::Other)
10817         break;
10818       if (VT == MVT::f32)
10819         return RCPair(0U, &ARM::SPRRegClass);
10820       if (VT.getSizeInBits() == 64)
10821         return RCPair(0U, &ARM::DPRRegClass);
10822       if (VT.getSizeInBits() == 128)
10823         return RCPair(0U, &ARM::QPRRegClass);
10824       break;
10825     case 'x':
10826       if (VT == MVT::Other)
10827         break;
10828       if (VT == MVT::f32)
10829         return RCPair(0U, &ARM::SPR_8RegClass);
10830       if (VT.getSizeInBits() == 64)
10831         return RCPair(0U, &ARM::DPR_8RegClass);
10832       if (VT.getSizeInBits() == 128)
10833         return RCPair(0U, &ARM::QPR_8RegClass);
10834       break;
10835     case 't':
10836       if (VT == MVT::f32)
10837         return RCPair(0U, &ARM::SPRRegClass);
10838       break;
10839     }
10840   }
10841   if (StringRef("{cc}").equals_lower(Constraint))
10842     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10843
10844   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10845 }
10846
10847 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10848 /// vector.  If it is invalid, don't add anything to Ops.
10849 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10850                                                      std::string &Constraint,
10851                                                      std::vector<SDValue>&Ops,
10852                                                      SelectionDAG &DAG) const {
10853   SDValue Result(0, 0);
10854
10855   // Currently only support length 1 constraints.
10856   if (Constraint.length() != 1) return;
10857
10858   char ConstraintLetter = Constraint[0];
10859   switch (ConstraintLetter) {
10860   default: break;
10861   case 'j':
10862   case 'I': case 'J': case 'K': case 'L':
10863   case 'M': case 'N': case 'O':
10864     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10865     if (!C)
10866       return;
10867
10868     int64_t CVal64 = C->getSExtValue();
10869     int CVal = (int) CVal64;
10870     // None of these constraints allow values larger than 32 bits.  Check
10871     // that the value fits in an int.
10872     if (CVal != CVal64)
10873       return;
10874
10875     switch (ConstraintLetter) {
10876       case 'j':
10877         // Constant suitable for movw, must be between 0 and
10878         // 65535.
10879         if (Subtarget->hasV6T2Ops())
10880           if (CVal >= 0 && CVal <= 65535)
10881             break;
10882         return;
10883       case 'I':
10884         if (Subtarget->isThumb1Only()) {
10885           // This must be a constant between 0 and 255, for ADD
10886           // immediates.
10887           if (CVal >= 0 && CVal <= 255)
10888             break;
10889         } else if (Subtarget->isThumb2()) {
10890           // A constant that can be used as an immediate value in a
10891           // data-processing instruction.
10892           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10893             break;
10894         } else {
10895           // A constant that can be used as an immediate value in a
10896           // data-processing instruction.
10897           if (ARM_AM::getSOImmVal(CVal) != -1)
10898             break;
10899         }
10900         return;
10901
10902       case 'J':
10903         if (Subtarget->isThumb()) {  // FIXME thumb2
10904           // This must be a constant between -255 and -1, for negated ADD
10905           // immediates. This can be used in GCC with an "n" modifier that
10906           // prints the negated value, for use with SUB instructions. It is
10907           // not useful otherwise but is implemented for compatibility.
10908           if (CVal >= -255 && CVal <= -1)
10909             break;
10910         } else {
10911           // This must be a constant between -4095 and 4095. It is not clear
10912           // what this constraint is intended for. Implemented for
10913           // compatibility with GCC.
10914           if (CVal >= -4095 && CVal <= 4095)
10915             break;
10916         }
10917         return;
10918
10919       case 'K':
10920         if (Subtarget->isThumb1Only()) {
10921           // A 32-bit value where only one byte has a nonzero value. Exclude
10922           // zero to match GCC. This constraint is used by GCC internally for
10923           // constants that can be loaded with a move/shift combination.
10924           // It is not useful otherwise but is implemented for compatibility.
10925           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10926             break;
10927         } else if (Subtarget->isThumb2()) {
10928           // A constant whose bitwise inverse can be used as an immediate
10929           // value in a data-processing instruction. This can be used in GCC
10930           // with a "B" modifier that prints the inverted value, for use with
10931           // BIC and MVN instructions. It is not useful otherwise but is
10932           // implemented for compatibility.
10933           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10934             break;
10935         } else {
10936           // A constant whose bitwise inverse can be used as an immediate
10937           // value in a data-processing instruction. This can be used in GCC
10938           // with a "B" modifier that prints the inverted value, for use with
10939           // BIC and MVN instructions. It is not useful otherwise but is
10940           // implemented for compatibility.
10941           if (ARM_AM::getSOImmVal(~CVal) != -1)
10942             break;
10943         }
10944         return;
10945
10946       case 'L':
10947         if (Subtarget->isThumb1Only()) {
10948           // This must be a constant between -7 and 7,
10949           // for 3-operand ADD/SUB immediate instructions.
10950           if (CVal >= -7 && CVal < 7)
10951             break;
10952         } else if (Subtarget->isThumb2()) {
10953           // A constant whose negation can be used as an immediate value in a
10954           // data-processing instruction. This can be used in GCC with an "n"
10955           // modifier that prints the negated value, for use with SUB
10956           // instructions. It is not useful otherwise but is implemented for
10957           // compatibility.
10958           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10959             break;
10960         } else {
10961           // A constant whose negation can be used as an immediate value in a
10962           // data-processing instruction. This can be used in GCC with an "n"
10963           // modifier that prints the negated value, for use with SUB
10964           // instructions. It is not useful otherwise but is implemented for
10965           // compatibility.
10966           if (ARM_AM::getSOImmVal(-CVal) != -1)
10967             break;
10968         }
10969         return;
10970
10971       case 'M':
10972         if (Subtarget->isThumb()) { // FIXME thumb2
10973           // This must be a multiple of 4 between 0 and 1020, for
10974           // ADD sp + immediate.
10975           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10976             break;
10977         } else {
10978           // A power of two or a constant between 0 and 32.  This is used in
10979           // GCC for the shift amount on shifted register operands, but it is
10980           // useful in general for any shift amounts.
10981           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10982             break;
10983         }
10984         return;
10985
10986       case 'N':
10987         if (Subtarget->isThumb()) {  // FIXME thumb2
10988           // This must be a constant between 0 and 31, for shift amounts.
10989           if (CVal >= 0 && CVal <= 31)
10990             break;
10991         }
10992         return;
10993
10994       case 'O':
10995         if (Subtarget->isThumb()) {  // FIXME thumb2
10996           // This must be a multiple of 4 between -508 and 508, for
10997           // ADD/SUB sp = sp + immediate.
10998           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10999             break;
11000         }
11001         return;
11002     }
11003     Result = DAG.getTargetConstant(CVal, Op.getValueType());
11004     break;
11005   }
11006
11007   if (Result.getNode()) {
11008     Ops.push_back(Result);
11009     return;
11010   }
11011   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11012 }
11013
11014 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11015   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
11016   unsigned Opcode = Op->getOpcode();
11017   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11018       "Invalid opcode for Div/Rem lowering");
11019   bool isSigned = (Opcode == ISD::SDIVREM);
11020   EVT VT = Op->getValueType(0);
11021   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11022
11023   RTLIB::Libcall LC;
11024   switch (VT.getSimpleVT().SimpleTy) {
11025   default: llvm_unreachable("Unexpected request for libcall!");
11026   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
11027   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11028   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11029   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11030   }
11031
11032   SDValue InChain = DAG.getEntryNode();
11033
11034   TargetLowering::ArgListTy Args;
11035   TargetLowering::ArgListEntry Entry;
11036   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
11037     EVT ArgVT = Op->getOperand(i).getValueType();
11038     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11039     Entry.Node = Op->getOperand(i);
11040     Entry.Ty = ArgTy;
11041     Entry.isSExt = isSigned;
11042     Entry.isZExt = !isSigned;
11043     Args.push_back(Entry);
11044   }
11045
11046   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11047                                          getPointerTy());
11048
11049   Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
11050
11051   SDLoc dl(Op);
11052   TargetLowering::
11053   CallLoweringInfo CLI(InChain, RetTy, isSigned, !isSigned, false, true,
11054                     0, getLibcallCallingConv(LC), /*isTailCall=*/false,
11055                     /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
11056                     Callee, Args, DAG, dl);
11057   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11058
11059   return CallInfo.first;
11060 }
11061
11062 bool
11063 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11064   // The ARM target isn't yet aware of offsets.
11065   return false;
11066 }
11067
11068 bool ARM::isBitFieldInvertedMask(unsigned v) {
11069   if (v == 0xffffffff)
11070     return false;
11071
11072   // there can be 1's on either or both "outsides", all the "inside"
11073   // bits must be 0's
11074   unsigned TO = CountTrailingOnes_32(v);
11075   unsigned LO = CountLeadingOnes_32(v);
11076   v = (v >> TO) << TO;
11077   v = (v << LO) >> LO;
11078   return v == 0;
11079 }
11080
11081 /// isFPImmLegal - Returns true if the target can instruction select the
11082 /// specified FP immediate natively. If false, the legalizer will
11083 /// materialize the FP immediate as a load from a constant pool.
11084 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11085   if (!Subtarget->hasVFP3())
11086     return false;
11087   if (VT == MVT::f32)
11088     return ARM_AM::getFP32Imm(Imm) != -1;
11089   if (VT == MVT::f64)
11090     return ARM_AM::getFP64Imm(Imm) != -1;
11091   return false;
11092 }
11093
11094 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11095 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11096 /// specified in the intrinsic calls.
11097 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11098                                            const CallInst &I,
11099                                            unsigned Intrinsic) const {
11100   switch (Intrinsic) {
11101   case Intrinsic::arm_neon_vld1:
11102   case Intrinsic::arm_neon_vld2:
11103   case Intrinsic::arm_neon_vld3:
11104   case Intrinsic::arm_neon_vld4:
11105   case Intrinsic::arm_neon_vld2lane:
11106   case Intrinsic::arm_neon_vld3lane:
11107   case Intrinsic::arm_neon_vld4lane: {
11108     Info.opc = ISD::INTRINSIC_W_CHAIN;
11109     // Conservatively set memVT to the entire set of vectors loaded.
11110     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
11111     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11112     Info.ptrVal = I.getArgOperand(0);
11113     Info.offset = 0;
11114     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11115     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11116     Info.vol = false; // volatile loads with NEON intrinsics not supported
11117     Info.readMem = true;
11118     Info.writeMem = false;
11119     return true;
11120   }
11121   case Intrinsic::arm_neon_vst1:
11122   case Intrinsic::arm_neon_vst2:
11123   case Intrinsic::arm_neon_vst3:
11124   case Intrinsic::arm_neon_vst4:
11125   case Intrinsic::arm_neon_vst2lane:
11126   case Intrinsic::arm_neon_vst3lane:
11127   case Intrinsic::arm_neon_vst4lane: {
11128     Info.opc = ISD::INTRINSIC_VOID;
11129     // Conservatively set memVT to the entire set of vectors stored.
11130     unsigned NumElts = 0;
11131     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11132       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11133       if (!ArgTy->isVectorTy())
11134         break;
11135       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
11136     }
11137     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11138     Info.ptrVal = I.getArgOperand(0);
11139     Info.offset = 0;
11140     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11141     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11142     Info.vol = false; // volatile stores with NEON intrinsics not supported
11143     Info.readMem = false;
11144     Info.writeMem = true;
11145     return true;
11146   }
11147   case Intrinsic::arm_ldrex: {
11148     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11149     Info.opc = ISD::INTRINSIC_W_CHAIN;
11150     Info.memVT = MVT::getVT(PtrTy->getElementType());
11151     Info.ptrVal = I.getArgOperand(0);
11152     Info.offset = 0;
11153     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11154     Info.vol = true;
11155     Info.readMem = true;
11156     Info.writeMem = false;
11157     return true;
11158   }
11159   case Intrinsic::arm_strex: {
11160     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11161     Info.opc = ISD::INTRINSIC_W_CHAIN;
11162     Info.memVT = MVT::getVT(PtrTy->getElementType());
11163     Info.ptrVal = I.getArgOperand(1);
11164     Info.offset = 0;
11165     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11166     Info.vol = true;
11167     Info.readMem = false;
11168     Info.writeMem = true;
11169     return true;
11170   }
11171   case Intrinsic::arm_strexd: {
11172     Info.opc = ISD::INTRINSIC_W_CHAIN;
11173     Info.memVT = MVT::i64;
11174     Info.ptrVal = I.getArgOperand(2);
11175     Info.offset = 0;
11176     Info.align = 8;
11177     Info.vol = true;
11178     Info.readMem = false;
11179     Info.writeMem = true;
11180     return true;
11181   }
11182   case Intrinsic::arm_ldrexd: {
11183     Info.opc = ISD::INTRINSIC_W_CHAIN;
11184     Info.memVT = MVT::i64;
11185     Info.ptrVal = I.getArgOperand(0);
11186     Info.offset = 0;
11187     Info.align = 8;
11188     Info.vol = true;
11189     Info.readMem = true;
11190     Info.writeMem = false;
11191     return true;
11192   }
11193   default:
11194     break;
11195   }
11196
11197   return false;
11198 }