ARM: remove special cases for Darwin dynamic-no-pic mode.
[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 (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1704       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1705       ARMConstantPoolValue *CPV =
1706         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1707       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1708       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1709       Callee = DAG.getLoad(getPointerTy(), dl,
1710                            DAG.getEntryNode(), CPAddr,
1711                            MachinePointerInfo::getConstantPool(),
1712                            false, false, false, 0);
1713       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1714       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1715                            getPointerTy(), Callee, PICLabel);
1716     } else {
1717       // On ELF targets for PIC code, direct calls should go through the PLT
1718       unsigned OpFlags = 0;
1719       if (Subtarget->isTargetELF() &&
1720           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1721         OpFlags = ARMII::MO_PLT;
1722       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1723     }
1724   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1725     isDirect = true;
1726     bool isStub = Subtarget->isTargetDarwin() &&
1727                   getTargetMachine().getRelocationModel() != Reloc::Static;
1728     isARMFunc = !Subtarget->isThumb() || isStub;
1729     // tBX takes a register source operand.
1730     const char *Sym = S->getSymbol();
1731     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1732       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1733       ARMConstantPoolValue *CPV =
1734         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1735                                       ARMPCLabelIndex, 4);
1736       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1737       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1738       Callee = DAG.getLoad(getPointerTy(), dl,
1739                            DAG.getEntryNode(), CPAddr,
1740                            MachinePointerInfo::getConstantPool(),
1741                            false, false, false, 0);
1742       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1743       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1744                            getPointerTy(), Callee, PICLabel);
1745     } else {
1746       unsigned OpFlags = 0;
1747       // On ELF targets for PIC code, direct calls should go through the PLT
1748       if (Subtarget->isTargetELF() &&
1749                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1750         OpFlags = ARMII::MO_PLT;
1751       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1752     }
1753   }
1754
1755   // FIXME: handle tail calls differently.
1756   unsigned CallOpc;
1757   bool HasMinSizeAttr = MF.getFunction()->getAttributes().
1758     hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
1759   if (Subtarget->isThumb()) {
1760     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1761       CallOpc = ARMISD::CALL_NOLINK;
1762     else
1763       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1764   } else {
1765     if (!isDirect && !Subtarget->hasV5TOps())
1766       CallOpc = ARMISD::CALL_NOLINK;
1767     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1768                // Emit regular call when code size is the priority
1769                !HasMinSizeAttr)
1770       // "mov lr, pc; b _foo" to avoid confusing the RSP
1771       CallOpc = ARMISD::CALL_NOLINK;
1772     else
1773       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1774   }
1775
1776   std::vector<SDValue> Ops;
1777   Ops.push_back(Chain);
1778   Ops.push_back(Callee);
1779
1780   // Add argument registers to the end of the list so that they are known live
1781   // into the call.
1782   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1783     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1784                                   RegsToPass[i].second.getValueType()));
1785
1786   // Add a register mask operand representing the call-preserved registers.
1787   if (!isTailCall) {
1788     const uint32_t *Mask;
1789     const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1790     const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1791     if (isThisReturn) {
1792       // For 'this' returns, use the R0-preserving mask if applicable
1793       Mask = ARI->getThisReturnPreservedMask(CallConv);
1794       if (!Mask) {
1795         // Set isThisReturn to false if the calling convention is not one that
1796         // allows 'returned' to be modeled in this way, so LowerCallResult does
1797         // not try to pass 'this' straight through
1798         isThisReturn = false;
1799         Mask = ARI->getCallPreservedMask(CallConv);
1800       }
1801     } else
1802       Mask = ARI->getCallPreservedMask(CallConv);
1803
1804     assert(Mask && "Missing call preserved mask for calling convention");
1805     Ops.push_back(DAG.getRegisterMask(Mask));
1806   }
1807
1808   if (InFlag.getNode())
1809     Ops.push_back(InFlag);
1810
1811   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1812   if (isTailCall)
1813     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1814
1815   // Returns a chain and a flag for retval copy to use.
1816   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1817   InFlag = Chain.getValue(1);
1818
1819   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1820                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1821   if (!Ins.empty())
1822     InFlag = Chain.getValue(1);
1823
1824   // Handle result values, copying them out of physregs into vregs that we
1825   // return.
1826   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1827                          InVals, isThisReturn,
1828                          isThisReturn ? OutVals[0] : SDValue());
1829 }
1830
1831 /// HandleByVal - Every parameter *after* a byval parameter is passed
1832 /// on the stack.  Remember the next parameter register to allocate,
1833 /// and then confiscate the rest of the parameter registers to insure
1834 /// this.
1835 void
1836 ARMTargetLowering::HandleByVal(
1837     CCState *State, unsigned &size, unsigned Align) const {
1838   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1839   assert((State->getCallOrPrologue() == Prologue ||
1840           State->getCallOrPrologue() == Call) &&
1841          "unhandled ParmContext");
1842
1843   // For in-prologue parameters handling, we also introduce stack offset
1844   // for byval registers: see CallingConvLower.cpp, CCState::HandleByVal.
1845   // This behaviour outsides AAPCS rules (5.5 Parameters Passing) of how
1846   // NSAA should be evaluted (NSAA means "next stacked argument address").
1847   // So: NextStackOffset = NSAAOffset + SizeOfByValParamsStoredInRegs.
1848   // Then: NSAAOffset = NextStackOffset - SizeOfByValParamsStoredInRegs.
1849   unsigned NSAAOffset = State->getNextStackOffset();
1850   if (State->getCallOrPrologue() != Call) {
1851     for (unsigned i = 0, e = State->getInRegsParamsCount(); i != e; ++i) {
1852       unsigned RB, RE;
1853       State->getInRegsParamInfo(i, RB, RE);
1854       assert(NSAAOffset >= (RE-RB)*4 &&
1855              "Stack offset for byval regs doesn't introduced anymore?");
1856       NSAAOffset -= (RE-RB)*4;
1857     }
1858   }
1859   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1860     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1861       unsigned AlignInRegs = Align / 4;
1862       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1863       for (unsigned i = 0; i < Waste; ++i)
1864         reg = State->AllocateReg(GPRArgRegs, 4);
1865     }
1866     if (reg != 0) {
1867       unsigned excess = 4 * (ARM::R4 - reg);
1868
1869       // Special case when NSAA != SP and parameter size greater than size of
1870       // all remained GPR regs. In that case we can't split parameter, we must
1871       // send it to stack. We also must set NCRN to R4, so waste all
1872       // remained registers.
1873       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1874         while (State->AllocateReg(GPRArgRegs, 4))
1875           ;
1876         return;
1877       }
1878
1879       // First register for byval parameter is the first register that wasn't
1880       // allocated before this method call, so it would be "reg".
1881       // If parameter is small enough to be saved in range [reg, r4), then
1882       // the end (first after last) register would be reg + param-size-in-regs,
1883       // else parameter would be splitted between registers and stack,
1884       // end register would be r4 in this case.
1885       unsigned ByValRegBegin = reg;
1886       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1887       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1888       // Note, first register is allocated in the beginning of function already,
1889       // allocate remained amount of registers we need.
1890       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1891         State->AllocateReg(GPRArgRegs, 4);
1892       // At a call site, a byval parameter that is split between
1893       // registers and memory needs its size truncated here.  In a
1894       // function prologue, such byval parameters are reassembled in
1895       // memory, and are not truncated.
1896       if (State->getCallOrPrologue() == Call) {
1897         // Make remained size equal to 0 in case, when
1898         // the whole structure may be stored into registers.
1899         if (size < excess)
1900           size = 0;
1901         else
1902           size -= excess;
1903       }
1904     }
1905   }
1906 }
1907
1908 /// MatchingStackOffset - Return true if the given stack call argument is
1909 /// already available in the same position (relatively) of the caller's
1910 /// incoming argument stack.
1911 static
1912 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1913                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1914                          const TargetInstrInfo *TII) {
1915   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1916   int FI = INT_MAX;
1917   if (Arg.getOpcode() == ISD::CopyFromReg) {
1918     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1919     if (!TargetRegisterInfo::isVirtualRegister(VR))
1920       return false;
1921     MachineInstr *Def = MRI->getVRegDef(VR);
1922     if (!Def)
1923       return false;
1924     if (!Flags.isByVal()) {
1925       if (!TII->isLoadFromStackSlot(Def, FI))
1926         return false;
1927     } else {
1928       return false;
1929     }
1930   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1931     if (Flags.isByVal())
1932       // ByVal argument is passed in as a pointer but it's now being
1933       // dereferenced. e.g.
1934       // define @foo(%struct.X* %A) {
1935       //   tail call @bar(%struct.X* byval %A)
1936       // }
1937       return false;
1938     SDValue Ptr = Ld->getBasePtr();
1939     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1940     if (!FINode)
1941       return false;
1942     FI = FINode->getIndex();
1943   } else
1944     return false;
1945
1946   assert(FI != INT_MAX);
1947   if (!MFI->isFixedObjectIndex(FI))
1948     return false;
1949   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1950 }
1951
1952 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1953 /// for tail call optimization. Targets which want to do tail call
1954 /// optimization should implement this function.
1955 bool
1956 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1957                                                      CallingConv::ID CalleeCC,
1958                                                      bool isVarArg,
1959                                                      bool isCalleeStructRet,
1960                                                      bool isCallerStructRet,
1961                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1962                                     const SmallVectorImpl<SDValue> &OutVals,
1963                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1964                                                      SelectionDAG& DAG) const {
1965   const Function *CallerF = DAG.getMachineFunction().getFunction();
1966   CallingConv::ID CallerCC = CallerF->getCallingConv();
1967   bool CCMatch = CallerCC == CalleeCC;
1968
1969   // Look for obvious safe cases to perform tail call optimization that do not
1970   // require ABI changes. This is what gcc calls sibcall.
1971
1972   // Do not sibcall optimize vararg calls unless the call site is not passing
1973   // any arguments.
1974   if (isVarArg && !Outs.empty())
1975     return false;
1976
1977   // Exception-handling functions need a special set of instructions to indicate
1978   // a return to the hardware. Tail-calling another function would probably
1979   // break this.
1980   if (CallerF->hasFnAttribute("interrupt"))
1981     return false;
1982
1983   // Also avoid sibcall optimization if either caller or callee uses struct
1984   // return semantics.
1985   if (isCalleeStructRet || isCallerStructRet)
1986     return false;
1987
1988   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1989   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1990   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1991   // support in the assembler and linker to be used. This would need to be
1992   // fixed to fully support tail calls in Thumb1.
1993   //
1994   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1995   // LR.  This means if we need to reload LR, it takes an extra instructions,
1996   // which outweighs the value of the tail call; but here we don't know yet
1997   // whether LR is going to be used.  Probably the right approach is to
1998   // generate the tail call here and turn it back into CALL/RET in
1999   // emitEpilogue if LR is used.
2000
2001   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2002   // but we need to make sure there are enough registers; the only valid
2003   // registers are the 4 used for parameters.  We don't currently do this
2004   // case.
2005   if (Subtarget->isThumb1Only())
2006     return false;
2007
2008   // If the calling conventions do not match, then we'd better make sure the
2009   // results are returned in the same way as what the caller expects.
2010   if (!CCMatch) {
2011     SmallVector<CCValAssign, 16> RVLocs1;
2012     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2013                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
2014     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2015
2016     SmallVector<CCValAssign, 16> RVLocs2;
2017     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2018                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
2019     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2020
2021     if (RVLocs1.size() != RVLocs2.size())
2022       return false;
2023     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2024       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2025         return false;
2026       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2027         return false;
2028       if (RVLocs1[i].isRegLoc()) {
2029         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2030           return false;
2031       } else {
2032         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2033           return false;
2034       }
2035     }
2036   }
2037
2038   // If Caller's vararg or byval argument has been split between registers and
2039   // stack, do not perform tail call, since part of the argument is in caller's
2040   // local frame.
2041   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2042                                       getInfo<ARMFunctionInfo>();
2043   if (AFI_Caller->getArgRegsSaveSize())
2044     return false;
2045
2046   // If the callee takes no arguments then go on to check the results of the
2047   // call.
2048   if (!Outs.empty()) {
2049     // Check if stack adjustment is needed. For now, do not do this if any
2050     // argument is passed on the stack.
2051     SmallVector<CCValAssign, 16> ArgLocs;
2052     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2053                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
2054     CCInfo.AnalyzeCallOperands(Outs,
2055                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2056     if (CCInfo.getNextStackOffset()) {
2057       MachineFunction &MF = DAG.getMachineFunction();
2058
2059       // Check if the arguments are already laid out in the right way as
2060       // the caller's fixed stack objects.
2061       MachineFrameInfo *MFI = MF.getFrameInfo();
2062       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2063       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2064       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2065            i != e;
2066            ++i, ++realArgIdx) {
2067         CCValAssign &VA = ArgLocs[i];
2068         EVT RegVT = VA.getLocVT();
2069         SDValue Arg = OutVals[realArgIdx];
2070         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2071         if (VA.getLocInfo() == CCValAssign::Indirect)
2072           return false;
2073         if (VA.needsCustom()) {
2074           // f64 and vector types are split into multiple registers or
2075           // register/stack-slot combinations.  The types will not match
2076           // the registers; give up on memory f64 refs until we figure
2077           // out what to do about this.
2078           if (!VA.isRegLoc())
2079             return false;
2080           if (!ArgLocs[++i].isRegLoc())
2081             return false;
2082           if (RegVT == MVT::v2f64) {
2083             if (!ArgLocs[++i].isRegLoc())
2084               return false;
2085             if (!ArgLocs[++i].isRegLoc())
2086               return false;
2087           }
2088         } else if (!VA.isRegLoc()) {
2089           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2090                                    MFI, MRI, TII))
2091             return false;
2092         }
2093       }
2094     }
2095   }
2096
2097   return true;
2098 }
2099
2100 bool
2101 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2102                                   MachineFunction &MF, bool isVarArg,
2103                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2104                                   LLVMContext &Context) const {
2105   SmallVector<CCValAssign, 16> RVLocs;
2106   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2107   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2108                                                     isVarArg));
2109 }
2110
2111 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2112                                     SDLoc DL, SelectionDAG &DAG) {
2113   const MachineFunction &MF = DAG.getMachineFunction();
2114   const Function *F = MF.getFunction();
2115
2116   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2117
2118   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2119   // version of the "preferred return address". These offsets affect the return
2120   // instruction if this is a return from PL1 without hypervisor extensions.
2121   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2122   //    SWI:     0      "subs pc, lr, #0"
2123   //    ABORT:   +4     "subs pc, lr, #4"
2124   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2125   // UNDEF varies depending on where the exception came from ARM or Thumb
2126   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2127
2128   int64_t LROffset;
2129   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2130       IntKind == "ABORT")
2131     LROffset = 4;
2132   else if (IntKind == "SWI" || IntKind == "UNDEF")
2133     LROffset = 0;
2134   else
2135     report_fatal_error("Unsupported interrupt attribute. If present, value "
2136                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2137
2138   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2139
2140   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other,
2141                      RetOps.data(), RetOps.size());
2142 }
2143
2144 SDValue
2145 ARMTargetLowering::LowerReturn(SDValue Chain,
2146                                CallingConv::ID CallConv, bool isVarArg,
2147                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2148                                const SmallVectorImpl<SDValue> &OutVals,
2149                                SDLoc dl, SelectionDAG &DAG) const {
2150
2151   // CCValAssign - represent the assignment of the return value to a location.
2152   SmallVector<CCValAssign, 16> RVLocs;
2153
2154   // CCState - Info about the registers and stack slots.
2155   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2156                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2157
2158   // Analyze outgoing return values.
2159   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2160                                                isVarArg));
2161
2162   SDValue Flag;
2163   SmallVector<SDValue, 4> RetOps;
2164   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2165
2166   // Copy the result values into the output registers.
2167   for (unsigned i = 0, realRVLocIdx = 0;
2168        i != RVLocs.size();
2169        ++i, ++realRVLocIdx) {
2170     CCValAssign &VA = RVLocs[i];
2171     assert(VA.isRegLoc() && "Can only return in registers!");
2172
2173     SDValue Arg = OutVals[realRVLocIdx];
2174
2175     switch (VA.getLocInfo()) {
2176     default: llvm_unreachable("Unknown loc info!");
2177     case CCValAssign::Full: break;
2178     case CCValAssign::BCvt:
2179       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2180       break;
2181     }
2182
2183     if (VA.needsCustom()) {
2184       if (VA.getLocVT() == MVT::v2f64) {
2185         // Extract the first half and return it in two registers.
2186         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2187                                    DAG.getConstant(0, MVT::i32));
2188         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2189                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2190
2191         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
2192         Flag = Chain.getValue(1);
2193         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2194         VA = RVLocs[++i]; // skip ahead to next loc
2195         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2196                                  HalfGPRs.getValue(1), Flag);
2197         Flag = Chain.getValue(1);
2198         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2199         VA = RVLocs[++i]; // skip ahead to next loc
2200
2201         // Extract the 2nd half and fall through to handle it as an f64 value.
2202         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2203                           DAG.getConstant(1, MVT::i32));
2204       }
2205       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2206       // available.
2207       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2208                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
2209       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
2210       Flag = Chain.getValue(1);
2211       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2212       VA = RVLocs[++i]; // skip ahead to next loc
2213       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
2214                                Flag);
2215     } else
2216       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2217
2218     // Guarantee that all emitted copies are
2219     // stuck together, avoiding something bad.
2220     Flag = Chain.getValue(1);
2221     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2222   }
2223
2224   // Update chain and glue.
2225   RetOps[0] = Chain;
2226   if (Flag.getNode())
2227     RetOps.push_back(Flag);
2228
2229   // CPUs which aren't M-class use a special sequence to return from
2230   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2231   // though we use "subs pc, lr, #N").
2232   //
2233   // M-class CPUs actually use a normal return sequence with a special
2234   // (hardware-provided) value in LR, so the normal code path works.
2235   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2236       !Subtarget->isMClass()) {
2237     if (Subtarget->isThumb1Only())
2238       report_fatal_error("interrupt attribute is not supported in Thumb1");
2239     return LowerInterruptReturn(RetOps, dl, DAG);
2240   }
2241
2242   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
2243                      RetOps.data(), RetOps.size());
2244 }
2245
2246 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2247   if (N->getNumValues() != 1)
2248     return false;
2249   if (!N->hasNUsesOfValue(1, 0))
2250     return false;
2251
2252   SDValue TCChain = Chain;
2253   SDNode *Copy = *N->use_begin();
2254   if (Copy->getOpcode() == ISD::CopyToReg) {
2255     // If the copy has a glue operand, we conservatively assume it isn't safe to
2256     // perform a tail call.
2257     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2258       return false;
2259     TCChain = Copy->getOperand(0);
2260   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2261     SDNode *VMov = Copy;
2262     // f64 returned in a pair of GPRs.
2263     SmallPtrSet<SDNode*, 2> Copies;
2264     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2265          UI != UE; ++UI) {
2266       if (UI->getOpcode() != ISD::CopyToReg)
2267         return false;
2268       Copies.insert(*UI);
2269     }
2270     if (Copies.size() > 2)
2271       return false;
2272
2273     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2274          UI != UE; ++UI) {
2275       SDValue UseChain = UI->getOperand(0);
2276       if (Copies.count(UseChain.getNode()))
2277         // Second CopyToReg
2278         Copy = *UI;
2279       else
2280         // First CopyToReg
2281         TCChain = UseChain;
2282     }
2283   } else if (Copy->getOpcode() == ISD::BITCAST) {
2284     // f32 returned in a single GPR.
2285     if (!Copy->hasOneUse())
2286       return false;
2287     Copy = *Copy->use_begin();
2288     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2289       return false;
2290     TCChain = Copy->getOperand(0);
2291   } else {
2292     return false;
2293   }
2294
2295   bool HasRet = false;
2296   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2297        UI != UE; ++UI) {
2298     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2299         UI->getOpcode() != ARMISD::INTRET_FLAG)
2300       return false;
2301     HasRet = true;
2302   }
2303
2304   if (!HasRet)
2305     return false;
2306
2307   Chain = TCChain;
2308   return true;
2309 }
2310
2311 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2312   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2313     return false;
2314
2315   if (!CI->isTailCall())
2316     return false;
2317
2318   return !Subtarget->isThumb1Only();
2319 }
2320
2321 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2322 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2323 // one of the above mentioned nodes. It has to be wrapped because otherwise
2324 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2325 // be used to form addressing mode. These wrapped nodes will be selected
2326 // into MOVi.
2327 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2328   EVT PtrVT = Op.getValueType();
2329   // FIXME there is no actual debug info here
2330   SDLoc dl(Op);
2331   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2332   SDValue Res;
2333   if (CP->isMachineConstantPoolEntry())
2334     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2335                                     CP->getAlignment());
2336   else
2337     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2338                                     CP->getAlignment());
2339   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2340 }
2341
2342 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2343   return MachineJumpTableInfo::EK_Inline;
2344 }
2345
2346 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2347                                              SelectionDAG &DAG) const {
2348   MachineFunction &MF = DAG.getMachineFunction();
2349   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2350   unsigned ARMPCLabelIndex = 0;
2351   SDLoc DL(Op);
2352   EVT PtrVT = getPointerTy();
2353   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2354   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2355   SDValue CPAddr;
2356   if (RelocM == Reloc::Static) {
2357     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2358   } else {
2359     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2360     ARMPCLabelIndex = AFI->createPICLabelUId();
2361     ARMConstantPoolValue *CPV =
2362       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2363                                       ARMCP::CPBlockAddress, PCAdj);
2364     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2365   }
2366   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2367   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2368                                MachinePointerInfo::getConstantPool(),
2369                                false, false, false, 0);
2370   if (RelocM == Reloc::Static)
2371     return Result;
2372   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2373   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2374 }
2375
2376 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2377 SDValue
2378 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2379                                                  SelectionDAG &DAG) const {
2380   SDLoc dl(GA);
2381   EVT PtrVT = getPointerTy();
2382   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2383   MachineFunction &MF = DAG.getMachineFunction();
2384   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2385   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2386   ARMConstantPoolValue *CPV =
2387     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2388                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2389   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2390   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2391   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2392                          MachinePointerInfo::getConstantPool(),
2393                          false, false, false, 0);
2394   SDValue Chain = Argument.getValue(1);
2395
2396   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2397   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2398
2399   // call __tls_get_addr.
2400   ArgListTy Args;
2401   ArgListEntry Entry;
2402   Entry.Node = Argument;
2403   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2404   Args.push_back(Entry);
2405   // FIXME: is there useful debug info available here?
2406   TargetLowering::CallLoweringInfo CLI(Chain,
2407                 (Type *) Type::getInt32Ty(*DAG.getContext()),
2408                 false, false, false, false,
2409                 0, CallingConv::C, /*isTailCall=*/false,
2410                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2411                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2412   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2413   return CallResult.first;
2414 }
2415
2416 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2417 // "local exec" model.
2418 SDValue
2419 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2420                                         SelectionDAG &DAG,
2421                                         TLSModel::Model model) const {
2422   const GlobalValue *GV = GA->getGlobal();
2423   SDLoc dl(GA);
2424   SDValue Offset;
2425   SDValue Chain = DAG.getEntryNode();
2426   EVT PtrVT = getPointerTy();
2427   // Get the Thread Pointer
2428   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2429
2430   if (model == TLSModel::InitialExec) {
2431     MachineFunction &MF = DAG.getMachineFunction();
2432     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2433     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2434     // Initial exec model.
2435     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2436     ARMConstantPoolValue *CPV =
2437       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2438                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2439                                       true);
2440     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2441     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2442     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2443                          MachinePointerInfo::getConstantPool(),
2444                          false, false, false, 0);
2445     Chain = Offset.getValue(1);
2446
2447     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2448     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2449
2450     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2451                          MachinePointerInfo::getConstantPool(),
2452                          false, false, false, 0);
2453   } else {
2454     // local exec model
2455     assert(model == TLSModel::LocalExec);
2456     ARMConstantPoolValue *CPV =
2457       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2458     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2459     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2460     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2461                          MachinePointerInfo::getConstantPool(),
2462                          false, false, false, 0);
2463   }
2464
2465   // The address of the thread local variable is the add of the thread
2466   // pointer with the offset of the variable.
2467   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2468 }
2469
2470 SDValue
2471 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2472   // TODO: implement the "local dynamic" model
2473   assert(Subtarget->isTargetELF() &&
2474          "TLS not implemented for non-ELF targets");
2475   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2476
2477   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2478
2479   switch (model) {
2480     case TLSModel::GeneralDynamic:
2481     case TLSModel::LocalDynamic:
2482       return LowerToTLSGeneralDynamicModel(GA, DAG);
2483     case TLSModel::InitialExec:
2484     case TLSModel::LocalExec:
2485       return LowerToTLSExecModels(GA, DAG, model);
2486   }
2487   llvm_unreachable("bogus TLS model");
2488 }
2489
2490 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2491                                                  SelectionDAG &DAG) const {
2492   EVT PtrVT = getPointerTy();
2493   SDLoc dl(Op);
2494   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2495   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2496     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2497     ARMConstantPoolValue *CPV =
2498       ARMConstantPoolConstant::Create(GV,
2499                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2500     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2501     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2502     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2503                                  CPAddr,
2504                                  MachinePointerInfo::getConstantPool(),
2505                                  false, false, false, 0);
2506     SDValue Chain = Result.getValue(1);
2507     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2508     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2509     if (!UseGOTOFF)
2510       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2511                            MachinePointerInfo::getGOT(),
2512                            false, false, false, 0);
2513     return Result;
2514   }
2515
2516   // If we have T2 ops, we can materialize the address directly via movt/movw
2517   // pair. This is always cheaper.
2518   if (Subtarget->useMovt()) {
2519     ++NumMovwMovt;
2520     // FIXME: Once remat is capable of dealing with instructions with register
2521     // operands, expand this into two nodes.
2522     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2523                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2524   } else {
2525     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2526     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2527     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2528                        MachinePointerInfo::getConstantPool(),
2529                        false, false, false, 0);
2530   }
2531 }
2532
2533 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2534                                                     SelectionDAG &DAG) const {
2535   EVT PtrVT = getPointerTy();
2536   SDLoc dl(Op);
2537   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2538   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2539
2540   // FIXME: Enable this for static codegen when tool issues are fixed.  Also
2541   // update ARMFastISel::ARMMaterializeGV.
2542   if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2543     ++NumMovwMovt;
2544     // FIXME: Once remat is capable of dealing with instructions with register
2545     // operands, expand this into two nodes.
2546     if (RelocM == Reloc::Static)
2547       return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2548                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2549
2550     unsigned Wrapper =
2551         RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2552
2553     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2554     SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2555
2556     if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2557       Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2558                            MachinePointerInfo::getGOT(),
2559                            false, false, false, 0);
2560     return Result;
2561   }
2562
2563   unsigned ARMPCLabelIndex = 0;
2564   SDValue CPAddr;
2565   if (RelocM == Reloc::Static) {
2566     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2567   } else {
2568     ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2569     ARMPCLabelIndex = AFI->createPICLabelUId();
2570     unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2571     ARMConstantPoolValue *CPV =
2572       ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2573                                       PCAdj);
2574     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2575   }
2576   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2577
2578   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2579                                MachinePointerInfo::getConstantPool(),
2580                                false, false, false, 0);
2581   SDValue Chain = Result.getValue(1);
2582
2583   if (RelocM == Reloc::PIC_) {
2584     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2585     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2586   }
2587
2588   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2589     Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2590                          false, false, false, 0);
2591
2592   return Result;
2593 }
2594
2595 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2596                                                     SelectionDAG &DAG) const {
2597   assert(Subtarget->isTargetELF() &&
2598          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2599   MachineFunction &MF = DAG.getMachineFunction();
2600   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2601   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2602   EVT PtrVT = getPointerTy();
2603   SDLoc dl(Op);
2604   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2605   ARMConstantPoolValue *CPV =
2606     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2607                                   ARMPCLabelIndex, PCAdj);
2608   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2609   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2610   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2611                                MachinePointerInfo::getConstantPool(),
2612                                false, false, false, 0);
2613   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2614   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2615 }
2616
2617 SDValue
2618 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2619   SDLoc dl(Op);
2620   SDValue Val = DAG.getConstant(0, MVT::i32);
2621   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2622                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2623                      Op.getOperand(1), Val);
2624 }
2625
2626 SDValue
2627 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2628   SDLoc dl(Op);
2629   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2630                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2631 }
2632
2633 SDValue
2634 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2635                                           const ARMSubtarget *Subtarget) const {
2636   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2637   SDLoc dl(Op);
2638   switch (IntNo) {
2639   default: return SDValue();    // Don't custom lower most intrinsics.
2640   case Intrinsic::arm_thread_pointer: {
2641     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2642     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2643   }
2644   case Intrinsic::eh_sjlj_lsda: {
2645     MachineFunction &MF = DAG.getMachineFunction();
2646     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2647     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2648     EVT PtrVT = getPointerTy();
2649     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2650     SDValue CPAddr;
2651     unsigned PCAdj = (RelocM != Reloc::PIC_)
2652       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2653     ARMConstantPoolValue *CPV =
2654       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2655                                       ARMCP::CPLSDA, PCAdj);
2656     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2657     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2658     SDValue Result =
2659       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2660                   MachinePointerInfo::getConstantPool(),
2661                   false, false, false, 0);
2662
2663     if (RelocM == Reloc::PIC_) {
2664       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2665       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2666     }
2667     return Result;
2668   }
2669   case Intrinsic::arm_neon_vmulls:
2670   case Intrinsic::arm_neon_vmullu: {
2671     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2672       ? ARMISD::VMULLs : ARMISD::VMULLu;
2673     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2674                        Op.getOperand(1), Op.getOperand(2));
2675   }
2676   }
2677 }
2678
2679 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2680                                  const ARMSubtarget *Subtarget) {
2681   // FIXME: handle "fence singlethread" more efficiently.
2682   SDLoc dl(Op);
2683   if (!Subtarget->hasDataBarrier()) {
2684     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2685     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2686     // here.
2687     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2688            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2689     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2690                        DAG.getConstant(0, MVT::i32));
2691   }
2692
2693   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2694   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2695   unsigned Domain = ARM_MB::ISH;
2696   if (Subtarget->isMClass()) {
2697     // Only a full system barrier exists in the M-class architectures.
2698     Domain = ARM_MB::SY;
2699   } else if (Subtarget->isSwift() && Ord == Release) {
2700     // Swift happens to implement ISHST barriers in a way that's compatible with
2701     // Release semantics but weaker than ISH so we'd be fools not to use
2702     // it. Beware: other processors probably don't!
2703     Domain = ARM_MB::ISHST;
2704   }
2705
2706   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2707                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2708                      DAG.getConstant(Domain, MVT::i32));
2709 }
2710
2711 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2712                              const ARMSubtarget *Subtarget) {
2713   // ARM pre v5TE and Thumb1 does not have preload instructions.
2714   if (!(Subtarget->isThumb2() ||
2715         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2716     // Just preserve the chain.
2717     return Op.getOperand(0);
2718
2719   SDLoc dl(Op);
2720   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2721   if (!isRead &&
2722       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2723     // ARMv7 with MP extension has PLDW.
2724     return Op.getOperand(0);
2725
2726   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2727   if (Subtarget->isThumb()) {
2728     // Invert the bits.
2729     isRead = ~isRead & 1;
2730     isData = ~isData & 1;
2731   }
2732
2733   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2734                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2735                      DAG.getConstant(isData, MVT::i32));
2736 }
2737
2738 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2739   MachineFunction &MF = DAG.getMachineFunction();
2740   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2741
2742   // vastart just stores the address of the VarArgsFrameIndex slot into the
2743   // memory location argument.
2744   SDLoc dl(Op);
2745   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2746   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2747   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2748   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2749                       MachinePointerInfo(SV), false, false, 0);
2750 }
2751
2752 SDValue
2753 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2754                                         SDValue &Root, SelectionDAG &DAG,
2755                                         SDLoc dl) const {
2756   MachineFunction &MF = DAG.getMachineFunction();
2757   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2758
2759   const TargetRegisterClass *RC;
2760   if (AFI->isThumb1OnlyFunction())
2761     RC = &ARM::tGPRRegClass;
2762   else
2763     RC = &ARM::GPRRegClass;
2764
2765   // Transform the arguments stored in physical registers into virtual ones.
2766   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2767   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2768
2769   SDValue ArgValue2;
2770   if (NextVA.isMemLoc()) {
2771     MachineFrameInfo *MFI = MF.getFrameInfo();
2772     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2773
2774     // Create load node to retrieve arguments from the stack.
2775     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2776     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2777                             MachinePointerInfo::getFixedStack(FI),
2778                             false, false, false, 0);
2779   } else {
2780     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2781     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2782   }
2783
2784   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2785 }
2786
2787 void
2788 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2789                                   unsigned InRegsParamRecordIdx,
2790                                   unsigned ArgSize,
2791                                   unsigned &ArgRegsSize,
2792                                   unsigned &ArgRegsSaveSize)
2793   const {
2794   unsigned NumGPRs;
2795   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2796     unsigned RBegin, REnd;
2797     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2798     NumGPRs = REnd - RBegin;
2799   } else {
2800     unsigned int firstUnalloced;
2801     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2802                                                 sizeof(GPRArgRegs) /
2803                                                 sizeof(GPRArgRegs[0]));
2804     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2805   }
2806
2807   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2808   ArgRegsSize = NumGPRs * 4;
2809
2810   // If parameter is split between stack and GPRs...
2811   if (NumGPRs && Align == 8 &&
2812       (ArgRegsSize < ArgSize ||
2813         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2814     // Add padding for part of param recovered from GPRs, so
2815     // its last byte must be at address K*8 - 1.
2816     // We need to do it, since remained (stack) part of parameter has
2817     // stack alignment, and we need to "attach" "GPRs head" without gaps
2818     // to it:
2819     // Stack:
2820     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2821     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2822     //
2823     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2824     unsigned Padding =
2825         ((ArgRegsSize + AFI->getArgRegsSaveSize() + Align - 1) & ~(Align-1)) -
2826         (ArgRegsSize + AFI->getArgRegsSaveSize());
2827     ArgRegsSaveSize = ArgRegsSize + Padding;
2828   } else
2829     // We don't need to extend regs save size for byval parameters if they
2830     // are passed via GPRs only.
2831     ArgRegsSaveSize = ArgRegsSize;
2832 }
2833
2834 // The remaining GPRs hold either the beginning of variable-argument
2835 // data, or the beginning of an aggregate passed by value (usually
2836 // byval).  Either way, we allocate stack slots adjacent to the data
2837 // provided by our caller, and store the unallocated registers there.
2838 // If this is a variadic function, the va_list pointer will begin with
2839 // these values; otherwise, this reassembles a (byval) structure that
2840 // was split between registers and memory.
2841 // Return: The frame index registers were stored into.
2842 int
2843 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2844                                   SDLoc dl, SDValue &Chain,
2845                                   const Value *OrigArg,
2846                                   unsigned InRegsParamRecordIdx,
2847                                   unsigned OffsetFromOrigArg,
2848                                   unsigned ArgOffset,
2849                                   unsigned ArgSize,
2850                                   bool ForceMutable) const {
2851
2852   // Currently, two use-cases possible:
2853   // Case #1. Non var-args function, and we meet first byval parameter.
2854   //          Setup first unallocated register as first byval register;
2855   //          eat all remained registers
2856   //          (these two actions are performed by HandleByVal method).
2857   //          Then, here, we initialize stack frame with
2858   //          "store-reg" instructions.
2859   // Case #2. Var-args function, that doesn't contain byval parameters.
2860   //          The same: eat all remained unallocated registers,
2861   //          initialize stack frame.
2862
2863   MachineFunction &MF = DAG.getMachineFunction();
2864   MachineFrameInfo *MFI = MF.getFrameInfo();
2865   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2866   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2867   unsigned RBegin, REnd;
2868   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2869     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2870     firstRegToSaveIndex = RBegin - ARM::R0;
2871     lastRegToSaveIndex = REnd - ARM::R0;
2872   } else {
2873     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2874       (GPRArgRegs, array_lengthof(GPRArgRegs));
2875     lastRegToSaveIndex = 4;
2876   }
2877
2878   unsigned ArgRegsSize, ArgRegsSaveSize;
2879   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2880                  ArgRegsSize, ArgRegsSaveSize);
2881
2882   // Store any by-val regs to their spots on the stack so that they may be
2883   // loaded by deferencing the result of formal parameter pointer or va_next.
2884   // Note: once stack area for byval/varargs registers
2885   // was initialized, it can't be initialized again.
2886   if (ArgRegsSaveSize) {
2887
2888     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2889
2890     if (Padding) {
2891       assert(AFI->getStoredByValParamsPadding() == 0 &&
2892              "The only parameter may be padded.");
2893       AFI->setStoredByValParamsPadding(Padding);
2894     }
2895
2896     int FrameIndex = MFI->CreateFixedObject(
2897                       ArgRegsSaveSize,
2898                       Padding + ArgOffset,
2899                       false);
2900     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2901
2902     SmallVector<SDValue, 4> MemOps;
2903     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2904          ++firstRegToSaveIndex, ++i) {
2905       const TargetRegisterClass *RC;
2906       if (AFI->isThumb1OnlyFunction())
2907         RC = &ARM::tGPRRegClass;
2908       else
2909         RC = &ARM::GPRRegClass;
2910
2911       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2912       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2913       SDValue Store =
2914         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2915                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2916                      false, false, 0);
2917       MemOps.push_back(Store);
2918       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2919                         DAG.getConstant(4, getPointerTy()));
2920     }
2921
2922     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2923
2924     if (!MemOps.empty())
2925       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2926                           &MemOps[0], MemOps.size());
2927     return FrameIndex;
2928   } else
2929     // This will point to the next argument passed via stack.
2930     return MFI->CreateFixedObject(
2931         4, AFI->getStoredByValParamsPadding() + ArgOffset, !ForceMutable);
2932 }
2933
2934 // Setup stack frame, the va_list pointer will start from.
2935 void
2936 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2937                                         SDLoc dl, SDValue &Chain,
2938                                         unsigned ArgOffset,
2939                                         bool ForceMutable) const {
2940   MachineFunction &MF = DAG.getMachineFunction();
2941   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2942
2943   // Try to store any remaining integer argument regs
2944   // to their spots on the stack so that they may be loaded by deferencing
2945   // the result of va_next.
2946   // If there is no regs to be stored, just point address after last
2947   // argument passed via stack.
2948   int FrameIndex =
2949     StoreByValRegs(CCInfo, DAG, dl, Chain, 0, CCInfo.getInRegsParamsCount(),
2950                    0, ArgOffset, 0, ForceMutable);
2951
2952   AFI->setVarArgsFrameIndex(FrameIndex);
2953 }
2954
2955 SDValue
2956 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2957                                         CallingConv::ID CallConv, bool isVarArg,
2958                                         const SmallVectorImpl<ISD::InputArg>
2959                                           &Ins,
2960                                         SDLoc dl, SelectionDAG &DAG,
2961                                         SmallVectorImpl<SDValue> &InVals)
2962                                           const {
2963   MachineFunction &MF = DAG.getMachineFunction();
2964   MachineFrameInfo *MFI = MF.getFrameInfo();
2965
2966   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2967
2968   // Assign locations to all of the incoming arguments.
2969   SmallVector<CCValAssign, 16> ArgLocs;
2970   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2971                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2972   CCInfo.AnalyzeFormalArguments(Ins,
2973                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2974                                                   isVarArg));
2975
2976   SmallVector<SDValue, 16> ArgValues;
2977   int lastInsIndex = -1;
2978   SDValue ArgValue;
2979   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2980   unsigned CurArgIdx = 0;
2981
2982   // Initially ArgRegsSaveSize is zero.
2983   // Then we increase this value each time we meet byval parameter.
2984   // We also increase this value in case of varargs function.
2985   AFI->setArgRegsSaveSize(0);
2986
2987   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2988     CCValAssign &VA = ArgLocs[i];
2989     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2990     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2991     // Arguments stored in registers.
2992     if (VA.isRegLoc()) {
2993       EVT RegVT = VA.getLocVT();
2994
2995       if (VA.needsCustom()) {
2996         // f64 and vector types are split up into multiple registers or
2997         // combinations of registers and stack slots.
2998         if (VA.getLocVT() == MVT::v2f64) {
2999           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3000                                                    Chain, DAG, dl);
3001           VA = ArgLocs[++i]; // skip ahead to next loc
3002           SDValue ArgValue2;
3003           if (VA.isMemLoc()) {
3004             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3005             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3006             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3007                                     MachinePointerInfo::getFixedStack(FI),
3008                                     false, false, false, 0);
3009           } else {
3010             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3011                                              Chain, DAG, dl);
3012           }
3013           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3014           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3015                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3016           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3017                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3018         } else
3019           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3020
3021       } else {
3022         const TargetRegisterClass *RC;
3023
3024         if (RegVT == MVT::f32)
3025           RC = &ARM::SPRRegClass;
3026         else if (RegVT == MVT::f64)
3027           RC = &ARM::DPRRegClass;
3028         else if (RegVT == MVT::v2f64)
3029           RC = &ARM::QPRRegClass;
3030         else if (RegVT == MVT::i32)
3031           RC = AFI->isThumb1OnlyFunction() ?
3032             (const TargetRegisterClass*)&ARM::tGPRRegClass :
3033             (const TargetRegisterClass*)&ARM::GPRRegClass;
3034         else
3035           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3036
3037         // Transform the arguments in physical registers into virtual ones.
3038         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3039         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3040       }
3041
3042       // If this is an 8 or 16-bit value, it is really passed promoted
3043       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3044       // truncate to the right size.
3045       switch (VA.getLocInfo()) {
3046       default: llvm_unreachable("Unknown loc info!");
3047       case CCValAssign::Full: break;
3048       case CCValAssign::BCvt:
3049         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3050         break;
3051       case CCValAssign::SExt:
3052         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3053                                DAG.getValueType(VA.getValVT()));
3054         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3055         break;
3056       case CCValAssign::ZExt:
3057         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3058                                DAG.getValueType(VA.getValVT()));
3059         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3060         break;
3061       }
3062
3063       InVals.push_back(ArgValue);
3064
3065     } else { // VA.isRegLoc()
3066
3067       // sanity check
3068       assert(VA.isMemLoc());
3069       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3070
3071       int index = ArgLocs[i].getValNo();
3072
3073       // Some Ins[] entries become multiple ArgLoc[] entries.
3074       // Process them only once.
3075       if (index != lastInsIndex)
3076         {
3077           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3078           // FIXME: For now, all byval parameter objects are marked mutable.
3079           // This can be changed with more analysis.
3080           // In case of tail call optimization mark all arguments mutable.
3081           // Since they could be overwritten by lowering of arguments in case of
3082           // a tail call.
3083           if (Flags.isByVal()) {
3084             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3085             int FrameIndex = StoreByValRegs(
3086                 CCInfo, DAG, dl, Chain, CurOrigArg,
3087                 CurByValIndex,
3088                 Ins[VA.getValNo()].PartOffset,
3089                 VA.getLocMemOffset(),
3090                 Flags.getByValSize(),
3091                 true /*force mutable frames*/);
3092             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3093             CCInfo.nextInRegsParam();
3094           } else {
3095             unsigned FIOffset = VA.getLocMemOffset() +
3096                                 AFI->getStoredByValParamsPadding();
3097             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3098                                             FIOffset, true);
3099
3100             // Create load nodes to retrieve arguments from the stack.
3101             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3102             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3103                                          MachinePointerInfo::getFixedStack(FI),
3104                                          false, false, false, 0));
3105           }
3106           lastInsIndex = index;
3107         }
3108     }
3109   }
3110
3111   // varargs
3112   if (isVarArg)
3113     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3114                          CCInfo.getNextStackOffset());
3115
3116   return Chain;
3117 }
3118
3119 /// isFloatingPointZero - Return true if this is +0.0.
3120 static bool isFloatingPointZero(SDValue Op) {
3121   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3122     return CFP->getValueAPF().isPosZero();
3123   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3124     // Maybe this has already been legalized into the constant pool?
3125     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3126       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3127       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3128         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3129           return CFP->getValueAPF().isPosZero();
3130     }
3131   }
3132   return false;
3133 }
3134
3135 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3136 /// the given operands.
3137 SDValue
3138 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3139                              SDValue &ARMcc, SelectionDAG &DAG,
3140                              SDLoc dl) const {
3141   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3142     unsigned C = RHSC->getZExtValue();
3143     if (!isLegalICmpImmediate(C)) {
3144       // Constant does not fit, try adjusting it by one?
3145       switch (CC) {
3146       default: break;
3147       case ISD::SETLT:
3148       case ISD::SETGE:
3149         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3150           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3151           RHS = DAG.getConstant(C-1, MVT::i32);
3152         }
3153         break;
3154       case ISD::SETULT:
3155       case ISD::SETUGE:
3156         if (C != 0 && isLegalICmpImmediate(C-1)) {
3157           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3158           RHS = DAG.getConstant(C-1, MVT::i32);
3159         }
3160         break;
3161       case ISD::SETLE:
3162       case ISD::SETGT:
3163         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3164           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3165           RHS = DAG.getConstant(C+1, MVT::i32);
3166         }
3167         break;
3168       case ISD::SETULE:
3169       case ISD::SETUGT:
3170         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3171           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3172           RHS = DAG.getConstant(C+1, MVT::i32);
3173         }
3174         break;
3175       }
3176     }
3177   }
3178
3179   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3180   ARMISD::NodeType CompareType;
3181   switch (CondCode) {
3182   default:
3183     CompareType = ARMISD::CMP;
3184     break;
3185   case ARMCC::EQ:
3186   case ARMCC::NE:
3187     // Uses only Z Flag
3188     CompareType = ARMISD::CMPZ;
3189     break;
3190   }
3191   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3192   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3193 }
3194
3195 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3196 SDValue
3197 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3198                              SDLoc dl) const {
3199   SDValue Cmp;
3200   if (!isFloatingPointZero(RHS))
3201     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3202   else
3203     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3204   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3205 }
3206
3207 /// duplicateCmp - Glue values can have only one use, so this function
3208 /// duplicates a comparison node.
3209 SDValue
3210 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3211   unsigned Opc = Cmp.getOpcode();
3212   SDLoc DL(Cmp);
3213   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3214     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3215
3216   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3217   Cmp = Cmp.getOperand(0);
3218   Opc = Cmp.getOpcode();
3219   if (Opc == ARMISD::CMPFP)
3220     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3221   else {
3222     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3223     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3224   }
3225   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3226 }
3227
3228 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3229   SDValue Cond = Op.getOperand(0);
3230   SDValue SelectTrue = Op.getOperand(1);
3231   SDValue SelectFalse = Op.getOperand(2);
3232   SDLoc dl(Op);
3233
3234   // Convert:
3235   //
3236   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3237   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3238   //
3239   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3240     const ConstantSDNode *CMOVTrue =
3241       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3242     const ConstantSDNode *CMOVFalse =
3243       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3244
3245     if (CMOVTrue && CMOVFalse) {
3246       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3247       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3248
3249       SDValue True;
3250       SDValue False;
3251       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3252         True = SelectTrue;
3253         False = SelectFalse;
3254       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3255         True = SelectFalse;
3256         False = SelectTrue;
3257       }
3258
3259       if (True.getNode() && False.getNode()) {
3260         EVT VT = Op.getValueType();
3261         SDValue ARMcc = Cond.getOperand(2);
3262         SDValue CCR = Cond.getOperand(3);
3263         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3264         assert(True.getValueType() == VT);
3265         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3266       }
3267     }
3268   }
3269
3270   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3271   // undefined bits before doing a full-word comparison with zero.
3272   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3273                      DAG.getConstant(1, Cond.getValueType()));
3274
3275   return DAG.getSelectCC(dl, Cond,
3276                          DAG.getConstant(0, Cond.getValueType()),
3277                          SelectTrue, SelectFalse, ISD::SETNE);
3278 }
3279
3280 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3281   if (CC == ISD::SETNE)
3282     return ISD::SETEQ;
3283   return ISD::getSetCCSwappedOperands(CC);
3284 }
3285
3286 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3287                                  bool &swpCmpOps, bool &swpVselOps) {
3288   // Start by selecting the GE condition code for opcodes that return true for
3289   // 'equality'
3290   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3291       CC == ISD::SETULE)
3292     CondCode = ARMCC::GE;
3293
3294   // and GT for opcodes that return false for 'equality'.
3295   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3296            CC == ISD::SETULT)
3297     CondCode = ARMCC::GT;
3298
3299   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3300   // to swap the compare operands.
3301   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3302       CC == ISD::SETULT)
3303     swpCmpOps = true;
3304
3305   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3306   // If we have an unordered opcode, we need to swap the operands to the VSEL
3307   // instruction (effectively negating the condition).
3308   //
3309   // This also has the effect of swapping which one of 'less' or 'greater'
3310   // returns true, so we also swap the compare operands. It also switches
3311   // whether we return true for 'equality', so we compensate by picking the
3312   // opposite condition code to our original choice.
3313   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3314       CC == ISD::SETUGT) {
3315     swpCmpOps = !swpCmpOps;
3316     swpVselOps = !swpVselOps;
3317     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3318   }
3319
3320   // 'ordered' is 'anything but unordered', so use the VS condition code and
3321   // swap the VSEL operands.
3322   if (CC == ISD::SETO) {
3323     CondCode = ARMCC::VS;
3324     swpVselOps = true;
3325   }
3326
3327   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3328   // code and swap the VSEL operands.
3329   if (CC == ISD::SETUNE) {
3330     CondCode = ARMCC::EQ;
3331     swpVselOps = true;
3332   }
3333 }
3334
3335 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3336   EVT VT = Op.getValueType();
3337   SDValue LHS = Op.getOperand(0);
3338   SDValue RHS = Op.getOperand(1);
3339   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3340   SDValue TrueVal = Op.getOperand(2);
3341   SDValue FalseVal = Op.getOperand(3);
3342   SDLoc dl(Op);
3343
3344   if (LHS.getValueType() == MVT::i32) {
3345     // Try to generate VSEL on ARMv8.
3346     // The VSEL instruction can't use all the usual ARM condition
3347     // codes: it only has two bits to select the condition code, so it's
3348     // constrained to use only GE, GT, VS and EQ.
3349     //
3350     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3351     // swap the operands of the previous compare instruction (effectively
3352     // inverting the compare condition, swapping 'less' and 'greater') and
3353     // sometimes need to swap the operands to the VSEL (which inverts the
3354     // condition in the sense of firing whenever the previous condition didn't)
3355     if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3356                                       TrueVal.getValueType() == MVT::f64)) {
3357       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3358       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3359           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3360         CC = getInverseCCForVSEL(CC);
3361         std::swap(TrueVal, FalseVal);
3362       }
3363     }
3364
3365     SDValue ARMcc;
3366     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3367     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3368     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3369                        Cmp);
3370   }
3371
3372   ARMCC::CondCodes CondCode, CondCode2;
3373   FPCCToARMCC(CC, CondCode, CondCode2);
3374
3375   // Try to generate VSEL on ARMv8.
3376   if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3377                                     TrueVal.getValueType() == MVT::f64)) {
3378     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3379     // same operands, as follows:
3380     //   c = fcmp [ogt, olt, ugt, ult] a, b
3381     //   select c, a, b
3382     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3383     // handled differently than the original code sequence.
3384     if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3385         RHS == FalseVal) {
3386       if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3387         return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3388       if (CC == ISD::SETOLT || CC == ISD::SETULT)
3389         return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3390     }
3391
3392     bool swpCmpOps = false;
3393     bool swpVselOps = false;
3394     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3395
3396     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3397         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3398       if (swpCmpOps)
3399         std::swap(LHS, RHS);
3400       if (swpVselOps)
3401         std::swap(TrueVal, FalseVal);
3402     }
3403   }
3404
3405   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3406   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3407   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3408   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3409                                ARMcc, CCR, Cmp);
3410   if (CondCode2 != ARMCC::AL) {
3411     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3412     // FIXME: Needs another CMP because flag can have but one use.
3413     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3414     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3415                          Result, TrueVal, ARMcc2, CCR, Cmp2);
3416   }
3417   return Result;
3418 }
3419
3420 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3421 /// to morph to an integer compare sequence.
3422 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3423                            const ARMSubtarget *Subtarget) {
3424   SDNode *N = Op.getNode();
3425   if (!N->hasOneUse())
3426     // Otherwise it requires moving the value from fp to integer registers.
3427     return false;
3428   if (!N->getNumValues())
3429     return false;
3430   EVT VT = Op.getValueType();
3431   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3432     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3433     // vmrs are very slow, e.g. cortex-a8.
3434     return false;
3435
3436   if (isFloatingPointZero(Op)) {
3437     SeenZero = true;
3438     return true;
3439   }
3440   return ISD::isNormalLoad(N);
3441 }
3442
3443 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3444   if (isFloatingPointZero(Op))
3445     return DAG.getConstant(0, MVT::i32);
3446
3447   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3448     return DAG.getLoad(MVT::i32, SDLoc(Op),
3449                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3450                        Ld->isVolatile(), Ld->isNonTemporal(),
3451                        Ld->isInvariant(), Ld->getAlignment());
3452
3453   llvm_unreachable("Unknown VFP cmp argument!");
3454 }
3455
3456 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3457                            SDValue &RetVal1, SDValue &RetVal2) {
3458   if (isFloatingPointZero(Op)) {
3459     RetVal1 = DAG.getConstant(0, MVT::i32);
3460     RetVal2 = DAG.getConstant(0, MVT::i32);
3461     return;
3462   }
3463
3464   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3465     SDValue Ptr = Ld->getBasePtr();
3466     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3467                           Ld->getChain(), Ptr,
3468                           Ld->getPointerInfo(),
3469                           Ld->isVolatile(), Ld->isNonTemporal(),
3470                           Ld->isInvariant(), Ld->getAlignment());
3471
3472     EVT PtrType = Ptr.getValueType();
3473     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3474     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3475                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3476     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3477                           Ld->getChain(), NewPtr,
3478                           Ld->getPointerInfo().getWithOffset(4),
3479                           Ld->isVolatile(), Ld->isNonTemporal(),
3480                           Ld->isInvariant(), NewAlign);
3481     return;
3482   }
3483
3484   llvm_unreachable("Unknown VFP cmp argument!");
3485 }
3486
3487 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3488 /// f32 and even f64 comparisons to integer ones.
3489 SDValue
3490 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3491   SDValue Chain = Op.getOperand(0);
3492   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3493   SDValue LHS = Op.getOperand(2);
3494   SDValue RHS = Op.getOperand(3);
3495   SDValue Dest = Op.getOperand(4);
3496   SDLoc dl(Op);
3497
3498   bool LHSSeenZero = false;
3499   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3500   bool RHSSeenZero = false;
3501   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3502   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3503     // If unsafe fp math optimization is enabled and there are no other uses of
3504     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3505     // to an integer comparison.
3506     if (CC == ISD::SETOEQ)
3507       CC = ISD::SETEQ;
3508     else if (CC == ISD::SETUNE)
3509       CC = ISD::SETNE;
3510
3511     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3512     SDValue ARMcc;
3513     if (LHS.getValueType() == MVT::f32) {
3514       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3515                         bitcastf32Toi32(LHS, DAG), Mask);
3516       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3517                         bitcastf32Toi32(RHS, DAG), Mask);
3518       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3519       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3520       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3521                          Chain, Dest, ARMcc, CCR, Cmp);
3522     }
3523
3524     SDValue LHS1, LHS2;
3525     SDValue RHS1, RHS2;
3526     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3527     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3528     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3529     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3530     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3531     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3532     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3533     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3534     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3535   }
3536
3537   return SDValue();
3538 }
3539
3540 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3541   SDValue Chain = Op.getOperand(0);
3542   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3543   SDValue LHS = Op.getOperand(2);
3544   SDValue RHS = Op.getOperand(3);
3545   SDValue Dest = Op.getOperand(4);
3546   SDLoc dl(Op);
3547
3548   if (LHS.getValueType() == MVT::i32) {
3549     SDValue ARMcc;
3550     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3551     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3552     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3553                        Chain, Dest, ARMcc, CCR, Cmp);
3554   }
3555
3556   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3557
3558   if (getTargetMachine().Options.UnsafeFPMath &&
3559       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3560        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3561     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3562     if (Result.getNode())
3563       return Result;
3564   }
3565
3566   ARMCC::CondCodes CondCode, CondCode2;
3567   FPCCToARMCC(CC, CondCode, CondCode2);
3568
3569   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3570   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3571   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3572   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3573   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3574   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3575   if (CondCode2 != ARMCC::AL) {
3576     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3577     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3578     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3579   }
3580   return Res;
3581 }
3582
3583 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3584   SDValue Chain = Op.getOperand(0);
3585   SDValue Table = Op.getOperand(1);
3586   SDValue Index = Op.getOperand(2);
3587   SDLoc dl(Op);
3588
3589   EVT PTy = getPointerTy();
3590   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3591   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3592   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3593   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3594   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3595   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3596   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3597   if (Subtarget->isThumb2()) {
3598     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3599     // which does another jump to the destination. This also makes it easier
3600     // to translate it to TBB / TBH later.
3601     // FIXME: This might not work if the function is extremely large.
3602     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3603                        Addr, Op.getOperand(2), JTI, UId);
3604   }
3605   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3606     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3607                        MachinePointerInfo::getJumpTable(),
3608                        false, false, false, 0);
3609     Chain = Addr.getValue(1);
3610     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3611     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3612   } else {
3613     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3614                        MachinePointerInfo::getJumpTable(),
3615                        false, false, false, 0);
3616     Chain = Addr.getValue(1);
3617     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3618   }
3619 }
3620
3621 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3622   EVT VT = Op.getValueType();
3623   SDLoc dl(Op);
3624
3625   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3626     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3627       return Op;
3628     return DAG.UnrollVectorOp(Op.getNode());
3629   }
3630
3631   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3632          "Invalid type for custom lowering!");
3633   if (VT != MVT::v4i16)
3634     return DAG.UnrollVectorOp(Op.getNode());
3635
3636   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3637   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3638 }
3639
3640 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3641   EVT VT = Op.getValueType();
3642   if (VT.isVector())
3643     return LowerVectorFP_TO_INT(Op, DAG);
3644
3645   SDLoc dl(Op);
3646   unsigned Opc;
3647
3648   switch (Op.getOpcode()) {
3649   default: llvm_unreachable("Invalid opcode!");
3650   case ISD::FP_TO_SINT:
3651     Opc = ARMISD::FTOSI;
3652     break;
3653   case ISD::FP_TO_UINT:
3654     Opc = ARMISD::FTOUI;
3655     break;
3656   }
3657   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3658   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3659 }
3660
3661 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3662   EVT VT = Op.getValueType();
3663   SDLoc dl(Op);
3664
3665   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3666     if (VT.getVectorElementType() == MVT::f32)
3667       return Op;
3668     return DAG.UnrollVectorOp(Op.getNode());
3669   }
3670
3671   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3672          "Invalid type for custom lowering!");
3673   if (VT != MVT::v4f32)
3674     return DAG.UnrollVectorOp(Op.getNode());
3675
3676   unsigned CastOpc;
3677   unsigned Opc;
3678   switch (Op.getOpcode()) {
3679   default: llvm_unreachable("Invalid opcode!");
3680   case ISD::SINT_TO_FP:
3681     CastOpc = ISD::SIGN_EXTEND;
3682     Opc = ISD::SINT_TO_FP;
3683     break;
3684   case ISD::UINT_TO_FP:
3685     CastOpc = ISD::ZERO_EXTEND;
3686     Opc = ISD::UINT_TO_FP;
3687     break;
3688   }
3689
3690   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3691   return DAG.getNode(Opc, dl, VT, Op);
3692 }
3693
3694 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3695   EVT VT = Op.getValueType();
3696   if (VT.isVector())
3697     return LowerVectorINT_TO_FP(Op, DAG);
3698
3699   SDLoc dl(Op);
3700   unsigned Opc;
3701
3702   switch (Op.getOpcode()) {
3703   default: llvm_unreachable("Invalid opcode!");
3704   case ISD::SINT_TO_FP:
3705     Opc = ARMISD::SITOF;
3706     break;
3707   case ISD::UINT_TO_FP:
3708     Opc = ARMISD::UITOF;
3709     break;
3710   }
3711
3712   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3713   return DAG.getNode(Opc, dl, VT, Op);
3714 }
3715
3716 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3717   // Implement fcopysign with a fabs and a conditional fneg.
3718   SDValue Tmp0 = Op.getOperand(0);
3719   SDValue Tmp1 = Op.getOperand(1);
3720   SDLoc dl(Op);
3721   EVT VT = Op.getValueType();
3722   EVT SrcVT = Tmp1.getValueType();
3723   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3724     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3725   bool UseNEON = !InGPR && Subtarget->hasNEON();
3726
3727   if (UseNEON) {
3728     // Use VBSL to copy the sign bit.
3729     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3730     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3731                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3732     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3733     if (VT == MVT::f64)
3734       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3735                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3736                          DAG.getConstant(32, MVT::i32));
3737     else /*if (VT == MVT::f32)*/
3738       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3739     if (SrcVT == MVT::f32) {
3740       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3741       if (VT == MVT::f64)
3742         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3743                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3744                            DAG.getConstant(32, MVT::i32));
3745     } else if (VT == MVT::f32)
3746       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3747                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3748                          DAG.getConstant(32, MVT::i32));
3749     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3750     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3751
3752     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3753                                             MVT::i32);
3754     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3755     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3756                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3757
3758     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3759                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3760                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3761     if (VT == MVT::f32) {
3762       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3763       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3764                         DAG.getConstant(0, MVT::i32));
3765     } else {
3766       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3767     }
3768
3769     return Res;
3770   }
3771
3772   // Bitcast operand 1 to i32.
3773   if (SrcVT == MVT::f64)
3774     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3775                        &Tmp1, 1).getValue(1);
3776   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3777
3778   // Or in the signbit with integer operations.
3779   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3780   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3781   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3782   if (VT == MVT::f32) {
3783     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3784                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3785     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3786                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3787   }
3788
3789   // f64: Or the high part with signbit and then combine two parts.
3790   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3791                      &Tmp0, 1);
3792   SDValue Lo = Tmp0.getValue(0);
3793   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3794   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3795   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3796 }
3797
3798 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3799   MachineFunction &MF = DAG.getMachineFunction();
3800   MachineFrameInfo *MFI = MF.getFrameInfo();
3801   MFI->setReturnAddressIsTaken(true);
3802
3803   EVT VT = Op.getValueType();
3804   SDLoc dl(Op);
3805   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3806   if (Depth) {
3807     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3808     SDValue Offset = DAG.getConstant(4, MVT::i32);
3809     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3810                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3811                        MachinePointerInfo(), false, false, false, 0);
3812   }
3813
3814   // Return LR, which contains the return address. Mark it an implicit live-in.
3815   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3816   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3817 }
3818
3819 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3820   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3821   MFI->setFrameAddressIsTaken(true);
3822
3823   EVT VT = Op.getValueType();
3824   SDLoc dl(Op);  // FIXME probably not meaningful
3825   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3826   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3827     ? ARM::R7 : ARM::R11;
3828   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3829   while (Depth--)
3830     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3831                             MachinePointerInfo(),
3832                             false, false, false, 0);
3833   return FrameAddr;
3834 }
3835
3836 /// ExpandBITCAST - If the target supports VFP, this function is called to
3837 /// expand a bit convert where either the source or destination type is i64 to
3838 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3839 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3840 /// vectors), since the legalizer won't know what to do with that.
3841 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3842   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3843   SDLoc dl(N);
3844   SDValue Op = N->getOperand(0);
3845
3846   // This function is only supposed to be called for i64 types, either as the
3847   // source or destination of the bit convert.
3848   EVT SrcVT = Op.getValueType();
3849   EVT DstVT = N->getValueType(0);
3850   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3851          "ExpandBITCAST called for non-i64 type");
3852
3853   // Turn i64->f64 into VMOVDRR.
3854   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3855     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3856                              DAG.getConstant(0, MVT::i32));
3857     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3858                              DAG.getConstant(1, MVT::i32));
3859     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3860                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3861   }
3862
3863   // Turn f64->i64 into VMOVRRD.
3864   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3865     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3866                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3867     // Merge the pieces into a single i64 value.
3868     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3869   }
3870
3871   return SDValue();
3872 }
3873
3874 /// getZeroVector - Returns a vector of specified type with all zero elements.
3875 /// Zero vectors are used to represent vector negation and in those cases
3876 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3877 /// not support i64 elements, so sometimes the zero vectors will need to be
3878 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3879 /// zero vector.
3880 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3881   assert(VT.isVector() && "Expected a vector type");
3882   // The canonical modified immediate encoding of a zero vector is....0!
3883   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3884   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3885   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3886   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3887 }
3888
3889 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3890 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3891 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3892                                                 SelectionDAG &DAG) const {
3893   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3894   EVT VT = Op.getValueType();
3895   unsigned VTBits = VT.getSizeInBits();
3896   SDLoc dl(Op);
3897   SDValue ShOpLo = Op.getOperand(0);
3898   SDValue ShOpHi = Op.getOperand(1);
3899   SDValue ShAmt  = Op.getOperand(2);
3900   SDValue ARMcc;
3901   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3902
3903   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3904
3905   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3906                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3907   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3908   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3909                                    DAG.getConstant(VTBits, MVT::i32));
3910   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3911   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3912   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3913
3914   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3915   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3916                           ARMcc, DAG, dl);
3917   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3918   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3919                            CCR, Cmp);
3920
3921   SDValue Ops[2] = { Lo, Hi };
3922   return DAG.getMergeValues(Ops, 2, dl);
3923 }
3924
3925 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3926 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3927 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3928                                                SelectionDAG &DAG) const {
3929   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3930   EVT VT = Op.getValueType();
3931   unsigned VTBits = VT.getSizeInBits();
3932   SDLoc dl(Op);
3933   SDValue ShOpLo = Op.getOperand(0);
3934   SDValue ShOpHi = Op.getOperand(1);
3935   SDValue ShAmt  = Op.getOperand(2);
3936   SDValue ARMcc;
3937
3938   assert(Op.getOpcode() == ISD::SHL_PARTS);
3939   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3940                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3941   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3942   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3943                                    DAG.getConstant(VTBits, MVT::i32));
3944   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3945   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3946
3947   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3948   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3949   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3950                           ARMcc, DAG, dl);
3951   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3952   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3953                            CCR, Cmp);
3954
3955   SDValue Ops[2] = { Lo, Hi };
3956   return DAG.getMergeValues(Ops, 2, dl);
3957 }
3958
3959 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3960                                             SelectionDAG &DAG) const {
3961   // The rounding mode is in bits 23:22 of the FPSCR.
3962   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3963   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3964   // so that the shift + and get folded into a bitfield extract.
3965   SDLoc dl(Op);
3966   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3967                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3968                                               MVT::i32));
3969   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3970                                   DAG.getConstant(1U << 22, MVT::i32));
3971   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3972                               DAG.getConstant(22, MVT::i32));
3973   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3974                      DAG.getConstant(3, MVT::i32));
3975 }
3976
3977 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3978                          const ARMSubtarget *ST) {
3979   EVT VT = N->getValueType(0);
3980   SDLoc dl(N);
3981
3982   if (!ST->hasV6T2Ops())
3983     return SDValue();
3984
3985   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3986   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3987 }
3988
3989 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3990 /// for each 16-bit element from operand, repeated.  The basic idea is to
3991 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3992 ///
3993 /// Trace for v4i16:
3994 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
3995 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3996 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3997 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3998 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
3999 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4000 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4001 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4002 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4003   EVT VT = N->getValueType(0);
4004   SDLoc DL(N);
4005
4006   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4007   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4008   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4009   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4010   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4011   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4012 }
4013
4014 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4015 /// bit-count for each 16-bit element from the operand.  We need slightly
4016 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4017 /// 64/128-bit registers.
4018 ///
4019 /// Trace for v4i16:
4020 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4021 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4022 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4023 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4024 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4025   EVT VT = N->getValueType(0);
4026   SDLoc DL(N);
4027
4028   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4029   if (VT.is64BitVector()) {
4030     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4031     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4032                        DAG.getIntPtrConstant(0));
4033   } else {
4034     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4035                                     BitCounts, DAG.getIntPtrConstant(0));
4036     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4037   }
4038 }
4039
4040 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4041 /// bit-count for each 32-bit element from the operand.  The idea here is
4042 /// to split the vector into 16-bit elements, leverage the 16-bit count
4043 /// routine, and then combine the results.
4044 ///
4045 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4046 /// input    = [v0    v1    ] (vi: 32-bit elements)
4047 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4048 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4049 /// vrev: N0 = [k1 k0 k3 k2 ]
4050 ///            [k0 k1 k2 k3 ]
4051 ///       N1 =+[k1 k0 k3 k2 ]
4052 ///            [k0 k2 k1 k3 ]
4053 ///       N2 =+[k1 k3 k0 k2 ]
4054 ///            [k0    k2    k1    k3    ]
4055 /// Extended =+[k1    k3    k0    k2    ]
4056 ///            [k0    k2    ]
4057 /// Extracted=+[k1    k3    ]
4058 ///
4059 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4060   EVT VT = N->getValueType(0);
4061   SDLoc DL(N);
4062
4063   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4064
4065   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4066   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4067   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4068   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4069   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4070
4071   if (VT.is64BitVector()) {
4072     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4073     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4074                        DAG.getIntPtrConstant(0));
4075   } else {
4076     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4077                                     DAG.getIntPtrConstant(0));
4078     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4079   }
4080 }
4081
4082 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4083                           const ARMSubtarget *ST) {
4084   EVT VT = N->getValueType(0);
4085
4086   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4087   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4088           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4089          "Unexpected type for custom ctpop lowering");
4090
4091   if (VT.getVectorElementType() == MVT::i32)
4092     return lowerCTPOP32BitElements(N, DAG);
4093   else
4094     return lowerCTPOP16BitElements(N, DAG);
4095 }
4096
4097 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4098                           const ARMSubtarget *ST) {
4099   EVT VT = N->getValueType(0);
4100   SDLoc dl(N);
4101
4102   if (!VT.isVector())
4103     return SDValue();
4104
4105   // Lower vector shifts on NEON to use VSHL.
4106   assert(ST->hasNEON() && "unexpected vector shift");
4107
4108   // Left shifts translate directly to the vshiftu intrinsic.
4109   if (N->getOpcode() == ISD::SHL)
4110     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4111                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4112                        N->getOperand(0), N->getOperand(1));
4113
4114   assert((N->getOpcode() == ISD::SRA ||
4115           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4116
4117   // NEON uses the same intrinsics for both left and right shifts.  For
4118   // right shifts, the shift amounts are negative, so negate the vector of
4119   // shift amounts.
4120   EVT ShiftVT = N->getOperand(1).getValueType();
4121   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4122                                      getZeroVector(ShiftVT, DAG, dl),
4123                                      N->getOperand(1));
4124   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4125                              Intrinsic::arm_neon_vshifts :
4126                              Intrinsic::arm_neon_vshiftu);
4127   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4128                      DAG.getConstant(vshiftInt, MVT::i32),
4129                      N->getOperand(0), NegatedCount);
4130 }
4131
4132 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4133                                 const ARMSubtarget *ST) {
4134   EVT VT = N->getValueType(0);
4135   SDLoc dl(N);
4136
4137   // We can get here for a node like i32 = ISD::SHL i32, i64
4138   if (VT != MVT::i64)
4139     return SDValue();
4140
4141   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4142          "Unknown shift to lower!");
4143
4144   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4145   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4146       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4147     return SDValue();
4148
4149   // If we are in thumb mode, we don't have RRX.
4150   if (ST->isThumb1Only()) return SDValue();
4151
4152   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4153   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4154                            DAG.getConstant(0, MVT::i32));
4155   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4156                            DAG.getConstant(1, MVT::i32));
4157
4158   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4159   // captures the result into a carry flag.
4160   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4161   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
4162
4163   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4164   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4165
4166   // Merge the pieces into a single i64 value.
4167  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4168 }
4169
4170 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4171   SDValue TmpOp0, TmpOp1;
4172   bool Invert = false;
4173   bool Swap = false;
4174   unsigned Opc = 0;
4175
4176   SDValue Op0 = Op.getOperand(0);
4177   SDValue Op1 = Op.getOperand(1);
4178   SDValue CC = Op.getOperand(2);
4179   EVT VT = Op.getValueType();
4180   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4181   SDLoc dl(Op);
4182
4183   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4184     switch (SetCCOpcode) {
4185     default: llvm_unreachable("Illegal FP comparison");
4186     case ISD::SETUNE:
4187     case ISD::SETNE:  Invert = true; // Fallthrough
4188     case ISD::SETOEQ:
4189     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4190     case ISD::SETOLT:
4191     case ISD::SETLT: Swap = true; // Fallthrough
4192     case ISD::SETOGT:
4193     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4194     case ISD::SETOLE:
4195     case ISD::SETLE:  Swap = true; // Fallthrough
4196     case ISD::SETOGE:
4197     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4198     case ISD::SETUGE: Swap = true; // Fallthrough
4199     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4200     case ISD::SETUGT: Swap = true; // Fallthrough
4201     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4202     case ISD::SETUEQ: Invert = true; // Fallthrough
4203     case ISD::SETONE:
4204       // Expand this to (OLT | OGT).
4205       TmpOp0 = Op0;
4206       TmpOp1 = Op1;
4207       Opc = ISD::OR;
4208       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4209       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4210       break;
4211     case ISD::SETUO: Invert = true; // Fallthrough
4212     case ISD::SETO:
4213       // Expand this to (OLT | OGE).
4214       TmpOp0 = Op0;
4215       TmpOp1 = Op1;
4216       Opc = ISD::OR;
4217       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4218       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4219       break;
4220     }
4221   } else {
4222     // Integer comparisons.
4223     switch (SetCCOpcode) {
4224     default: llvm_unreachable("Illegal integer comparison");
4225     case ISD::SETNE:  Invert = true;
4226     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4227     case ISD::SETLT:  Swap = true;
4228     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4229     case ISD::SETLE:  Swap = true;
4230     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4231     case ISD::SETULT: Swap = true;
4232     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4233     case ISD::SETULE: Swap = true;
4234     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4235     }
4236
4237     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4238     if (Opc == ARMISD::VCEQ) {
4239
4240       SDValue AndOp;
4241       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4242         AndOp = Op0;
4243       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4244         AndOp = Op1;
4245
4246       // Ignore bitconvert.
4247       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4248         AndOp = AndOp.getOperand(0);
4249
4250       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4251         Opc = ARMISD::VTST;
4252         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4253         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4254         Invert = !Invert;
4255       }
4256     }
4257   }
4258
4259   if (Swap)
4260     std::swap(Op0, Op1);
4261
4262   // If one of the operands is a constant vector zero, attempt to fold the
4263   // comparison to a specialized compare-against-zero form.
4264   SDValue SingleOp;
4265   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4266     SingleOp = Op0;
4267   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4268     if (Opc == ARMISD::VCGE)
4269       Opc = ARMISD::VCLEZ;
4270     else if (Opc == ARMISD::VCGT)
4271       Opc = ARMISD::VCLTZ;
4272     SingleOp = Op1;
4273   }
4274
4275   SDValue Result;
4276   if (SingleOp.getNode()) {
4277     switch (Opc) {
4278     case ARMISD::VCEQ:
4279       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4280     case ARMISD::VCGE:
4281       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4282     case ARMISD::VCLEZ:
4283       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4284     case ARMISD::VCGT:
4285       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4286     case ARMISD::VCLTZ:
4287       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4288     default:
4289       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4290     }
4291   } else {
4292      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4293   }
4294
4295   if (Invert)
4296     Result = DAG.getNOT(dl, Result, VT);
4297
4298   return Result;
4299 }
4300
4301 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4302 /// valid vector constant for a NEON instruction with a "modified immediate"
4303 /// operand (e.g., VMOV).  If so, return the encoded value.
4304 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4305                                  unsigned SplatBitSize, SelectionDAG &DAG,
4306                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4307   unsigned OpCmode, Imm;
4308
4309   // SplatBitSize is set to the smallest size that splats the vector, so a
4310   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4311   // immediate instructions others than VMOV do not support the 8-bit encoding
4312   // of a zero vector, and the default encoding of zero is supposed to be the
4313   // 32-bit version.
4314   if (SplatBits == 0)
4315     SplatBitSize = 32;
4316
4317   switch (SplatBitSize) {
4318   case 8:
4319     if (type != VMOVModImm)
4320       return SDValue();
4321     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4322     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4323     OpCmode = 0xe;
4324     Imm = SplatBits;
4325     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4326     break;
4327
4328   case 16:
4329     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4330     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4331     if ((SplatBits & ~0xff) == 0) {
4332       // Value = 0x00nn: Op=x, Cmode=100x.
4333       OpCmode = 0x8;
4334       Imm = SplatBits;
4335       break;
4336     }
4337     if ((SplatBits & ~0xff00) == 0) {
4338       // Value = 0xnn00: Op=x, Cmode=101x.
4339       OpCmode = 0xa;
4340       Imm = SplatBits >> 8;
4341       break;
4342     }
4343     return SDValue();
4344
4345   case 32:
4346     // NEON's 32-bit VMOV supports splat values where:
4347     // * only one byte is nonzero, or
4348     // * the least significant byte is 0xff and the second byte is nonzero, or
4349     // * the least significant 2 bytes are 0xff and the third is nonzero.
4350     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4351     if ((SplatBits & ~0xff) == 0) {
4352       // Value = 0x000000nn: Op=x, Cmode=000x.
4353       OpCmode = 0;
4354       Imm = SplatBits;
4355       break;
4356     }
4357     if ((SplatBits & ~0xff00) == 0) {
4358       // Value = 0x0000nn00: Op=x, Cmode=001x.
4359       OpCmode = 0x2;
4360       Imm = SplatBits >> 8;
4361       break;
4362     }
4363     if ((SplatBits & ~0xff0000) == 0) {
4364       // Value = 0x00nn0000: Op=x, Cmode=010x.
4365       OpCmode = 0x4;
4366       Imm = SplatBits >> 16;
4367       break;
4368     }
4369     if ((SplatBits & ~0xff000000) == 0) {
4370       // Value = 0xnn000000: Op=x, Cmode=011x.
4371       OpCmode = 0x6;
4372       Imm = SplatBits >> 24;
4373       break;
4374     }
4375
4376     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4377     if (type == OtherModImm) return SDValue();
4378
4379     if ((SplatBits & ~0xffff) == 0 &&
4380         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4381       // Value = 0x0000nnff: Op=x, Cmode=1100.
4382       OpCmode = 0xc;
4383       Imm = SplatBits >> 8;
4384       SplatBits |= 0xff;
4385       break;
4386     }
4387
4388     if ((SplatBits & ~0xffffff) == 0 &&
4389         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4390       // Value = 0x00nnffff: Op=x, Cmode=1101.
4391       OpCmode = 0xd;
4392       Imm = SplatBits >> 16;
4393       SplatBits |= 0xffff;
4394       break;
4395     }
4396
4397     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4398     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4399     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4400     // and fall through here to test for a valid 64-bit splat.  But, then the
4401     // caller would also need to check and handle the change in size.
4402     return SDValue();
4403
4404   case 64: {
4405     if (type != VMOVModImm)
4406       return SDValue();
4407     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4408     uint64_t BitMask = 0xff;
4409     uint64_t Val = 0;
4410     unsigned ImmMask = 1;
4411     Imm = 0;
4412     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4413       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4414         Val |= BitMask;
4415         Imm |= ImmMask;
4416       } else if ((SplatBits & BitMask) != 0) {
4417         return SDValue();
4418       }
4419       BitMask <<= 8;
4420       ImmMask <<= 1;
4421     }
4422     // Op=1, Cmode=1110.
4423     OpCmode = 0x1e;
4424     SplatBits = Val;
4425     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4426     break;
4427   }
4428
4429   default:
4430     llvm_unreachable("unexpected size for isNEONModifiedImm");
4431   }
4432
4433   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4434   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4435 }
4436
4437 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4438                                            const ARMSubtarget *ST) const {
4439   if (!ST->hasVFP3())
4440     return SDValue();
4441
4442   bool IsDouble = Op.getValueType() == MVT::f64;
4443   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4444
4445   // Try splatting with a VMOV.f32...
4446   APFloat FPVal = CFP->getValueAPF();
4447   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4448
4449   if (ImmVal != -1) {
4450     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4451       // We have code in place to select a valid ConstantFP already, no need to
4452       // do any mangling.
4453       return Op;
4454     }
4455
4456     // It's a float and we are trying to use NEON operations where
4457     // possible. Lower it to a splat followed by an extract.
4458     SDLoc DL(Op);
4459     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4460     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4461                                       NewVal);
4462     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4463                        DAG.getConstant(0, MVT::i32));
4464   }
4465
4466   // The rest of our options are NEON only, make sure that's allowed before
4467   // proceeding..
4468   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4469     return SDValue();
4470
4471   EVT VMovVT;
4472   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4473
4474   // It wouldn't really be worth bothering for doubles except for one very
4475   // important value, which does happen to match: 0.0. So make sure we don't do
4476   // anything stupid.
4477   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4478     return SDValue();
4479
4480   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4481   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4482                                      false, VMOVModImm);
4483   if (NewVal != SDValue()) {
4484     SDLoc DL(Op);
4485     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4486                                       NewVal);
4487     if (IsDouble)
4488       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4489
4490     // It's a float: cast and extract a vector element.
4491     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4492                                        VecConstant);
4493     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4494                        DAG.getConstant(0, MVT::i32));
4495   }
4496
4497   // Finally, try a VMVN.i32
4498   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4499                              false, VMVNModImm);
4500   if (NewVal != SDValue()) {
4501     SDLoc DL(Op);
4502     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4503
4504     if (IsDouble)
4505       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4506
4507     // It's a float: cast and extract a vector element.
4508     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4509                                        VecConstant);
4510     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4511                        DAG.getConstant(0, MVT::i32));
4512   }
4513
4514   return SDValue();
4515 }
4516
4517 // check if an VEXT instruction can handle the shuffle mask when the
4518 // vector sources of the shuffle are the same.
4519 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4520   unsigned NumElts = VT.getVectorNumElements();
4521
4522   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4523   if (M[0] < 0)
4524     return false;
4525
4526   Imm = M[0];
4527
4528   // If this is a VEXT shuffle, the immediate value is the index of the first
4529   // element.  The other shuffle indices must be the successive elements after
4530   // the first one.
4531   unsigned ExpectedElt = Imm;
4532   for (unsigned i = 1; i < NumElts; ++i) {
4533     // Increment the expected index.  If it wraps around, just follow it
4534     // back to index zero and keep going.
4535     ++ExpectedElt;
4536     if (ExpectedElt == NumElts)
4537       ExpectedElt = 0;
4538
4539     if (M[i] < 0) continue; // ignore UNDEF indices
4540     if (ExpectedElt != static_cast<unsigned>(M[i]))
4541       return false;
4542   }
4543
4544   return true;
4545 }
4546
4547
4548 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4549                        bool &ReverseVEXT, unsigned &Imm) {
4550   unsigned NumElts = VT.getVectorNumElements();
4551   ReverseVEXT = false;
4552
4553   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4554   if (M[0] < 0)
4555     return false;
4556
4557   Imm = M[0];
4558
4559   // If this is a VEXT shuffle, the immediate value is the index of the first
4560   // element.  The other shuffle indices must be the successive elements after
4561   // the first one.
4562   unsigned ExpectedElt = Imm;
4563   for (unsigned i = 1; i < NumElts; ++i) {
4564     // Increment the expected index.  If it wraps around, it may still be
4565     // a VEXT but the source vectors must be swapped.
4566     ExpectedElt += 1;
4567     if (ExpectedElt == NumElts * 2) {
4568       ExpectedElt = 0;
4569       ReverseVEXT = true;
4570     }
4571
4572     if (M[i] < 0) continue; // ignore UNDEF indices
4573     if (ExpectedElt != static_cast<unsigned>(M[i]))
4574       return false;
4575   }
4576
4577   // Adjust the index value if the source operands will be swapped.
4578   if (ReverseVEXT)
4579     Imm -= NumElts;
4580
4581   return true;
4582 }
4583
4584 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4585 /// instruction with the specified blocksize.  (The order of the elements
4586 /// within each block of the vector is reversed.)
4587 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4588   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4589          "Only possible block sizes for VREV are: 16, 32, 64");
4590
4591   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4592   if (EltSz == 64)
4593     return false;
4594
4595   unsigned NumElts = VT.getVectorNumElements();
4596   unsigned BlockElts = M[0] + 1;
4597   // If the first shuffle index is UNDEF, be optimistic.
4598   if (M[0] < 0)
4599     BlockElts = BlockSize / EltSz;
4600
4601   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4602     return false;
4603
4604   for (unsigned i = 0; i < NumElts; ++i) {
4605     if (M[i] < 0) continue; // ignore UNDEF indices
4606     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4607       return false;
4608   }
4609
4610   return true;
4611 }
4612
4613 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4614   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4615   // range, then 0 is placed into the resulting vector. So pretty much any mask
4616   // of 8 elements can work here.
4617   return VT == MVT::v8i8 && M.size() == 8;
4618 }
4619
4620 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4621   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4622   if (EltSz == 64)
4623     return false;
4624
4625   unsigned NumElts = VT.getVectorNumElements();
4626   WhichResult = (M[0] == 0 ? 0 : 1);
4627   for (unsigned i = 0; i < NumElts; i += 2) {
4628     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4629         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4630       return false;
4631   }
4632   return true;
4633 }
4634
4635 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4636 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4637 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4638 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4639   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4640   if (EltSz == 64)
4641     return false;
4642
4643   unsigned NumElts = VT.getVectorNumElements();
4644   WhichResult = (M[0] == 0 ? 0 : 1);
4645   for (unsigned i = 0; i < NumElts; i += 2) {
4646     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4647         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4648       return false;
4649   }
4650   return true;
4651 }
4652
4653 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4654   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4655   if (EltSz == 64)
4656     return false;
4657
4658   unsigned NumElts = VT.getVectorNumElements();
4659   WhichResult = (M[0] == 0 ? 0 : 1);
4660   for (unsigned i = 0; i != NumElts; ++i) {
4661     if (M[i] < 0) continue; // ignore UNDEF indices
4662     if ((unsigned) M[i] != 2 * i + WhichResult)
4663       return false;
4664   }
4665
4666   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4667   if (VT.is64BitVector() && EltSz == 32)
4668     return false;
4669
4670   return true;
4671 }
4672
4673 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4674 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4675 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4676 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4677   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4678   if (EltSz == 64)
4679     return false;
4680
4681   unsigned Half = VT.getVectorNumElements() / 2;
4682   WhichResult = (M[0] == 0 ? 0 : 1);
4683   for (unsigned j = 0; j != 2; ++j) {
4684     unsigned Idx = WhichResult;
4685     for (unsigned i = 0; i != Half; ++i) {
4686       int MIdx = M[i + j * Half];
4687       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4688         return false;
4689       Idx += 2;
4690     }
4691   }
4692
4693   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4694   if (VT.is64BitVector() && EltSz == 32)
4695     return false;
4696
4697   return true;
4698 }
4699
4700 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4701   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4702   if (EltSz == 64)
4703     return false;
4704
4705   unsigned NumElts = VT.getVectorNumElements();
4706   WhichResult = (M[0] == 0 ? 0 : 1);
4707   unsigned Idx = WhichResult * NumElts / 2;
4708   for (unsigned i = 0; i != NumElts; i += 2) {
4709     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4710         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4711       return false;
4712     Idx += 1;
4713   }
4714
4715   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4716   if (VT.is64BitVector() && EltSz == 32)
4717     return false;
4718
4719   return true;
4720 }
4721
4722 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4723 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4724 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4725 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4726   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4727   if (EltSz == 64)
4728     return false;
4729
4730   unsigned NumElts = VT.getVectorNumElements();
4731   WhichResult = (M[0] == 0 ? 0 : 1);
4732   unsigned Idx = WhichResult * NumElts / 2;
4733   for (unsigned i = 0; i != NumElts; i += 2) {
4734     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4735         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4736       return false;
4737     Idx += 1;
4738   }
4739
4740   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4741   if (VT.is64BitVector() && EltSz == 32)
4742     return false;
4743
4744   return true;
4745 }
4746
4747 /// \return true if this is a reverse operation on an vector.
4748 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4749   unsigned NumElts = VT.getVectorNumElements();
4750   // Make sure the mask has the right size.
4751   if (NumElts != M.size())
4752       return false;
4753
4754   // Look for <15, ..., 3, -1, 1, 0>.
4755   for (unsigned i = 0; i != NumElts; ++i)
4756     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4757       return false;
4758
4759   return true;
4760 }
4761
4762 // If N is an integer constant that can be moved into a register in one
4763 // instruction, return an SDValue of such a constant (will become a MOV
4764 // instruction).  Otherwise return null.
4765 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4766                                      const ARMSubtarget *ST, SDLoc dl) {
4767   uint64_t Val;
4768   if (!isa<ConstantSDNode>(N))
4769     return SDValue();
4770   Val = cast<ConstantSDNode>(N)->getZExtValue();
4771
4772   if (ST->isThumb1Only()) {
4773     if (Val <= 255 || ~Val <= 255)
4774       return DAG.getConstant(Val, MVT::i32);
4775   } else {
4776     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4777       return DAG.getConstant(Val, MVT::i32);
4778   }
4779   return SDValue();
4780 }
4781
4782 // If this is a case we can't handle, return null and let the default
4783 // expansion code take care of it.
4784 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4785                                              const ARMSubtarget *ST) const {
4786   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4787   SDLoc dl(Op);
4788   EVT VT = Op.getValueType();
4789
4790   APInt SplatBits, SplatUndef;
4791   unsigned SplatBitSize;
4792   bool HasAnyUndefs;
4793   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4794     if (SplatBitSize <= 64) {
4795       // Check if an immediate VMOV works.
4796       EVT VmovVT;
4797       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4798                                       SplatUndef.getZExtValue(), SplatBitSize,
4799                                       DAG, VmovVT, VT.is128BitVector(),
4800                                       VMOVModImm);
4801       if (Val.getNode()) {
4802         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4803         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4804       }
4805
4806       // Try an immediate VMVN.
4807       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4808       Val = isNEONModifiedImm(NegatedImm,
4809                                       SplatUndef.getZExtValue(), SplatBitSize,
4810                                       DAG, VmovVT, VT.is128BitVector(),
4811                                       VMVNModImm);
4812       if (Val.getNode()) {
4813         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4814         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4815       }
4816
4817       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4818       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4819         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4820         if (ImmVal != -1) {
4821           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4822           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4823         }
4824       }
4825     }
4826   }
4827
4828   // Scan through the operands to see if only one value is used.
4829   //
4830   // As an optimisation, even if more than one value is used it may be more
4831   // profitable to splat with one value then change some lanes.
4832   //
4833   // Heuristically we decide to do this if the vector has a "dominant" value,
4834   // defined as splatted to more than half of the lanes.
4835   unsigned NumElts = VT.getVectorNumElements();
4836   bool isOnlyLowElement = true;
4837   bool usesOnlyOneValue = true;
4838   bool hasDominantValue = false;
4839   bool isConstant = true;
4840
4841   // Map of the number of times a particular SDValue appears in the
4842   // element list.
4843   DenseMap<SDValue, unsigned> ValueCounts;
4844   SDValue Value;
4845   for (unsigned i = 0; i < NumElts; ++i) {
4846     SDValue V = Op.getOperand(i);
4847     if (V.getOpcode() == ISD::UNDEF)
4848       continue;
4849     if (i > 0)
4850       isOnlyLowElement = false;
4851     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4852       isConstant = false;
4853
4854     ValueCounts.insert(std::make_pair(V, 0));
4855     unsigned &Count = ValueCounts[V];
4856
4857     // Is this value dominant? (takes up more than half of the lanes)
4858     if (++Count > (NumElts / 2)) {
4859       hasDominantValue = true;
4860       Value = V;
4861     }
4862   }
4863   if (ValueCounts.size() != 1)
4864     usesOnlyOneValue = false;
4865   if (!Value.getNode() && ValueCounts.size() > 0)
4866     Value = ValueCounts.begin()->first;
4867
4868   if (ValueCounts.size() == 0)
4869     return DAG.getUNDEF(VT);
4870
4871   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
4872   // Keep going if we are hitting this case.
4873   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
4874     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4875
4876   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4877
4878   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4879   // i32 and try again.
4880   if (hasDominantValue && EltSize <= 32) {
4881     if (!isConstant) {
4882       SDValue N;
4883
4884       // If we are VDUPing a value that comes directly from a vector, that will
4885       // cause an unnecessary move to and from a GPR, where instead we could
4886       // just use VDUPLANE. We can only do this if the lane being extracted
4887       // is at a constant index, as the VDUP from lane instructions only have
4888       // constant-index forms.
4889       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4890           isa<ConstantSDNode>(Value->getOperand(1))) {
4891         // We need to create a new undef vector to use for the VDUPLANE if the
4892         // size of the vector from which we get the value is different than the
4893         // size of the vector that we need to create. We will insert the element
4894         // such that the register coalescer will remove unnecessary copies.
4895         if (VT != Value->getOperand(0).getValueType()) {
4896           ConstantSDNode *constIndex;
4897           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4898           assert(constIndex && "The index is not a constant!");
4899           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4900                              VT.getVectorNumElements();
4901           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4902                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4903                         Value, DAG.getConstant(index, MVT::i32)),
4904                            DAG.getConstant(index, MVT::i32));
4905         } else
4906           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4907                         Value->getOperand(0), Value->getOperand(1));
4908       } else
4909         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4910
4911       if (!usesOnlyOneValue) {
4912         // The dominant value was splatted as 'N', but we now have to insert
4913         // all differing elements.
4914         for (unsigned I = 0; I < NumElts; ++I) {
4915           if (Op.getOperand(I) == Value)
4916             continue;
4917           SmallVector<SDValue, 3> Ops;
4918           Ops.push_back(N);
4919           Ops.push_back(Op.getOperand(I));
4920           Ops.push_back(DAG.getConstant(I, MVT::i32));
4921           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4922         }
4923       }
4924       return N;
4925     }
4926     if (VT.getVectorElementType().isFloatingPoint()) {
4927       SmallVector<SDValue, 8> Ops;
4928       for (unsigned i = 0; i < NumElts; ++i)
4929         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4930                                   Op.getOperand(i)));
4931       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4932       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4933       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4934       if (Val.getNode())
4935         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4936     }
4937     if (usesOnlyOneValue) {
4938       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4939       if (isConstant && Val.getNode())
4940         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4941     }
4942   }
4943
4944   // If all elements are constants and the case above didn't get hit, fall back
4945   // to the default expansion, which will generate a load from the constant
4946   // pool.
4947   if (isConstant)
4948     return SDValue();
4949
4950   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4951   if (NumElts >= 4) {
4952     SDValue shuffle = ReconstructShuffle(Op, DAG);
4953     if (shuffle != SDValue())
4954       return shuffle;
4955   }
4956
4957   // Vectors with 32- or 64-bit elements can be built by directly assigning
4958   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4959   // will be legalized.
4960   if (EltSize >= 32) {
4961     // Do the expansion with floating-point types, since that is what the VFP
4962     // registers are defined to use, and since i64 is not legal.
4963     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4964     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4965     SmallVector<SDValue, 8> Ops;
4966     for (unsigned i = 0; i < NumElts; ++i)
4967       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4968     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4969     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4970   }
4971
4972   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
4973   // know the default expansion would otherwise fall back on something even
4974   // worse. For a vector with one or two non-undef values, that's
4975   // scalar_to_vector for the elements followed by a shuffle (provided the
4976   // shuffle is valid for the target) and materialization element by element
4977   // on the stack followed by a load for everything else.
4978   if (!isConstant && !usesOnlyOneValue) {
4979     SDValue Vec = DAG.getUNDEF(VT);
4980     for (unsigned i = 0 ; i < NumElts; ++i) {
4981       SDValue V = Op.getOperand(i);
4982       if (V.getOpcode() == ISD::UNDEF)
4983         continue;
4984       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
4985       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
4986     }
4987     return Vec;
4988   }
4989
4990   return SDValue();
4991 }
4992
4993 // Gather data to see if the operation can be modelled as a
4994 // shuffle in combination with VEXTs.
4995 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4996                                               SelectionDAG &DAG) const {
4997   SDLoc dl(Op);
4998   EVT VT = Op.getValueType();
4999   unsigned NumElts = VT.getVectorNumElements();
5000
5001   SmallVector<SDValue, 2> SourceVecs;
5002   SmallVector<unsigned, 2> MinElts;
5003   SmallVector<unsigned, 2> MaxElts;
5004
5005   for (unsigned i = 0; i < NumElts; ++i) {
5006     SDValue V = Op.getOperand(i);
5007     if (V.getOpcode() == ISD::UNDEF)
5008       continue;
5009     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5010       // A shuffle can only come from building a vector from various
5011       // elements of other vectors.
5012       return SDValue();
5013     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5014                VT.getVectorElementType()) {
5015       // This code doesn't know how to handle shuffles where the vector
5016       // element types do not match (this happens because type legalization
5017       // promotes the return type of EXTRACT_VECTOR_ELT).
5018       // FIXME: It might be appropriate to extend this code to handle
5019       // mismatched types.
5020       return SDValue();
5021     }
5022
5023     // Record this extraction against the appropriate vector if possible...
5024     SDValue SourceVec = V.getOperand(0);
5025     // If the element number isn't a constant, we can't effectively
5026     // analyze what's going on.
5027     if (!isa<ConstantSDNode>(V.getOperand(1)))
5028       return SDValue();
5029     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5030     bool FoundSource = false;
5031     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5032       if (SourceVecs[j] == SourceVec) {
5033         if (MinElts[j] > EltNo)
5034           MinElts[j] = EltNo;
5035         if (MaxElts[j] < EltNo)
5036           MaxElts[j] = EltNo;
5037         FoundSource = true;
5038         break;
5039       }
5040     }
5041
5042     // Or record a new source if not...
5043     if (!FoundSource) {
5044       SourceVecs.push_back(SourceVec);
5045       MinElts.push_back(EltNo);
5046       MaxElts.push_back(EltNo);
5047     }
5048   }
5049
5050   // Currently only do something sane when at most two source vectors
5051   // involved.
5052   if (SourceVecs.size() > 2)
5053     return SDValue();
5054
5055   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5056   int VEXTOffsets[2] = {0, 0};
5057
5058   // This loop extracts the usage patterns of the source vectors
5059   // and prepares appropriate SDValues for a shuffle if possible.
5060   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5061     if (SourceVecs[i].getValueType() == VT) {
5062       // No VEXT necessary
5063       ShuffleSrcs[i] = SourceVecs[i];
5064       VEXTOffsets[i] = 0;
5065       continue;
5066     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5067       // It probably isn't worth padding out a smaller vector just to
5068       // break it down again in a shuffle.
5069       return SDValue();
5070     }
5071
5072     // Since only 64-bit and 128-bit vectors are legal on ARM and
5073     // we've eliminated the other cases...
5074     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5075            "unexpected vector sizes in ReconstructShuffle");
5076
5077     if (MaxElts[i] - MinElts[i] >= NumElts) {
5078       // Span too large for a VEXT to cope
5079       return SDValue();
5080     }
5081
5082     if (MinElts[i] >= NumElts) {
5083       // The extraction can just take the second half
5084       VEXTOffsets[i] = NumElts;
5085       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5086                                    SourceVecs[i],
5087                                    DAG.getIntPtrConstant(NumElts));
5088     } else if (MaxElts[i] < NumElts) {
5089       // The extraction can just take the first half
5090       VEXTOffsets[i] = 0;
5091       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5092                                    SourceVecs[i],
5093                                    DAG.getIntPtrConstant(0));
5094     } else {
5095       // An actual VEXT is needed
5096       VEXTOffsets[i] = MinElts[i];
5097       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5098                                      SourceVecs[i],
5099                                      DAG.getIntPtrConstant(0));
5100       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5101                                      SourceVecs[i],
5102                                      DAG.getIntPtrConstant(NumElts));
5103       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5104                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5105     }
5106   }
5107
5108   SmallVector<int, 8> Mask;
5109
5110   for (unsigned i = 0; i < NumElts; ++i) {
5111     SDValue Entry = Op.getOperand(i);
5112     if (Entry.getOpcode() == ISD::UNDEF) {
5113       Mask.push_back(-1);
5114       continue;
5115     }
5116
5117     SDValue ExtractVec = Entry.getOperand(0);
5118     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5119                                           .getOperand(1))->getSExtValue();
5120     if (ExtractVec == SourceVecs[0]) {
5121       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5122     } else {
5123       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5124     }
5125   }
5126
5127   // Final check before we try to produce nonsense...
5128   if (isShuffleMaskLegal(Mask, VT))
5129     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5130                                 &Mask[0]);
5131
5132   return SDValue();
5133 }
5134
5135 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5136 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5137 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5138 /// are assumed to be legal.
5139 bool
5140 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5141                                       EVT VT) const {
5142   if (VT.getVectorNumElements() == 4 &&
5143       (VT.is128BitVector() || VT.is64BitVector())) {
5144     unsigned PFIndexes[4];
5145     for (unsigned i = 0; i != 4; ++i) {
5146       if (M[i] < 0)
5147         PFIndexes[i] = 8;
5148       else
5149         PFIndexes[i] = M[i];
5150     }
5151
5152     // Compute the index in the perfect shuffle table.
5153     unsigned PFTableIndex =
5154       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5155     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5156     unsigned Cost = (PFEntry >> 30);
5157
5158     if (Cost <= 4)
5159       return true;
5160   }
5161
5162   bool ReverseVEXT;
5163   unsigned Imm, WhichResult;
5164
5165   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5166   return (EltSize >= 32 ||
5167           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5168           isVREVMask(M, VT, 64) ||
5169           isVREVMask(M, VT, 32) ||
5170           isVREVMask(M, VT, 16) ||
5171           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5172           isVTBLMask(M, VT) ||
5173           isVTRNMask(M, VT, WhichResult) ||
5174           isVUZPMask(M, VT, WhichResult) ||
5175           isVZIPMask(M, VT, WhichResult) ||
5176           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5177           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5178           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5179           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5180 }
5181
5182 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5183 /// the specified operations to build the shuffle.
5184 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5185                                       SDValue RHS, SelectionDAG &DAG,
5186                                       SDLoc dl) {
5187   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5188   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5189   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5190
5191   enum {
5192     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5193     OP_VREV,
5194     OP_VDUP0,
5195     OP_VDUP1,
5196     OP_VDUP2,
5197     OP_VDUP3,
5198     OP_VEXT1,
5199     OP_VEXT2,
5200     OP_VEXT3,
5201     OP_VUZPL, // VUZP, left result
5202     OP_VUZPR, // VUZP, right result
5203     OP_VZIPL, // VZIP, left result
5204     OP_VZIPR, // VZIP, right result
5205     OP_VTRNL, // VTRN, left result
5206     OP_VTRNR  // VTRN, right result
5207   };
5208
5209   if (OpNum == OP_COPY) {
5210     if (LHSID == (1*9+2)*9+3) return LHS;
5211     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5212     return RHS;
5213   }
5214
5215   SDValue OpLHS, OpRHS;
5216   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5217   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5218   EVT VT = OpLHS.getValueType();
5219
5220   switch (OpNum) {
5221   default: llvm_unreachable("Unknown shuffle opcode!");
5222   case OP_VREV:
5223     // VREV divides the vector in half and swaps within the half.
5224     if (VT.getVectorElementType() == MVT::i32 ||
5225         VT.getVectorElementType() == MVT::f32)
5226       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5227     // vrev <4 x i16> -> VREV32
5228     if (VT.getVectorElementType() == MVT::i16)
5229       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5230     // vrev <4 x i8> -> VREV16
5231     assert(VT.getVectorElementType() == MVT::i8);
5232     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5233   case OP_VDUP0:
5234   case OP_VDUP1:
5235   case OP_VDUP2:
5236   case OP_VDUP3:
5237     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5238                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5239   case OP_VEXT1:
5240   case OP_VEXT2:
5241   case OP_VEXT3:
5242     return DAG.getNode(ARMISD::VEXT, dl, VT,
5243                        OpLHS, OpRHS,
5244                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5245   case OP_VUZPL:
5246   case OP_VUZPR:
5247     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5248                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5249   case OP_VZIPL:
5250   case OP_VZIPR:
5251     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5252                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5253   case OP_VTRNL:
5254   case OP_VTRNR:
5255     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5256                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5257   }
5258 }
5259
5260 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5261                                        ArrayRef<int> ShuffleMask,
5262                                        SelectionDAG &DAG) {
5263   // Check to see if we can use the VTBL instruction.
5264   SDValue V1 = Op.getOperand(0);
5265   SDValue V2 = Op.getOperand(1);
5266   SDLoc DL(Op);
5267
5268   SmallVector<SDValue, 8> VTBLMask;
5269   for (ArrayRef<int>::iterator
5270          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5271     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5272
5273   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5274     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5275                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5276                                    &VTBLMask[0], 8));
5277
5278   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5279                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5280                                  &VTBLMask[0], 8));
5281 }
5282
5283 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5284                                                       SelectionDAG &DAG) {
5285   SDLoc DL(Op);
5286   SDValue OpLHS = Op.getOperand(0);
5287   EVT VT = OpLHS.getValueType();
5288
5289   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5290          "Expect an v8i16/v16i8 type");
5291   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5292   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5293   // extract the first 8 bytes into the top double word and the last 8 bytes
5294   // into the bottom double word. The v8i16 case is similar.
5295   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5296   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5297                      DAG.getConstant(ExtractNum, MVT::i32));
5298 }
5299
5300 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5301   SDValue V1 = Op.getOperand(0);
5302   SDValue V2 = Op.getOperand(1);
5303   SDLoc dl(Op);
5304   EVT VT = Op.getValueType();
5305   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5306
5307   // Convert shuffles that are directly supported on NEON to target-specific
5308   // DAG nodes, instead of keeping them as shuffles and matching them again
5309   // during code selection.  This is more efficient and avoids the possibility
5310   // of inconsistencies between legalization and selection.
5311   // FIXME: floating-point vectors should be canonicalized to integer vectors
5312   // of the same time so that they get CSEd properly.
5313   ArrayRef<int> ShuffleMask = SVN->getMask();
5314
5315   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5316   if (EltSize <= 32) {
5317     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5318       int Lane = SVN->getSplatIndex();
5319       // If this is undef splat, generate it via "just" vdup, if possible.
5320       if (Lane == -1) Lane = 0;
5321
5322       // Test if V1 is a SCALAR_TO_VECTOR.
5323       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5324         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5325       }
5326       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5327       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5328       // reaches it).
5329       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5330           !isa<ConstantSDNode>(V1.getOperand(0))) {
5331         bool IsScalarToVector = true;
5332         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5333           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5334             IsScalarToVector = false;
5335             break;
5336           }
5337         if (IsScalarToVector)
5338           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5339       }
5340       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5341                          DAG.getConstant(Lane, MVT::i32));
5342     }
5343
5344     bool ReverseVEXT;
5345     unsigned Imm;
5346     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5347       if (ReverseVEXT)
5348         std::swap(V1, V2);
5349       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5350                          DAG.getConstant(Imm, MVT::i32));
5351     }
5352
5353     if (isVREVMask(ShuffleMask, VT, 64))
5354       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5355     if (isVREVMask(ShuffleMask, VT, 32))
5356       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5357     if (isVREVMask(ShuffleMask, VT, 16))
5358       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5359
5360     if (V2->getOpcode() == ISD::UNDEF &&
5361         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5362       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5363                          DAG.getConstant(Imm, MVT::i32));
5364     }
5365
5366     // Check for Neon shuffles that modify both input vectors in place.
5367     // If both results are used, i.e., if there are two shuffles with the same
5368     // source operands and with masks corresponding to both results of one of
5369     // these operations, DAG memoization will ensure that a single node is
5370     // used for both shuffles.
5371     unsigned WhichResult;
5372     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5373       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5374                          V1, V2).getValue(WhichResult);
5375     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5376       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5377                          V1, V2).getValue(WhichResult);
5378     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5379       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5380                          V1, V2).getValue(WhichResult);
5381
5382     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5383       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5384                          V1, V1).getValue(WhichResult);
5385     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5386       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5387                          V1, V1).getValue(WhichResult);
5388     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5389       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5390                          V1, V1).getValue(WhichResult);
5391   }
5392
5393   // If the shuffle is not directly supported and it has 4 elements, use
5394   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5395   unsigned NumElts = VT.getVectorNumElements();
5396   if (NumElts == 4) {
5397     unsigned PFIndexes[4];
5398     for (unsigned i = 0; i != 4; ++i) {
5399       if (ShuffleMask[i] < 0)
5400         PFIndexes[i] = 8;
5401       else
5402         PFIndexes[i] = ShuffleMask[i];
5403     }
5404
5405     // Compute the index in the perfect shuffle table.
5406     unsigned PFTableIndex =
5407       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5408     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5409     unsigned Cost = (PFEntry >> 30);
5410
5411     if (Cost <= 4)
5412       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5413   }
5414
5415   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5416   if (EltSize >= 32) {
5417     // Do the expansion with floating-point types, since that is what the VFP
5418     // registers are defined to use, and since i64 is not legal.
5419     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5420     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5421     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5422     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5423     SmallVector<SDValue, 8> Ops;
5424     for (unsigned i = 0; i < NumElts; ++i) {
5425       if (ShuffleMask[i] < 0)
5426         Ops.push_back(DAG.getUNDEF(EltVT));
5427       else
5428         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5429                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5430                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5431                                                   MVT::i32)));
5432     }
5433     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5434     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5435   }
5436
5437   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5438     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5439
5440   if (VT == MVT::v8i8) {
5441     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5442     if (NewOp.getNode())
5443       return NewOp;
5444   }
5445
5446   return SDValue();
5447 }
5448
5449 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5450   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5451   SDValue Lane = Op.getOperand(2);
5452   if (!isa<ConstantSDNode>(Lane))
5453     return SDValue();
5454
5455   return Op;
5456 }
5457
5458 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5459   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5460   SDValue Lane = Op.getOperand(1);
5461   if (!isa<ConstantSDNode>(Lane))
5462     return SDValue();
5463
5464   SDValue Vec = Op.getOperand(0);
5465   if (Op.getValueType() == MVT::i32 &&
5466       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5467     SDLoc dl(Op);
5468     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5469   }
5470
5471   return Op;
5472 }
5473
5474 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5475   // The only time a CONCAT_VECTORS operation can have legal types is when
5476   // two 64-bit vectors are concatenated to a 128-bit vector.
5477   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5478          "unexpected CONCAT_VECTORS");
5479   SDLoc dl(Op);
5480   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5481   SDValue Op0 = Op.getOperand(0);
5482   SDValue Op1 = Op.getOperand(1);
5483   if (Op0.getOpcode() != ISD::UNDEF)
5484     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5485                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5486                       DAG.getIntPtrConstant(0));
5487   if (Op1.getOpcode() != ISD::UNDEF)
5488     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5489                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5490                       DAG.getIntPtrConstant(1));
5491   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5492 }
5493
5494 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5495 /// element has been zero/sign-extended, depending on the isSigned parameter,
5496 /// from an integer type half its size.
5497 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5498                                    bool isSigned) {
5499   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5500   EVT VT = N->getValueType(0);
5501   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5502     SDNode *BVN = N->getOperand(0).getNode();
5503     if (BVN->getValueType(0) != MVT::v4i32 ||
5504         BVN->getOpcode() != ISD::BUILD_VECTOR)
5505       return false;
5506     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5507     unsigned HiElt = 1 - LoElt;
5508     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5509     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5510     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5511     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5512     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5513       return false;
5514     if (isSigned) {
5515       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5516           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5517         return true;
5518     } else {
5519       if (Hi0->isNullValue() && Hi1->isNullValue())
5520         return true;
5521     }
5522     return false;
5523   }
5524
5525   if (N->getOpcode() != ISD::BUILD_VECTOR)
5526     return false;
5527
5528   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5529     SDNode *Elt = N->getOperand(i).getNode();
5530     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5531       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5532       unsigned HalfSize = EltSize / 2;
5533       if (isSigned) {
5534         if (!isIntN(HalfSize, C->getSExtValue()))
5535           return false;
5536       } else {
5537         if (!isUIntN(HalfSize, C->getZExtValue()))
5538           return false;
5539       }
5540       continue;
5541     }
5542     return false;
5543   }
5544
5545   return true;
5546 }
5547
5548 /// isSignExtended - Check if a node is a vector value that is sign-extended
5549 /// or a constant BUILD_VECTOR with sign-extended elements.
5550 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5551   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5552     return true;
5553   if (isExtendedBUILD_VECTOR(N, DAG, true))
5554     return true;
5555   return false;
5556 }
5557
5558 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5559 /// or a constant BUILD_VECTOR with zero-extended elements.
5560 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5561   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5562     return true;
5563   if (isExtendedBUILD_VECTOR(N, DAG, false))
5564     return true;
5565   return false;
5566 }
5567
5568 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5569   if (OrigVT.getSizeInBits() >= 64)
5570     return OrigVT;
5571
5572   assert(OrigVT.isSimple() && "Expecting a simple value type");
5573
5574   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5575   switch (OrigSimpleTy) {
5576   default: llvm_unreachable("Unexpected Vector Type");
5577   case MVT::v2i8:
5578   case MVT::v2i16:
5579      return MVT::v2i32;
5580   case MVT::v4i8:
5581     return  MVT::v4i16;
5582   }
5583 }
5584
5585 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5586 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5587 /// We insert the required extension here to get the vector to fill a D register.
5588 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5589                                             const EVT &OrigTy,
5590                                             const EVT &ExtTy,
5591                                             unsigned ExtOpcode) {
5592   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5593   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5594   // 64-bits we need to insert a new extension so that it will be 64-bits.
5595   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5596   if (OrigTy.getSizeInBits() >= 64)
5597     return N;
5598
5599   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5600   EVT NewVT = getExtensionTo64Bits(OrigTy);
5601
5602   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5603 }
5604
5605 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5606 /// does not do any sign/zero extension. If the original vector is less
5607 /// than 64 bits, an appropriate extension will be added after the load to
5608 /// reach a total size of 64 bits. We have to add the extension separately
5609 /// because ARM does not have a sign/zero extending load for vectors.
5610 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5611   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5612
5613   // The load already has the right type.
5614   if (ExtendedTy == LD->getMemoryVT())
5615     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5616                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5617                 LD->isNonTemporal(), LD->isInvariant(),
5618                 LD->getAlignment());
5619
5620   // We need to create a zextload/sextload. We cannot just create a load
5621   // followed by a zext/zext node because LowerMUL is also run during normal
5622   // operation legalization where we can't create illegal types.
5623   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5624                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5625                         LD->getMemoryVT(), LD->isVolatile(),
5626                         LD->isNonTemporal(), LD->getAlignment());
5627 }
5628
5629 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5630 /// extending load, or BUILD_VECTOR with extended elements, return the
5631 /// unextended value. The unextended vector should be 64 bits so that it can
5632 /// be used as an operand to a VMULL instruction. If the original vector size
5633 /// before extension is less than 64 bits we add a an extension to resize
5634 /// the vector to 64 bits.
5635 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5636   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5637     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5638                                         N->getOperand(0)->getValueType(0),
5639                                         N->getValueType(0),
5640                                         N->getOpcode());
5641
5642   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5643     return SkipLoadExtensionForVMULL(LD, DAG);
5644
5645   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5646   // have been legalized as a BITCAST from v4i32.
5647   if (N->getOpcode() == ISD::BITCAST) {
5648     SDNode *BVN = N->getOperand(0).getNode();
5649     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5650            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5651     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5652     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5653                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5654   }
5655   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5656   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5657   EVT VT = N->getValueType(0);
5658   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5659   unsigned NumElts = VT.getVectorNumElements();
5660   MVT TruncVT = MVT::getIntegerVT(EltSize);
5661   SmallVector<SDValue, 8> Ops;
5662   for (unsigned i = 0; i != NumElts; ++i) {
5663     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5664     const APInt &CInt = C->getAPIntValue();
5665     // Element types smaller than 32 bits are not legal, so use i32 elements.
5666     // The values are implicitly truncated so sext vs. zext doesn't matter.
5667     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5668   }
5669   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5670                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5671 }
5672
5673 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5674   unsigned Opcode = N->getOpcode();
5675   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5676     SDNode *N0 = N->getOperand(0).getNode();
5677     SDNode *N1 = N->getOperand(1).getNode();
5678     return N0->hasOneUse() && N1->hasOneUse() &&
5679       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5680   }
5681   return false;
5682 }
5683
5684 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5685   unsigned Opcode = N->getOpcode();
5686   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5687     SDNode *N0 = N->getOperand(0).getNode();
5688     SDNode *N1 = N->getOperand(1).getNode();
5689     return N0->hasOneUse() && N1->hasOneUse() &&
5690       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5691   }
5692   return false;
5693 }
5694
5695 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5696   // Multiplications are only custom-lowered for 128-bit vectors so that
5697   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5698   EVT VT = Op.getValueType();
5699   assert(VT.is128BitVector() && VT.isInteger() &&
5700          "unexpected type for custom-lowering ISD::MUL");
5701   SDNode *N0 = Op.getOperand(0).getNode();
5702   SDNode *N1 = Op.getOperand(1).getNode();
5703   unsigned NewOpc = 0;
5704   bool isMLA = false;
5705   bool isN0SExt = isSignExtended(N0, DAG);
5706   bool isN1SExt = isSignExtended(N1, DAG);
5707   if (isN0SExt && isN1SExt)
5708     NewOpc = ARMISD::VMULLs;
5709   else {
5710     bool isN0ZExt = isZeroExtended(N0, DAG);
5711     bool isN1ZExt = isZeroExtended(N1, DAG);
5712     if (isN0ZExt && isN1ZExt)
5713       NewOpc = ARMISD::VMULLu;
5714     else if (isN1SExt || isN1ZExt) {
5715       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5716       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5717       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5718         NewOpc = ARMISD::VMULLs;
5719         isMLA = true;
5720       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5721         NewOpc = ARMISD::VMULLu;
5722         isMLA = true;
5723       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5724         std::swap(N0, N1);
5725         NewOpc = ARMISD::VMULLu;
5726         isMLA = true;
5727       }
5728     }
5729
5730     if (!NewOpc) {
5731       if (VT == MVT::v2i64)
5732         // Fall through to expand this.  It is not legal.
5733         return SDValue();
5734       else
5735         // Other vector multiplications are legal.
5736         return Op;
5737     }
5738   }
5739
5740   // Legalize to a VMULL instruction.
5741   SDLoc DL(Op);
5742   SDValue Op0;
5743   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5744   if (!isMLA) {
5745     Op0 = SkipExtensionForVMULL(N0, DAG);
5746     assert(Op0.getValueType().is64BitVector() &&
5747            Op1.getValueType().is64BitVector() &&
5748            "unexpected types for extended operands to VMULL");
5749     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5750   }
5751
5752   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5753   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5754   //   vmull q0, d4, d6
5755   //   vmlal q0, d5, d6
5756   // is faster than
5757   //   vaddl q0, d4, d5
5758   //   vmovl q1, d6
5759   //   vmul  q0, q0, q1
5760   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5761   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5762   EVT Op1VT = Op1.getValueType();
5763   return DAG.getNode(N0->getOpcode(), DL, VT,
5764                      DAG.getNode(NewOpc, DL, VT,
5765                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5766                      DAG.getNode(NewOpc, DL, VT,
5767                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5768 }
5769
5770 static SDValue
5771 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5772   // Convert to float
5773   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5774   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5775   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5776   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5777   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5778   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5779   // Get reciprocal estimate.
5780   // float4 recip = vrecpeq_f32(yf);
5781   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5782                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5783   // Because char has a smaller range than uchar, we can actually get away
5784   // without any newton steps.  This requires that we use a weird bias
5785   // of 0xb000, however (again, this has been exhaustively tested).
5786   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5787   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5788   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5789   Y = DAG.getConstant(0xb000, MVT::i32);
5790   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5791   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5792   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5793   // Convert back to short.
5794   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5795   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5796   return X;
5797 }
5798
5799 static SDValue
5800 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5801   SDValue N2;
5802   // Convert to float.
5803   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5804   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5805   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5806   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5807   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5808   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5809
5810   // Use reciprocal estimate and one refinement step.
5811   // float4 recip = vrecpeq_f32(yf);
5812   // recip *= vrecpsq_f32(yf, recip);
5813   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5814                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5815   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5816                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5817                    N1, N2);
5818   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5819   // Because short has a smaller range than ushort, we can actually get away
5820   // with only a single newton step.  This requires that we use a weird bias
5821   // of 89, however (again, this has been exhaustively tested).
5822   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5823   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5824   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5825   N1 = DAG.getConstant(0x89, MVT::i32);
5826   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5827   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5828   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5829   // Convert back to integer and return.
5830   // return vmovn_s32(vcvt_s32_f32(result));
5831   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5832   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5833   return N0;
5834 }
5835
5836 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5837   EVT VT = Op.getValueType();
5838   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5839          "unexpected type for custom-lowering ISD::SDIV");
5840
5841   SDLoc dl(Op);
5842   SDValue N0 = Op.getOperand(0);
5843   SDValue N1 = Op.getOperand(1);
5844   SDValue N2, N3;
5845
5846   if (VT == MVT::v8i8) {
5847     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5848     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5849
5850     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5851                      DAG.getIntPtrConstant(4));
5852     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5853                      DAG.getIntPtrConstant(4));
5854     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5855                      DAG.getIntPtrConstant(0));
5856     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5857                      DAG.getIntPtrConstant(0));
5858
5859     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5860     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5861
5862     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5863     N0 = LowerCONCAT_VECTORS(N0, DAG);
5864
5865     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5866     return N0;
5867   }
5868   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5869 }
5870
5871 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5872   EVT VT = Op.getValueType();
5873   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5874          "unexpected type for custom-lowering ISD::UDIV");
5875
5876   SDLoc dl(Op);
5877   SDValue N0 = Op.getOperand(0);
5878   SDValue N1 = Op.getOperand(1);
5879   SDValue N2, N3;
5880
5881   if (VT == MVT::v8i8) {
5882     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5883     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5884
5885     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5886                      DAG.getIntPtrConstant(4));
5887     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5888                      DAG.getIntPtrConstant(4));
5889     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5890                      DAG.getIntPtrConstant(0));
5891     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5892                      DAG.getIntPtrConstant(0));
5893
5894     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5895     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5896
5897     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5898     N0 = LowerCONCAT_VECTORS(N0, DAG);
5899
5900     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5901                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5902                      N0);
5903     return N0;
5904   }
5905
5906   // v4i16 sdiv ... Convert to float.
5907   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5908   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5909   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5910   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5911   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5912   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5913
5914   // Use reciprocal estimate and two refinement steps.
5915   // float4 recip = vrecpeq_f32(yf);
5916   // recip *= vrecpsq_f32(yf, recip);
5917   // recip *= vrecpsq_f32(yf, recip);
5918   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5919                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5920   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5921                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5922                    BN1, N2);
5923   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5924   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5925                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5926                    BN1, N2);
5927   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5928   // Simply multiplying by the reciprocal estimate can leave us a few ulps
5929   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5930   // and that it will never cause us to return an answer too large).
5931   // float4 result = as_float4(as_int4(xf*recip) + 2);
5932   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5933   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5934   N1 = DAG.getConstant(2, MVT::i32);
5935   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5936   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5937   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5938   // Convert back to integer and return.
5939   // return vmovn_u32(vcvt_s32_f32(result));
5940   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5941   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5942   return N0;
5943 }
5944
5945 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5946   EVT VT = Op.getNode()->getValueType(0);
5947   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5948
5949   unsigned Opc;
5950   bool ExtraOp = false;
5951   switch (Op.getOpcode()) {
5952   default: llvm_unreachable("Invalid code");
5953   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5954   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5955   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5956   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5957   }
5958
5959   if (!ExtraOp)
5960     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5961                        Op.getOperand(1));
5962   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5963                      Op.getOperand(1), Op.getOperand(2));
5964 }
5965
5966 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
5967   assert(Subtarget->isTargetDarwin());
5968
5969   // For iOS, we want to call an alternative entry point: __sincos_stret,
5970   // return values are passed via sret.
5971   SDLoc dl(Op);
5972   SDValue Arg = Op.getOperand(0);
5973   EVT ArgVT = Arg.getValueType();
5974   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
5975
5976   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
5977   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5978
5979   // Pair of floats / doubles used to pass the result.
5980   StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
5981
5982   // Create stack object for sret.
5983   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
5984   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
5985   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
5986   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
5987
5988   ArgListTy Args;
5989   ArgListEntry Entry;
5990
5991   Entry.Node = SRet;
5992   Entry.Ty = RetTy->getPointerTo();
5993   Entry.isSExt = false;
5994   Entry.isZExt = false;
5995   Entry.isSRet = true;
5996   Args.push_back(Entry);
5997
5998   Entry.Node = Arg;
5999   Entry.Ty = ArgTy;
6000   Entry.isSExt = false;
6001   Entry.isZExt = false;
6002   Args.push_back(Entry);
6003
6004   const char *LibcallName  = (ArgVT == MVT::f64)
6005   ? "__sincos_stret" : "__sincosf_stret";
6006   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6007
6008   TargetLowering::
6009   CallLoweringInfo CLI(DAG.getEntryNode(), Type::getVoidTy(*DAG.getContext()),
6010                        false, false, false, false, 0,
6011                        CallingConv::C, /*isTaillCall=*/false,
6012                        /*doesNotRet=*/false, /*isReturnValueUsed*/false,
6013                        Callee, Args, DAG, dl);
6014   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6015
6016   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6017                                 MachinePointerInfo(), false, false, false, 0);
6018
6019   // Address of cos field.
6020   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6021                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6022   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6023                                 MachinePointerInfo(), false, false, false, 0);
6024
6025   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6026   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6027                      LoadSin.getValue(0), LoadCos.getValue(0));
6028 }
6029
6030 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6031   // Monotonic load/store is legal for all targets
6032   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6033     return Op;
6034
6035   // Aquire/Release load/store is not legal for targets without a
6036   // dmb or equivalent available.
6037   return SDValue();
6038 }
6039
6040 static void
6041 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
6042                     SelectionDAG &DAG) {
6043   SDLoc dl(Node);
6044   assert (Node->getValueType(0) == MVT::i64 &&
6045           "Only know how to expand i64 atomics");
6046   AtomicSDNode *AN = cast<AtomicSDNode>(Node);
6047
6048   SmallVector<SDValue, 6> Ops;
6049   Ops.push_back(Node->getOperand(0)); // Chain
6050   Ops.push_back(Node->getOperand(1)); // Ptr
6051   for(unsigned i=2; i<Node->getNumOperands(); i++) {
6052     // Low part
6053     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6054                               Node->getOperand(i), DAG.getIntPtrConstant(0)));
6055     // High part
6056     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6057                               Node->getOperand(i), DAG.getIntPtrConstant(1)));
6058   }
6059   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6060   SDValue Result =
6061     DAG.getAtomic(Node->getOpcode(), dl, MVT::i64, Tys, Ops.data(), Ops.size(),
6062                   cast<MemSDNode>(Node)->getMemOperand(), AN->getOrdering(),
6063                   AN->getSynchScope());
6064   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
6065   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6066   Results.push_back(Result.getValue(2));
6067 }
6068
6069 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6070                                     SmallVectorImpl<SDValue> &Results,
6071                                     SelectionDAG &DAG,
6072                                     const ARMSubtarget *Subtarget) {
6073   SDLoc DL(N);
6074   SDValue Cycles32, OutChain;
6075
6076   if (Subtarget->hasPerfMon()) {
6077     // Under Power Management extensions, the cycle-count is:
6078     //    mrc p15, #0, <Rt>, c9, c13, #0
6079     SDValue Ops[] = { N->getOperand(0), // Chain
6080                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6081                       DAG.getConstant(15, MVT::i32),
6082                       DAG.getConstant(0, MVT::i32),
6083                       DAG.getConstant(9, MVT::i32),
6084                       DAG.getConstant(13, MVT::i32),
6085                       DAG.getConstant(0, MVT::i32)
6086     };
6087
6088     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6089                            DAG.getVTList(MVT::i32, MVT::Other), &Ops[0],
6090                            array_lengthof(Ops));
6091     OutChain = Cycles32.getValue(1);
6092   } else {
6093     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6094     // there are older ARM CPUs that have implementation-specific ways of
6095     // obtaining this information (FIXME!).
6096     Cycles32 = DAG.getConstant(0, MVT::i32);
6097     OutChain = DAG.getEntryNode();
6098   }
6099
6100
6101   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6102                                  Cycles32, DAG.getConstant(0, MVT::i32));
6103   Results.push_back(Cycles64);
6104   Results.push_back(OutChain);
6105 }
6106
6107 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6108   switch (Op.getOpcode()) {
6109   default: llvm_unreachable("Don't know how to custom lower this!");
6110   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6111   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6112   case ISD::GlobalAddress:
6113     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
6114       LowerGlobalAddressELF(Op, DAG);
6115   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6116   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6117   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6118   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6119   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6120   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6121   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6122   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6123   case ISD::SINT_TO_FP:
6124   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6125   case ISD::FP_TO_SINT:
6126   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6127   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6128   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6129   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6130   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6131   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6132   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6133   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6134                                                                Subtarget);
6135   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6136   case ISD::SHL:
6137   case ISD::SRL:
6138   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6139   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6140   case ISD::SRL_PARTS:
6141   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6142   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6143   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6144   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6145   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6146   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6147   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6148   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6149   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6150   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6151   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6152   case ISD::MUL:           return LowerMUL(Op, DAG);
6153   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6154   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6155   case ISD::ADDC:
6156   case ISD::ADDE:
6157   case ISD::SUBC:
6158   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6159   case ISD::ATOMIC_LOAD:
6160   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6161   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6162   case ISD::SDIVREM:
6163   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6164   }
6165 }
6166
6167 /// ReplaceNodeResults - Replace the results of node with an illegal result
6168 /// type with new values built out of custom code.
6169 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6170                                            SmallVectorImpl<SDValue>&Results,
6171                                            SelectionDAG &DAG) const {
6172   SDValue Res;
6173   switch (N->getOpcode()) {
6174   default:
6175     llvm_unreachable("Don't know how to custom expand this!");
6176   case ISD::BITCAST:
6177     Res = ExpandBITCAST(N, DAG);
6178     break;
6179   case ISD::SRL:
6180   case ISD::SRA:
6181     Res = Expand64BitShift(N, DAG, Subtarget);
6182     break;
6183   case ISD::READCYCLECOUNTER:
6184     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6185     return;
6186   case ISD::ATOMIC_STORE:
6187   case ISD::ATOMIC_LOAD:
6188   case ISD::ATOMIC_LOAD_ADD:
6189   case ISD::ATOMIC_LOAD_AND:
6190   case ISD::ATOMIC_LOAD_NAND:
6191   case ISD::ATOMIC_LOAD_OR:
6192   case ISD::ATOMIC_LOAD_SUB:
6193   case ISD::ATOMIC_LOAD_XOR:
6194   case ISD::ATOMIC_SWAP:
6195   case ISD::ATOMIC_CMP_SWAP:
6196   case ISD::ATOMIC_LOAD_MIN:
6197   case ISD::ATOMIC_LOAD_UMIN:
6198   case ISD::ATOMIC_LOAD_MAX:
6199   case ISD::ATOMIC_LOAD_UMAX:
6200     ReplaceATOMIC_OP_64(N, Results, DAG);
6201     return;
6202   }
6203   if (Res.getNode())
6204     Results.push_back(Res);
6205 }
6206
6207 //===----------------------------------------------------------------------===//
6208 //                           ARM Scheduler Hooks
6209 //===----------------------------------------------------------------------===//
6210
6211 MachineBasicBlock *
6212 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
6213                                      MachineBasicBlock *BB,
6214                                      unsigned Size) const {
6215   unsigned dest    = MI->getOperand(0).getReg();
6216   unsigned ptr     = MI->getOperand(1).getReg();
6217   unsigned oldval  = MI->getOperand(2).getReg();
6218   unsigned newval  = MI->getOperand(3).getReg();
6219   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6220   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(4).getImm());
6221   DebugLoc dl = MI->getDebugLoc();
6222   bool isThumb2 = Subtarget->isThumb2();
6223
6224   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6225   unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
6226     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6227     (const TargetRegisterClass*)&ARM::GPRRegClass);
6228
6229   if (isThumb2) {
6230     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6231     MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
6232     MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
6233   }
6234
6235   unsigned ldrOpc, strOpc;
6236   getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6237
6238   MachineFunction *MF = BB->getParent();
6239   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6240   MachineFunction::iterator It = BB;
6241   ++It; // insert the new blocks after the current block
6242
6243   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6244   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6245   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6246   MF->insert(It, loop1MBB);
6247   MF->insert(It, loop2MBB);
6248   MF->insert(It, exitMBB);
6249
6250   // Transfer the remainder of BB and its successor edges to exitMBB.
6251   exitMBB->splice(exitMBB->begin(), BB,
6252                   llvm::next(MachineBasicBlock::iterator(MI)),
6253                   BB->end());
6254   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6255
6256   //  thisMBB:
6257   //   ...
6258   //   fallthrough --> loop1MBB
6259   BB->addSuccessor(loop1MBB);
6260
6261   // loop1MBB:
6262   //   ldrex dest, [ptr]
6263   //   cmp dest, oldval
6264   //   bne exitMBB
6265   BB = loop1MBB;
6266   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6267   if (ldrOpc == ARM::t2LDREX)
6268     MIB.addImm(0);
6269   AddDefaultPred(MIB);
6270   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6271                  .addReg(dest).addReg(oldval));
6272   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6273     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6274   BB->addSuccessor(loop2MBB);
6275   BB->addSuccessor(exitMBB);
6276
6277   // loop2MBB:
6278   //   strex scratch, newval, [ptr]
6279   //   cmp scratch, #0
6280   //   bne loop1MBB
6281   BB = loop2MBB;
6282   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
6283   if (strOpc == ARM::t2STREX)
6284     MIB.addImm(0);
6285   AddDefaultPred(MIB);
6286   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6287                  .addReg(scratch).addImm(0));
6288   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6289     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6290   BB->addSuccessor(loop1MBB);
6291   BB->addSuccessor(exitMBB);
6292
6293   //  exitMBB:
6294   //   ...
6295   BB = exitMBB;
6296
6297   MI->eraseFromParent();   // The instruction is gone now.
6298
6299   return BB;
6300 }
6301
6302 MachineBasicBlock *
6303 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6304                                     unsigned Size, unsigned BinOpcode) const {
6305   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6306   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6307
6308   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6309   MachineFunction *MF = BB->getParent();
6310   MachineFunction::iterator It = BB;
6311   ++It;
6312
6313   unsigned dest = MI->getOperand(0).getReg();
6314   unsigned ptr = MI->getOperand(1).getReg();
6315   unsigned incr = MI->getOperand(2).getReg();
6316   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6317   DebugLoc dl = MI->getDebugLoc();
6318   bool isThumb2 = Subtarget->isThumb2();
6319
6320   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6321   if (isThumb2) {
6322     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6323     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6324     MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6325   }
6326
6327   unsigned ldrOpc, strOpc;
6328   getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6329
6330   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6331   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6332   MF->insert(It, loopMBB);
6333   MF->insert(It, exitMBB);
6334
6335   // Transfer the remainder of BB and its successor edges to exitMBB.
6336   exitMBB->splice(exitMBB->begin(), BB,
6337                   llvm::next(MachineBasicBlock::iterator(MI)),
6338                   BB->end());
6339   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6340
6341   const TargetRegisterClass *TRC = isThumb2 ?
6342     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6343     (const TargetRegisterClass*)&ARM::GPRRegClass;
6344   unsigned scratch = MRI.createVirtualRegister(TRC);
6345   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
6346
6347   //  thisMBB:
6348   //   ...
6349   //   fallthrough --> loopMBB
6350   BB->addSuccessor(loopMBB);
6351
6352   //  loopMBB:
6353   //   ldrex dest, ptr
6354   //   <binop> scratch2, dest, incr
6355   //   strex scratch, scratch2, ptr
6356   //   cmp scratch, #0
6357   //   bne- loopMBB
6358   //   fallthrough --> exitMBB
6359   BB = loopMBB;
6360   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6361   if (ldrOpc == ARM::t2LDREX)
6362     MIB.addImm(0);
6363   AddDefaultPred(MIB);
6364   if (BinOpcode) {
6365     // operand order needs to go the other way for NAND
6366     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
6367       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6368                      addReg(incr).addReg(dest)).addReg(0);
6369     else
6370       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6371                      addReg(dest).addReg(incr)).addReg(0);
6372   }
6373
6374   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6375   if (strOpc == ARM::t2STREX)
6376     MIB.addImm(0);
6377   AddDefaultPred(MIB);
6378   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6379                  .addReg(scratch).addImm(0));
6380   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6381     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6382
6383   BB->addSuccessor(loopMBB);
6384   BB->addSuccessor(exitMBB);
6385
6386   //  exitMBB:
6387   //   ...
6388   BB = exitMBB;
6389
6390   MI->eraseFromParent();   // The instruction is gone now.
6391
6392   return BB;
6393 }
6394
6395 MachineBasicBlock *
6396 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
6397                                           MachineBasicBlock *BB,
6398                                           unsigned Size,
6399                                           bool signExtend,
6400                                           ARMCC::CondCodes Cond) const {
6401   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6402
6403   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6404   MachineFunction *MF = BB->getParent();
6405   MachineFunction::iterator It = BB;
6406   ++It;
6407
6408   unsigned dest = MI->getOperand(0).getReg();
6409   unsigned ptr = MI->getOperand(1).getReg();
6410   unsigned incr = MI->getOperand(2).getReg();
6411   unsigned oldval = dest;
6412   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6413   DebugLoc dl = MI->getDebugLoc();
6414   bool isThumb2 = Subtarget->isThumb2();
6415
6416   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6417   if (isThumb2) {
6418     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6419     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6420     MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6421   }
6422
6423   unsigned ldrOpc, strOpc, extendOpc;
6424   getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6425   switch (Size) {
6426   default: llvm_unreachable("unsupported size for AtomicBinaryMinMax!");
6427   case 1:
6428     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
6429     break;
6430   case 2:
6431     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
6432     break;
6433   case 4:
6434     extendOpc = 0;
6435     break;
6436   }
6437
6438   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6439   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6440   MF->insert(It, loopMBB);
6441   MF->insert(It, exitMBB);
6442
6443   // Transfer the remainder of BB and its successor edges to exitMBB.
6444   exitMBB->splice(exitMBB->begin(), BB,
6445                   llvm::next(MachineBasicBlock::iterator(MI)),
6446                   BB->end());
6447   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6448
6449   const TargetRegisterClass *TRC = isThumb2 ?
6450     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6451     (const TargetRegisterClass*)&ARM::GPRRegClass;
6452   unsigned scratch = MRI.createVirtualRegister(TRC);
6453   unsigned scratch2 = MRI.createVirtualRegister(TRC);
6454
6455   //  thisMBB:
6456   //   ...
6457   //   fallthrough --> loopMBB
6458   BB->addSuccessor(loopMBB);
6459
6460   //  loopMBB:
6461   //   ldrex dest, ptr
6462   //   (sign extend dest, if required)
6463   //   cmp dest, incr
6464   //   cmov.cond scratch2, incr, dest
6465   //   strex scratch, scratch2, ptr
6466   //   cmp scratch, #0
6467   //   bne- loopMBB
6468   //   fallthrough --> exitMBB
6469   BB = loopMBB;
6470   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6471   if (ldrOpc == ARM::t2LDREX)
6472     MIB.addImm(0);
6473   AddDefaultPred(MIB);
6474
6475   // Sign extend the value, if necessary.
6476   if (signExtend && extendOpc) {
6477     oldval = MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass
6478                                                 : &ARM::GPRnopcRegClass);
6479     if (!isThumb2)
6480       MRI.constrainRegClass(dest, &ARM::GPRnopcRegClass);
6481     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
6482                      .addReg(dest)
6483                      .addImm(0));
6484   }
6485
6486   // Build compare and cmov instructions.
6487   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6488                  .addReg(oldval).addReg(incr));
6489   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
6490          .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
6491
6492   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6493   if (strOpc == ARM::t2STREX)
6494     MIB.addImm(0);
6495   AddDefaultPred(MIB);
6496   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6497                  .addReg(scratch).addImm(0));
6498   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6499     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6500
6501   BB->addSuccessor(loopMBB);
6502   BB->addSuccessor(exitMBB);
6503
6504   //  exitMBB:
6505   //   ...
6506   BB = exitMBB;
6507
6508   MI->eraseFromParent();   // The instruction is gone now.
6509
6510   return BB;
6511 }
6512
6513 MachineBasicBlock *
6514 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
6515                                       unsigned Op1, unsigned Op2,
6516                                       bool NeedsCarry, bool IsCmpxchg,
6517                                       bool IsMinMax, ARMCC::CondCodes CC) const {
6518   // This also handles ATOMIC_SWAP and ATOMIC_STORE, indicated by Op1==0.
6519   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6520
6521   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6522   MachineFunction *MF = BB->getParent();
6523   MachineFunction::iterator It = BB;
6524   ++It;
6525
6526   bool isStore = (MI->getOpcode() == ARM::ATOMIC_STORE_I64);
6527   unsigned offset = (isStore ? -2 : 0);
6528   unsigned destlo = MI->getOperand(0).getReg();
6529   unsigned desthi = MI->getOperand(1).getReg();
6530   unsigned ptr = MI->getOperand(offset+2).getReg();
6531   unsigned vallo = MI->getOperand(offset+3).getReg();
6532   unsigned valhi = MI->getOperand(offset+4).getReg();
6533   unsigned OrdIdx = offset + (IsCmpxchg ? 7 : 5);
6534   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(OrdIdx).getImm());
6535   DebugLoc dl = MI->getDebugLoc();
6536   bool isThumb2 = Subtarget->isThumb2();
6537
6538   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6539   if (isThumb2) {
6540     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6541     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6542     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6543     MRI.constrainRegClass(vallo, &ARM::rGPRRegClass);
6544     MRI.constrainRegClass(valhi, &ARM::rGPRRegClass);
6545   }
6546
6547   unsigned ldrOpc, strOpc;
6548   getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6549
6550   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6551   MachineBasicBlock *contBB = 0, *cont2BB = 0;
6552   if (IsCmpxchg || IsMinMax)
6553     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
6554   if (IsCmpxchg)
6555     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
6556   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6557
6558   MF->insert(It, loopMBB);
6559   if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6560   if (IsCmpxchg) MF->insert(It, cont2BB);
6561   MF->insert(It, exitMBB);
6562
6563   // Transfer the remainder of BB and its successor edges to exitMBB.
6564   exitMBB->splice(exitMBB->begin(), BB,
6565                   llvm::next(MachineBasicBlock::iterator(MI)),
6566                   BB->end());
6567   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6568
6569   const TargetRegisterClass *TRC = isThumb2 ?
6570     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6571     (const TargetRegisterClass*)&ARM::GPRRegClass;
6572   unsigned storesuccess = MRI.createVirtualRegister(TRC);
6573
6574   //  thisMBB:
6575   //   ...
6576   //   fallthrough --> loopMBB
6577   BB->addSuccessor(loopMBB);
6578
6579   //  loopMBB:
6580   //   ldrexd r2, r3, ptr
6581   //   <binopa> r0, r2, incr
6582   //   <binopb> r1, r3, incr
6583   //   strexd storesuccess, r0, r1, ptr
6584   //   cmp storesuccess, #0
6585   //   bne- loopMBB
6586   //   fallthrough --> exitMBB
6587   BB = loopMBB;
6588
6589   if (!isStore) {
6590     // Load
6591     if (isThumb2) {
6592       AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6593                      .addReg(destlo, RegState::Define)
6594                      .addReg(desthi, RegState::Define)
6595                      .addReg(ptr));
6596     } else {
6597       unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6598       AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6599                      .addReg(GPRPair0, RegState::Define).addReg(ptr));
6600       // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
6601       BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6602         .addReg(GPRPair0, 0, ARM::gsub_0);
6603       BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6604         .addReg(GPRPair0, 0, ARM::gsub_1);
6605     }
6606   }
6607
6608   unsigned StoreLo, StoreHi;
6609   if (IsCmpxchg) {
6610     // Add early exit
6611     for (unsigned i = 0; i < 2; i++) {
6612       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6613                                                          ARM::CMPrr))
6614                      .addReg(i == 0 ? destlo : desthi)
6615                      .addReg(i == 0 ? vallo : valhi));
6616       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6617         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6618       BB->addSuccessor(exitMBB);
6619       BB->addSuccessor(i == 0 ? contBB : cont2BB);
6620       BB = (i == 0 ? contBB : cont2BB);
6621     }
6622
6623     // Copy to physregs for strexd
6624     StoreLo = MI->getOperand(5).getReg();
6625     StoreHi = MI->getOperand(6).getReg();
6626   } else if (Op1) {
6627     // Perform binary operation
6628     unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6629     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6630                    .addReg(destlo).addReg(vallo))
6631         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6632     unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6633     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6634                    .addReg(desthi).addReg(valhi))
6635         .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6636
6637     StoreLo = tmpRegLo;
6638     StoreHi = tmpRegHi;
6639   } else {
6640     // Copy to physregs for strexd
6641     StoreLo = vallo;
6642     StoreHi = valhi;
6643   }
6644   if (IsMinMax) {
6645     // Compare and branch to exit block.
6646     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6647       .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6648     BB->addSuccessor(exitMBB);
6649     BB->addSuccessor(contBB);
6650     BB = contBB;
6651     StoreLo = vallo;
6652     StoreHi = valhi;
6653   }
6654
6655   // Store
6656   if (isThumb2) {
6657     MRI.constrainRegClass(StoreLo, &ARM::rGPRRegClass);
6658     MRI.constrainRegClass(StoreHi, &ARM::rGPRRegClass);
6659     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6660                    .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6661   } else {
6662     // Marshal a pair...
6663     unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6664     unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6665     unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6666     BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6667     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6668       .addReg(UndefPair)
6669       .addReg(StoreLo)
6670       .addImm(ARM::gsub_0);
6671     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6672       .addReg(r1)
6673       .addReg(StoreHi)
6674       .addImm(ARM::gsub_1);
6675
6676     // ...and store it
6677     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6678                    .addReg(StorePair).addReg(ptr));
6679   }
6680   // Cmp+jump
6681   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6682                  .addReg(storesuccess).addImm(0));
6683   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6684     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6685
6686   BB->addSuccessor(loopMBB);
6687   BB->addSuccessor(exitMBB);
6688
6689   //  exitMBB:
6690   //   ...
6691   BB = exitMBB;
6692
6693   MI->eraseFromParent();   // The instruction is gone now.
6694
6695   return BB;
6696 }
6697
6698 MachineBasicBlock *
6699 ARMTargetLowering::EmitAtomicLoad64(MachineInstr *MI, MachineBasicBlock *BB) const {
6700
6701   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6702
6703   unsigned destlo = MI->getOperand(0).getReg();
6704   unsigned desthi = MI->getOperand(1).getReg();
6705   unsigned ptr = MI->getOperand(2).getReg();
6706   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6707   DebugLoc dl = MI->getDebugLoc();
6708   bool isThumb2 = Subtarget->isThumb2();
6709
6710   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6711   if (isThumb2) {
6712     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6713     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6714     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6715   }
6716   unsigned ldrOpc, strOpc;
6717   getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6718
6719   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(ldrOpc));
6720
6721   if (isThumb2) {
6722     MIB.addReg(destlo, RegState::Define)
6723        .addReg(desthi, RegState::Define)
6724        .addReg(ptr);
6725
6726   } else {
6727     unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6728     MIB.addReg(GPRPair0, RegState::Define).addReg(ptr);
6729
6730     // Copy GPRPair0 into dest.  (This copy will normally be coalesced.)
6731     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), destlo)
6732       .addReg(GPRPair0, 0, ARM::gsub_0);
6733     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), desthi)
6734       .addReg(GPRPair0, 0, ARM::gsub_1);
6735   }
6736   AddDefaultPred(MIB);
6737
6738   MI->eraseFromParent();   // The instruction is gone now.
6739
6740   return BB;
6741 }
6742
6743 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6744 /// registers the function context.
6745 void ARMTargetLowering::
6746 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6747                        MachineBasicBlock *DispatchBB, int FI) const {
6748   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6749   DebugLoc dl = MI->getDebugLoc();
6750   MachineFunction *MF = MBB->getParent();
6751   MachineRegisterInfo *MRI = &MF->getRegInfo();
6752   MachineConstantPool *MCP = MF->getConstantPool();
6753   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6754   const Function *F = MF->getFunction();
6755
6756   bool isThumb = Subtarget->isThumb();
6757   bool isThumb2 = Subtarget->isThumb2();
6758
6759   unsigned PCLabelId = AFI->createPICLabelUId();
6760   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6761   ARMConstantPoolValue *CPV =
6762     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6763   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6764
6765   const TargetRegisterClass *TRC = isThumb ?
6766     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6767     (const TargetRegisterClass*)&ARM::GPRRegClass;
6768
6769   // Grab constant pool and fixed stack memory operands.
6770   MachineMemOperand *CPMMO =
6771     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6772                              MachineMemOperand::MOLoad, 4, 4);
6773
6774   MachineMemOperand *FIMMOSt =
6775     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6776                              MachineMemOperand::MOStore, 4, 4);
6777
6778   // Load the address of the dispatch MBB into the jump buffer.
6779   if (isThumb2) {
6780     // Incoming value: jbuf
6781     //   ldr.n  r5, LCPI1_1
6782     //   orr    r5, r5, #1
6783     //   add    r5, pc
6784     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6785     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6786     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6787                    .addConstantPoolIndex(CPI)
6788                    .addMemOperand(CPMMO));
6789     // Set the low bit because of thumb mode.
6790     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6791     AddDefaultCC(
6792       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6793                      .addReg(NewVReg1, RegState::Kill)
6794                      .addImm(0x01)));
6795     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6796     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6797       .addReg(NewVReg2, RegState::Kill)
6798       .addImm(PCLabelId);
6799     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6800                    .addReg(NewVReg3, RegState::Kill)
6801                    .addFrameIndex(FI)
6802                    .addImm(36)  // &jbuf[1] :: pc
6803                    .addMemOperand(FIMMOSt));
6804   } else if (isThumb) {
6805     // Incoming value: jbuf
6806     //   ldr.n  r1, LCPI1_4
6807     //   add    r1, pc
6808     //   mov    r2, #1
6809     //   orrs   r1, r2
6810     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6811     //   str    r1, [r2]
6812     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6813     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6814                    .addConstantPoolIndex(CPI)
6815                    .addMemOperand(CPMMO));
6816     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6817     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6818       .addReg(NewVReg1, RegState::Kill)
6819       .addImm(PCLabelId);
6820     // Set the low bit because of thumb mode.
6821     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6822     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6823                    .addReg(ARM::CPSR, RegState::Define)
6824                    .addImm(1));
6825     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6826     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6827                    .addReg(ARM::CPSR, RegState::Define)
6828                    .addReg(NewVReg2, RegState::Kill)
6829                    .addReg(NewVReg3, RegState::Kill));
6830     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6831     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6832                    .addFrameIndex(FI)
6833                    .addImm(36)); // &jbuf[1] :: pc
6834     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6835                    .addReg(NewVReg4, RegState::Kill)
6836                    .addReg(NewVReg5, RegState::Kill)
6837                    .addImm(0)
6838                    .addMemOperand(FIMMOSt));
6839   } else {
6840     // Incoming value: jbuf
6841     //   ldr  r1, LCPI1_1
6842     //   add  r1, pc, r1
6843     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6844     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6845     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6846                    .addConstantPoolIndex(CPI)
6847                    .addImm(0)
6848                    .addMemOperand(CPMMO));
6849     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6850     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6851                    .addReg(NewVReg1, RegState::Kill)
6852                    .addImm(PCLabelId));
6853     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6854                    .addReg(NewVReg2, RegState::Kill)
6855                    .addFrameIndex(FI)
6856                    .addImm(36)  // &jbuf[1] :: pc
6857                    .addMemOperand(FIMMOSt));
6858   }
6859 }
6860
6861 MachineBasicBlock *ARMTargetLowering::
6862 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6863   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6864   DebugLoc dl = MI->getDebugLoc();
6865   MachineFunction *MF = MBB->getParent();
6866   MachineRegisterInfo *MRI = &MF->getRegInfo();
6867   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6868   MachineFrameInfo *MFI = MF->getFrameInfo();
6869   int FI = MFI->getFunctionContextIndex();
6870
6871   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6872     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6873     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6874
6875   // Get a mapping of the call site numbers to all of the landing pads they're
6876   // associated with.
6877   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6878   unsigned MaxCSNum = 0;
6879   MachineModuleInfo &MMI = MF->getMMI();
6880   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6881        ++BB) {
6882     if (!BB->isLandingPad()) continue;
6883
6884     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6885     // pad.
6886     for (MachineBasicBlock::iterator
6887            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6888       if (!II->isEHLabel()) continue;
6889
6890       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6891       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6892
6893       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6894       for (SmallVectorImpl<unsigned>::iterator
6895              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6896            CSI != CSE; ++CSI) {
6897         CallSiteNumToLPad[*CSI].push_back(BB);
6898         MaxCSNum = std::max(MaxCSNum, *CSI);
6899       }
6900       break;
6901     }
6902   }
6903
6904   // Get an ordered list of the machine basic blocks for the jump table.
6905   std::vector<MachineBasicBlock*> LPadList;
6906   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6907   LPadList.reserve(CallSiteNumToLPad.size());
6908   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6909     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6910     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6911            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6912       LPadList.push_back(*II);
6913       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6914     }
6915   }
6916
6917   assert(!LPadList.empty() &&
6918          "No landing pad destinations for the dispatch jump table!");
6919
6920   // Create the jump table and associated information.
6921   MachineJumpTableInfo *JTI =
6922     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6923   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6924   unsigned UId = AFI->createJumpTableUId();
6925   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6926
6927   // Create the MBBs for the dispatch code.
6928
6929   // Shove the dispatch's address into the return slot in the function context.
6930   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6931   DispatchBB->setIsLandingPad();
6932
6933   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6934   unsigned trap_opcode;
6935   if (Subtarget->isThumb())
6936     trap_opcode = ARM::tTRAP;
6937   else
6938     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6939
6940   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6941   DispatchBB->addSuccessor(TrapBB);
6942
6943   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6944   DispatchBB->addSuccessor(DispContBB);
6945
6946   // Insert and MBBs.
6947   MF->insert(MF->end(), DispatchBB);
6948   MF->insert(MF->end(), DispContBB);
6949   MF->insert(MF->end(), TrapBB);
6950
6951   // Insert code into the entry block that creates and registers the function
6952   // context.
6953   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6954
6955   MachineMemOperand *FIMMOLd =
6956     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6957                              MachineMemOperand::MOLoad |
6958                              MachineMemOperand::MOVolatile, 4, 4);
6959
6960   MachineInstrBuilder MIB;
6961   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6962
6963   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6964   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6965
6966   // Add a register mask with no preserved registers.  This results in all
6967   // registers being marked as clobbered.
6968   MIB.addRegMask(RI.getNoPreservedMask());
6969
6970   unsigned NumLPads = LPadList.size();
6971   if (Subtarget->isThumb2()) {
6972     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6973     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6974                    .addFrameIndex(FI)
6975                    .addImm(4)
6976                    .addMemOperand(FIMMOLd));
6977
6978     if (NumLPads < 256) {
6979       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6980                      .addReg(NewVReg1)
6981                      .addImm(LPadList.size()));
6982     } else {
6983       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6984       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6985                      .addImm(NumLPads & 0xFFFF));
6986
6987       unsigned VReg2 = VReg1;
6988       if ((NumLPads & 0xFFFF0000) != 0) {
6989         VReg2 = MRI->createVirtualRegister(TRC);
6990         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6991                        .addReg(VReg1)
6992                        .addImm(NumLPads >> 16));
6993       }
6994
6995       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6996                      .addReg(NewVReg1)
6997                      .addReg(VReg2));
6998     }
6999
7000     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7001       .addMBB(TrapBB)
7002       .addImm(ARMCC::HI)
7003       .addReg(ARM::CPSR);
7004
7005     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7006     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7007                    .addJumpTableIndex(MJTI)
7008                    .addImm(UId));
7009
7010     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7011     AddDefaultCC(
7012       AddDefaultPred(
7013         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7014         .addReg(NewVReg3, RegState::Kill)
7015         .addReg(NewVReg1)
7016         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7017
7018     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7019       .addReg(NewVReg4, RegState::Kill)
7020       .addReg(NewVReg1)
7021       .addJumpTableIndex(MJTI)
7022       .addImm(UId);
7023   } else if (Subtarget->isThumb()) {
7024     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7025     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7026                    .addFrameIndex(FI)
7027                    .addImm(1)
7028                    .addMemOperand(FIMMOLd));
7029
7030     if (NumLPads < 256) {
7031       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7032                      .addReg(NewVReg1)
7033                      .addImm(NumLPads));
7034     } else {
7035       MachineConstantPool *ConstantPool = MF->getConstantPool();
7036       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7037       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7038
7039       // MachineConstantPool wants an explicit alignment.
7040       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7041       if (Align == 0)
7042         Align = getDataLayout()->getTypeAllocSize(C->getType());
7043       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7044
7045       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7046       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7047                      .addReg(VReg1, RegState::Define)
7048                      .addConstantPoolIndex(Idx));
7049       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7050                      .addReg(NewVReg1)
7051                      .addReg(VReg1));
7052     }
7053
7054     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7055       .addMBB(TrapBB)
7056       .addImm(ARMCC::HI)
7057       .addReg(ARM::CPSR);
7058
7059     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7060     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7061                    .addReg(ARM::CPSR, RegState::Define)
7062                    .addReg(NewVReg1)
7063                    .addImm(2));
7064
7065     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7066     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7067                    .addJumpTableIndex(MJTI)
7068                    .addImm(UId));
7069
7070     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7071     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7072                    .addReg(ARM::CPSR, RegState::Define)
7073                    .addReg(NewVReg2, RegState::Kill)
7074                    .addReg(NewVReg3));
7075
7076     MachineMemOperand *JTMMOLd =
7077       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7078                                MachineMemOperand::MOLoad, 4, 4);
7079
7080     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7081     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7082                    .addReg(NewVReg4, RegState::Kill)
7083                    .addImm(0)
7084                    .addMemOperand(JTMMOLd));
7085
7086     unsigned NewVReg6 = NewVReg5;
7087     if (RelocM == Reloc::PIC_) {
7088       NewVReg6 = MRI->createVirtualRegister(TRC);
7089       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7090                      .addReg(ARM::CPSR, RegState::Define)
7091                      .addReg(NewVReg5, RegState::Kill)
7092                      .addReg(NewVReg3));
7093     }
7094
7095     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7096       .addReg(NewVReg6, RegState::Kill)
7097       .addJumpTableIndex(MJTI)
7098       .addImm(UId);
7099   } else {
7100     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7101     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7102                    .addFrameIndex(FI)
7103                    .addImm(4)
7104                    .addMemOperand(FIMMOLd));
7105
7106     if (NumLPads < 256) {
7107       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7108                      .addReg(NewVReg1)
7109                      .addImm(NumLPads));
7110     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7111       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7112       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7113                      .addImm(NumLPads & 0xFFFF));
7114
7115       unsigned VReg2 = VReg1;
7116       if ((NumLPads & 0xFFFF0000) != 0) {
7117         VReg2 = MRI->createVirtualRegister(TRC);
7118         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7119                        .addReg(VReg1)
7120                        .addImm(NumLPads >> 16));
7121       }
7122
7123       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7124                      .addReg(NewVReg1)
7125                      .addReg(VReg2));
7126     } else {
7127       MachineConstantPool *ConstantPool = MF->getConstantPool();
7128       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7129       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7130
7131       // MachineConstantPool wants an explicit alignment.
7132       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7133       if (Align == 0)
7134         Align = getDataLayout()->getTypeAllocSize(C->getType());
7135       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7136
7137       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7138       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7139                      .addReg(VReg1, RegState::Define)
7140                      .addConstantPoolIndex(Idx)
7141                      .addImm(0));
7142       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7143                      .addReg(NewVReg1)
7144                      .addReg(VReg1, RegState::Kill));
7145     }
7146
7147     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7148       .addMBB(TrapBB)
7149       .addImm(ARMCC::HI)
7150       .addReg(ARM::CPSR);
7151
7152     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7153     AddDefaultCC(
7154       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7155                      .addReg(NewVReg1)
7156                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7157     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7158     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7159                    .addJumpTableIndex(MJTI)
7160                    .addImm(UId));
7161
7162     MachineMemOperand *JTMMOLd =
7163       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7164                                MachineMemOperand::MOLoad, 4, 4);
7165     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7166     AddDefaultPred(
7167       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7168       .addReg(NewVReg3, RegState::Kill)
7169       .addReg(NewVReg4)
7170       .addImm(0)
7171       .addMemOperand(JTMMOLd));
7172
7173     if (RelocM == Reloc::PIC_) {
7174       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7175         .addReg(NewVReg5, RegState::Kill)
7176         .addReg(NewVReg4)
7177         .addJumpTableIndex(MJTI)
7178         .addImm(UId);
7179     } else {
7180       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7181         .addReg(NewVReg5, RegState::Kill)
7182         .addJumpTableIndex(MJTI)
7183         .addImm(UId);
7184     }
7185   }
7186
7187   // Add the jump table entries as successors to the MBB.
7188   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7189   for (std::vector<MachineBasicBlock*>::iterator
7190          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7191     MachineBasicBlock *CurMBB = *I;
7192     if (SeenMBBs.insert(CurMBB))
7193       DispContBB->addSuccessor(CurMBB);
7194   }
7195
7196   // N.B. the order the invoke BBs are processed in doesn't matter here.
7197   const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
7198   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7199   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
7200          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
7201     MachineBasicBlock *BB = *I;
7202
7203     // Remove the landing pad successor from the invoke block and replace it
7204     // with the new dispatch block.
7205     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7206                                                   BB->succ_end());
7207     while (!Successors.empty()) {
7208       MachineBasicBlock *SMBB = Successors.pop_back_val();
7209       if (SMBB->isLandingPad()) {
7210         BB->removeSuccessor(SMBB);
7211         MBBLPads.push_back(SMBB);
7212       }
7213     }
7214
7215     BB->addSuccessor(DispatchBB);
7216
7217     // Find the invoke call and mark all of the callee-saved registers as
7218     // 'implicit defined' so that they're spilled. This prevents code from
7219     // moving instructions to before the EH block, where they will never be
7220     // executed.
7221     for (MachineBasicBlock::reverse_iterator
7222            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7223       if (!II->isCall()) continue;
7224
7225       DenseMap<unsigned, bool> DefRegs;
7226       for (MachineInstr::mop_iterator
7227              OI = II->operands_begin(), OE = II->operands_end();
7228            OI != OE; ++OI) {
7229         if (!OI->isReg()) continue;
7230         DefRegs[OI->getReg()] = true;
7231       }
7232
7233       MachineInstrBuilder MIB(*MF, &*II);
7234
7235       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7236         unsigned Reg = SavedRegs[i];
7237         if (Subtarget->isThumb2() &&
7238             !ARM::tGPRRegClass.contains(Reg) &&
7239             !ARM::hGPRRegClass.contains(Reg))
7240           continue;
7241         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7242           continue;
7243         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7244           continue;
7245         if (!DefRegs[Reg])
7246           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7247       }
7248
7249       break;
7250     }
7251   }
7252
7253   // Mark all former landing pads as non-landing pads. The dispatch is the only
7254   // landing pad now.
7255   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7256          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7257     (*I)->setIsLandingPad(false);
7258
7259   // The instruction is gone now.
7260   MI->eraseFromParent();
7261
7262   return MBB;
7263 }
7264
7265 static
7266 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7267   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7268        E = MBB->succ_end(); I != E; ++I)
7269     if (*I != Succ)
7270       return *I;
7271   llvm_unreachable("Expecting a BB with two successors!");
7272 }
7273
7274 /// Return the load opcode for a given load size. If load size >= 8,
7275 /// neon opcode will be returned.
7276 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7277   if (LdSize >= 8)
7278     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7279                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7280   if (IsThumb1)
7281     return LdSize == 4 ? ARM::tLDRi
7282                        : LdSize == 2 ? ARM::tLDRHi
7283                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7284   if (IsThumb2)
7285     return LdSize == 4 ? ARM::t2LDR_POST
7286                        : LdSize == 2 ? ARM::t2LDRH_POST
7287                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7288   return LdSize == 4 ? ARM::LDR_POST_IMM
7289                      : LdSize == 2 ? ARM::LDRH_POST
7290                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7291 }
7292
7293 /// Return the store opcode for a given store size. If store size >= 8,
7294 /// neon opcode will be returned.
7295 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7296   if (StSize >= 8)
7297     return StSize == 16 ? ARM::VST1q32wb_fixed
7298                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7299   if (IsThumb1)
7300     return StSize == 4 ? ARM::tSTRi
7301                        : StSize == 2 ? ARM::tSTRHi
7302                                      : StSize == 1 ? ARM::tSTRBi : 0;
7303   if (IsThumb2)
7304     return StSize == 4 ? ARM::t2STR_POST
7305                        : StSize == 2 ? ARM::t2STRH_POST
7306                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7307   return StSize == 4 ? ARM::STR_POST_IMM
7308                      : StSize == 2 ? ARM::STRH_POST
7309                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7310 }
7311
7312 /// Emit a post-increment load operation with given size. The instructions
7313 /// will be added to BB at Pos.
7314 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7315                        const TargetInstrInfo *TII, DebugLoc dl,
7316                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7317                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7318   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7319   assert(LdOpc != 0 && "Should have a load opcode");
7320   if (LdSize >= 8) {
7321     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7322                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7323                        .addImm(0));
7324   } else if (IsThumb1) {
7325     // load + update AddrIn
7326     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7327                        .addReg(AddrIn).addImm(0));
7328     MachineInstrBuilder MIB =
7329         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7330     MIB = AddDefaultT1CC(MIB);
7331     MIB.addReg(AddrIn).addImm(LdSize);
7332     AddDefaultPred(MIB);
7333   } else if (IsThumb2) {
7334     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7335                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7336                        .addImm(LdSize));
7337   } else { // arm
7338     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7339                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7340                        .addReg(0).addImm(LdSize));
7341   }
7342 }
7343
7344 /// Emit a post-increment store operation with given size. The instructions
7345 /// will be added to BB at Pos.
7346 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7347                        const TargetInstrInfo *TII, DebugLoc dl,
7348                        unsigned StSize, unsigned Data, unsigned AddrIn,
7349                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7350   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7351   assert(StOpc != 0 && "Should have a store opcode");
7352   if (StSize >= 8) {
7353     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7354                        .addReg(AddrIn).addImm(0).addReg(Data));
7355   } else if (IsThumb1) {
7356     // store + update AddrIn
7357     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7358                        .addReg(AddrIn).addImm(0));
7359     MachineInstrBuilder MIB =
7360         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7361     MIB = AddDefaultT1CC(MIB);
7362     MIB.addReg(AddrIn).addImm(StSize);
7363     AddDefaultPred(MIB);
7364   } else if (IsThumb2) {
7365     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7366                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7367   } else { // arm
7368     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7369                        .addReg(Data).addReg(AddrIn).addReg(0)
7370                        .addImm(StSize));
7371   }
7372 }
7373
7374 MachineBasicBlock *
7375 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7376                                    MachineBasicBlock *BB) const {
7377   // This pseudo instruction has 3 operands: dst, src, size
7378   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7379   // Otherwise, we will generate unrolled scalar copies.
7380   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7381   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7382   MachineFunction::iterator It = BB;
7383   ++It;
7384
7385   unsigned dest = MI->getOperand(0).getReg();
7386   unsigned src = MI->getOperand(1).getReg();
7387   unsigned SizeVal = MI->getOperand(2).getImm();
7388   unsigned Align = MI->getOperand(3).getImm();
7389   DebugLoc dl = MI->getDebugLoc();
7390
7391   MachineFunction *MF = BB->getParent();
7392   MachineRegisterInfo &MRI = MF->getRegInfo();
7393   unsigned UnitSize = 0;
7394   const TargetRegisterClass *TRC = 0;
7395   const TargetRegisterClass *VecTRC = 0;
7396
7397   bool IsThumb1 = Subtarget->isThumb1Only();
7398   bool IsThumb2 = Subtarget->isThumb2();
7399
7400   if (Align & 1) {
7401     UnitSize = 1;
7402   } else if (Align & 2) {
7403     UnitSize = 2;
7404   } else {
7405     // Check whether we can use NEON instructions.
7406     if (!MF->getFunction()->getAttributes().
7407           hasAttribute(AttributeSet::FunctionIndex,
7408                        Attribute::NoImplicitFloat) &&
7409         Subtarget->hasNEON()) {
7410       if ((Align % 16 == 0) && SizeVal >= 16)
7411         UnitSize = 16;
7412       else if ((Align % 8 == 0) && SizeVal >= 8)
7413         UnitSize = 8;
7414     }
7415     // Can't use NEON instructions.
7416     if (UnitSize == 0)
7417       UnitSize = 4;
7418   }
7419
7420   // Select the correct opcode and register class for unit size load/store
7421   bool IsNeon = UnitSize >= 8;
7422   TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
7423                                : (const TargetRegisterClass *)&ARM::GPRRegClass;
7424   if (IsNeon)
7425     VecTRC = UnitSize == 16
7426                  ? (const TargetRegisterClass *)&ARM::DPairRegClass
7427                  : UnitSize == 8
7428                        ? (const TargetRegisterClass *)&ARM::DPRRegClass
7429                        : 0;
7430
7431   unsigned BytesLeft = SizeVal % UnitSize;
7432   unsigned LoopSize = SizeVal - BytesLeft;
7433
7434   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7435     // Use LDR and STR to copy.
7436     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7437     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7438     unsigned srcIn = src;
7439     unsigned destIn = dest;
7440     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7441       unsigned srcOut = MRI.createVirtualRegister(TRC);
7442       unsigned destOut = MRI.createVirtualRegister(TRC);
7443       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7444       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7445                  IsThumb1, IsThumb2);
7446       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7447                  IsThumb1, IsThumb2);
7448       srcIn = srcOut;
7449       destIn = destOut;
7450     }
7451
7452     // Handle the leftover bytes with LDRB and STRB.
7453     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7454     // [destOut] = STRB_POST(scratch, destIn, 1)
7455     for (unsigned i = 0; i < BytesLeft; i++) {
7456       unsigned srcOut = MRI.createVirtualRegister(TRC);
7457       unsigned destOut = MRI.createVirtualRegister(TRC);
7458       unsigned scratch = MRI.createVirtualRegister(TRC);
7459       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7460                  IsThumb1, IsThumb2);
7461       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7462                  IsThumb1, IsThumb2);
7463       srcIn = srcOut;
7464       destIn = destOut;
7465     }
7466     MI->eraseFromParent();   // The instruction is gone now.
7467     return BB;
7468   }
7469
7470   // Expand the pseudo op to a loop.
7471   // thisMBB:
7472   //   ...
7473   //   movw varEnd, # --> with thumb2
7474   //   movt varEnd, #
7475   //   ldrcp varEnd, idx --> without thumb2
7476   //   fallthrough --> loopMBB
7477   // loopMBB:
7478   //   PHI varPhi, varEnd, varLoop
7479   //   PHI srcPhi, src, srcLoop
7480   //   PHI destPhi, dst, destLoop
7481   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7482   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7483   //   subs varLoop, varPhi, #UnitSize
7484   //   bne loopMBB
7485   //   fallthrough --> exitMBB
7486   // exitMBB:
7487   //   epilogue to handle left-over bytes
7488   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7489   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7490   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7491   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7492   MF->insert(It, loopMBB);
7493   MF->insert(It, exitMBB);
7494
7495   // Transfer the remainder of BB and its successor edges to exitMBB.
7496   exitMBB->splice(exitMBB->begin(), BB,
7497                   llvm::next(MachineBasicBlock::iterator(MI)),
7498                   BB->end());
7499   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7500
7501   // Load an immediate to varEnd.
7502   unsigned varEnd = MRI.createVirtualRegister(TRC);
7503   if (IsThumb2) {
7504     unsigned Vtmp = varEnd;
7505     if ((LoopSize & 0xFFFF0000) != 0)
7506       Vtmp = MRI.createVirtualRegister(TRC);
7507     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7508                        .addImm(LoopSize & 0xFFFF));
7509
7510     if ((LoopSize & 0xFFFF0000) != 0)
7511       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7512                          .addReg(Vtmp).addImm(LoopSize >> 16));
7513   } else {
7514     MachineConstantPool *ConstantPool = MF->getConstantPool();
7515     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7516     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7517
7518     // MachineConstantPool wants an explicit alignment.
7519     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7520     if (Align == 0)
7521       Align = getDataLayout()->getTypeAllocSize(C->getType());
7522     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7523
7524     if (IsThumb1)
7525       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7526           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7527     else
7528       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7529           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7530   }
7531   BB->addSuccessor(loopMBB);
7532
7533   // Generate the loop body:
7534   //   varPhi = PHI(varLoop, varEnd)
7535   //   srcPhi = PHI(srcLoop, src)
7536   //   destPhi = PHI(destLoop, dst)
7537   MachineBasicBlock *entryBB = BB;
7538   BB = loopMBB;
7539   unsigned varLoop = MRI.createVirtualRegister(TRC);
7540   unsigned varPhi = MRI.createVirtualRegister(TRC);
7541   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7542   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7543   unsigned destLoop = MRI.createVirtualRegister(TRC);
7544   unsigned destPhi = MRI.createVirtualRegister(TRC);
7545
7546   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7547     .addReg(varLoop).addMBB(loopMBB)
7548     .addReg(varEnd).addMBB(entryBB);
7549   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7550     .addReg(srcLoop).addMBB(loopMBB)
7551     .addReg(src).addMBB(entryBB);
7552   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7553     .addReg(destLoop).addMBB(loopMBB)
7554     .addReg(dest).addMBB(entryBB);
7555
7556   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7557   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7558   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7559   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7560              IsThumb1, IsThumb2);
7561   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7562              IsThumb1, IsThumb2);
7563
7564   // Decrement loop variable by UnitSize.
7565   if (IsThumb1) {
7566     MachineInstrBuilder MIB =
7567         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7568     MIB = AddDefaultT1CC(MIB);
7569     MIB.addReg(varPhi).addImm(UnitSize);
7570     AddDefaultPred(MIB);
7571   } else {
7572     MachineInstrBuilder MIB =
7573         BuildMI(*BB, BB->end(), dl,
7574                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7575     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7576     MIB->getOperand(5).setReg(ARM::CPSR);
7577     MIB->getOperand(5).setIsDef(true);
7578   }
7579   BuildMI(*BB, BB->end(), dl,
7580           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7581       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7582
7583   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7584   BB->addSuccessor(loopMBB);
7585   BB->addSuccessor(exitMBB);
7586
7587   // Add epilogue to handle BytesLeft.
7588   BB = exitMBB;
7589   MachineInstr *StartOfExit = exitMBB->begin();
7590
7591   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7592   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7593   unsigned srcIn = srcLoop;
7594   unsigned destIn = destLoop;
7595   for (unsigned i = 0; i < BytesLeft; i++) {
7596     unsigned srcOut = MRI.createVirtualRegister(TRC);
7597     unsigned destOut = MRI.createVirtualRegister(TRC);
7598     unsigned scratch = MRI.createVirtualRegister(TRC);
7599     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7600                IsThumb1, IsThumb2);
7601     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7602                IsThumb1, IsThumb2);
7603     srcIn = srcOut;
7604     destIn = destOut;
7605   }
7606
7607   MI->eraseFromParent();   // The instruction is gone now.
7608   return BB;
7609 }
7610
7611 MachineBasicBlock *
7612 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7613                                                MachineBasicBlock *BB) const {
7614   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7615   DebugLoc dl = MI->getDebugLoc();
7616   bool isThumb2 = Subtarget->isThumb2();
7617   switch (MI->getOpcode()) {
7618   default: {
7619     MI->dump();
7620     llvm_unreachable("Unexpected instr type to insert");
7621   }
7622   // The Thumb2 pre-indexed stores have the same MI operands, they just
7623   // define them differently in the .td files from the isel patterns, so
7624   // they need pseudos.
7625   case ARM::t2STR_preidx:
7626     MI->setDesc(TII->get(ARM::t2STR_PRE));
7627     return BB;
7628   case ARM::t2STRB_preidx:
7629     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7630     return BB;
7631   case ARM::t2STRH_preidx:
7632     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7633     return BB;
7634
7635   case ARM::STRi_preidx:
7636   case ARM::STRBi_preidx: {
7637     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7638       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7639     // Decode the offset.
7640     unsigned Offset = MI->getOperand(4).getImm();
7641     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7642     Offset = ARM_AM::getAM2Offset(Offset);
7643     if (isSub)
7644       Offset = -Offset;
7645
7646     MachineMemOperand *MMO = *MI->memoperands_begin();
7647     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7648       .addOperand(MI->getOperand(0))  // Rn_wb
7649       .addOperand(MI->getOperand(1))  // Rt
7650       .addOperand(MI->getOperand(2))  // Rn
7651       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7652       .addOperand(MI->getOperand(5))  // pred
7653       .addOperand(MI->getOperand(6))
7654       .addMemOperand(MMO);
7655     MI->eraseFromParent();
7656     return BB;
7657   }
7658   case ARM::STRr_preidx:
7659   case ARM::STRBr_preidx:
7660   case ARM::STRH_preidx: {
7661     unsigned NewOpc;
7662     switch (MI->getOpcode()) {
7663     default: llvm_unreachable("unexpected opcode!");
7664     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7665     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7666     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7667     }
7668     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7669     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7670       MIB.addOperand(MI->getOperand(i));
7671     MI->eraseFromParent();
7672     return BB;
7673   }
7674   case ARM::ATOMIC_LOAD_ADD_I8:
7675      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7676   case ARM::ATOMIC_LOAD_ADD_I16:
7677      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7678   case ARM::ATOMIC_LOAD_ADD_I32:
7679      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7680
7681   case ARM::ATOMIC_LOAD_AND_I8:
7682      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7683   case ARM::ATOMIC_LOAD_AND_I16:
7684      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7685   case ARM::ATOMIC_LOAD_AND_I32:
7686      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7687
7688   case ARM::ATOMIC_LOAD_OR_I8:
7689      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7690   case ARM::ATOMIC_LOAD_OR_I16:
7691      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7692   case ARM::ATOMIC_LOAD_OR_I32:
7693      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7694
7695   case ARM::ATOMIC_LOAD_XOR_I8:
7696      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7697   case ARM::ATOMIC_LOAD_XOR_I16:
7698      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7699   case ARM::ATOMIC_LOAD_XOR_I32:
7700      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7701
7702   case ARM::ATOMIC_LOAD_NAND_I8:
7703      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7704   case ARM::ATOMIC_LOAD_NAND_I16:
7705      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7706   case ARM::ATOMIC_LOAD_NAND_I32:
7707      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7708
7709   case ARM::ATOMIC_LOAD_SUB_I8:
7710      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7711   case ARM::ATOMIC_LOAD_SUB_I16:
7712      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7713   case ARM::ATOMIC_LOAD_SUB_I32:
7714      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7715
7716   case ARM::ATOMIC_LOAD_MIN_I8:
7717      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7718   case ARM::ATOMIC_LOAD_MIN_I16:
7719      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7720   case ARM::ATOMIC_LOAD_MIN_I32:
7721      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7722
7723   case ARM::ATOMIC_LOAD_MAX_I8:
7724      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7725   case ARM::ATOMIC_LOAD_MAX_I16:
7726      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7727   case ARM::ATOMIC_LOAD_MAX_I32:
7728      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7729
7730   case ARM::ATOMIC_LOAD_UMIN_I8:
7731      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7732   case ARM::ATOMIC_LOAD_UMIN_I16:
7733      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7734   case ARM::ATOMIC_LOAD_UMIN_I32:
7735      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7736
7737   case ARM::ATOMIC_LOAD_UMAX_I8:
7738      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7739   case ARM::ATOMIC_LOAD_UMAX_I16:
7740      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7741   case ARM::ATOMIC_LOAD_UMAX_I32:
7742      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7743
7744   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
7745   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7746   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7747
7748   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
7749   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7750   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7751
7752   case ARM::ATOMIC_LOAD_I64:
7753     return EmitAtomicLoad64(MI, BB);
7754
7755   case ARM::ATOMIC_LOAD_ADD_I64:
7756     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7757                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7758                               /*NeedsCarry*/ true);
7759   case ARM::ATOMIC_LOAD_SUB_I64:
7760     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7761                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7762                               /*NeedsCarry*/ true);
7763   case ARM::ATOMIC_LOAD_OR_I64:
7764     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7765                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7766   case ARM::ATOMIC_LOAD_XOR_I64:
7767     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7768                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7769   case ARM::ATOMIC_LOAD_AND_I64:
7770     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7771                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7772   case ARM::ATOMIC_STORE_I64:
7773   case ARM::ATOMIC_SWAP_I64:
7774     return EmitAtomicBinary64(MI, BB, 0, 0, false);
7775   case ARM::ATOMIC_CMP_SWAP_I64:
7776     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7777                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7778                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7779   case ARM::ATOMIC_LOAD_MIN_I64:
7780     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7781                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7782                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7783                               /*IsMinMax*/ true, ARMCC::LT);
7784   case ARM::ATOMIC_LOAD_MAX_I64:
7785     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7786                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7787                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7788                               /*IsMinMax*/ true, ARMCC::GE);
7789   case ARM::ATOMIC_LOAD_UMIN_I64:
7790     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7791                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7792                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7793                               /*IsMinMax*/ true, ARMCC::LO);
7794   case ARM::ATOMIC_LOAD_UMAX_I64:
7795     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7796                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7797                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7798                               /*IsMinMax*/ true, ARMCC::HS);
7799
7800   case ARM::tMOVCCr_pseudo: {
7801     // To "insert" a SELECT_CC instruction, we actually have to insert the
7802     // diamond control-flow pattern.  The incoming instruction knows the
7803     // destination vreg to set, the condition code register to branch on, the
7804     // true/false values to select between, and a branch opcode to use.
7805     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7806     MachineFunction::iterator It = BB;
7807     ++It;
7808
7809     //  thisMBB:
7810     //  ...
7811     //   TrueVal = ...
7812     //   cmpTY ccX, r1, r2
7813     //   bCC copy1MBB
7814     //   fallthrough --> copy0MBB
7815     MachineBasicBlock *thisMBB  = BB;
7816     MachineFunction *F = BB->getParent();
7817     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7818     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7819     F->insert(It, copy0MBB);
7820     F->insert(It, sinkMBB);
7821
7822     // Transfer the remainder of BB and its successor edges to sinkMBB.
7823     sinkMBB->splice(sinkMBB->begin(), BB,
7824                     llvm::next(MachineBasicBlock::iterator(MI)),
7825                     BB->end());
7826     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7827
7828     BB->addSuccessor(copy0MBB);
7829     BB->addSuccessor(sinkMBB);
7830
7831     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7832       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7833
7834     //  copy0MBB:
7835     //   %FalseValue = ...
7836     //   # fallthrough to sinkMBB
7837     BB = copy0MBB;
7838
7839     // Update machine-CFG edges
7840     BB->addSuccessor(sinkMBB);
7841
7842     //  sinkMBB:
7843     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7844     //  ...
7845     BB = sinkMBB;
7846     BuildMI(*BB, BB->begin(), dl,
7847             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7848       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7849       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7850
7851     MI->eraseFromParent();   // The pseudo instruction is gone now.
7852     return BB;
7853   }
7854
7855   case ARM::BCCi64:
7856   case ARM::BCCZi64: {
7857     // If there is an unconditional branch to the other successor, remove it.
7858     BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
7859
7860     // Compare both parts that make up the double comparison separately for
7861     // equality.
7862     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7863
7864     unsigned LHS1 = MI->getOperand(1).getReg();
7865     unsigned LHS2 = MI->getOperand(2).getReg();
7866     if (RHSisZero) {
7867       AddDefaultPred(BuildMI(BB, dl,
7868                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7869                      .addReg(LHS1).addImm(0));
7870       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7871         .addReg(LHS2).addImm(0)
7872         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7873     } else {
7874       unsigned RHS1 = MI->getOperand(3).getReg();
7875       unsigned RHS2 = MI->getOperand(4).getReg();
7876       AddDefaultPred(BuildMI(BB, dl,
7877                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7878                      .addReg(LHS1).addReg(RHS1));
7879       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7880         .addReg(LHS2).addReg(RHS2)
7881         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7882     }
7883
7884     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7885     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7886     if (MI->getOperand(0).getImm() == ARMCC::NE)
7887       std::swap(destMBB, exitMBB);
7888
7889     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7890       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7891     if (isThumb2)
7892       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7893     else
7894       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7895
7896     MI->eraseFromParent();   // The pseudo instruction is gone now.
7897     return BB;
7898   }
7899
7900   case ARM::Int_eh_sjlj_setjmp:
7901   case ARM::Int_eh_sjlj_setjmp_nofp:
7902   case ARM::tInt_eh_sjlj_setjmp:
7903   case ARM::t2Int_eh_sjlj_setjmp:
7904   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7905     EmitSjLjDispatchBlock(MI, BB);
7906     return BB;
7907
7908   case ARM::ABS:
7909   case ARM::t2ABS: {
7910     // To insert an ABS instruction, we have to insert the
7911     // diamond control-flow pattern.  The incoming instruction knows the
7912     // source vreg to test against 0, the destination vreg to set,
7913     // the condition code register to branch on, the
7914     // true/false values to select between, and a branch opcode to use.
7915     // It transforms
7916     //     V1 = ABS V0
7917     // into
7918     //     V2 = MOVS V0
7919     //     BCC                      (branch to SinkBB if V0 >= 0)
7920     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7921     //     SinkBB: V1 = PHI(V2, V3)
7922     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7923     MachineFunction::iterator BBI = BB;
7924     ++BBI;
7925     MachineFunction *Fn = BB->getParent();
7926     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7927     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7928     Fn->insert(BBI, RSBBB);
7929     Fn->insert(BBI, SinkBB);
7930
7931     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7932     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7933     bool isThumb2 = Subtarget->isThumb2();
7934     MachineRegisterInfo &MRI = Fn->getRegInfo();
7935     // In Thumb mode S must not be specified if source register is the SP or
7936     // PC and if destination register is the SP, so restrict register class
7937     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7938       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7939       (const TargetRegisterClass*)&ARM::GPRRegClass);
7940
7941     // Transfer the remainder of BB and its successor edges to sinkMBB.
7942     SinkBB->splice(SinkBB->begin(), BB,
7943       llvm::next(MachineBasicBlock::iterator(MI)),
7944       BB->end());
7945     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7946
7947     BB->addSuccessor(RSBBB);
7948     BB->addSuccessor(SinkBB);
7949
7950     // fall through to SinkMBB
7951     RSBBB->addSuccessor(SinkBB);
7952
7953     // insert a cmp at the end of BB
7954     AddDefaultPred(BuildMI(BB, dl,
7955                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7956                    .addReg(ABSSrcReg).addImm(0));
7957
7958     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7959     BuildMI(BB, dl,
7960       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7961       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7962
7963     // insert rsbri in RSBBB
7964     // Note: BCC and rsbri will be converted into predicated rsbmi
7965     // by if-conversion pass
7966     BuildMI(*RSBBB, RSBBB->begin(), dl,
7967       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7968       .addReg(ABSSrcReg, RegState::Kill)
7969       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7970
7971     // insert PHI in SinkBB,
7972     // reuse ABSDstReg to not change uses of ABS instruction
7973     BuildMI(*SinkBB, SinkBB->begin(), dl,
7974       TII->get(ARM::PHI), ABSDstReg)
7975       .addReg(NewRsbDstReg).addMBB(RSBBB)
7976       .addReg(ABSSrcReg).addMBB(BB);
7977
7978     // remove ABS instruction
7979     MI->eraseFromParent();
7980
7981     // return last added BB
7982     return SinkBB;
7983   }
7984   case ARM::COPY_STRUCT_BYVAL_I32:
7985     ++NumLoopByVals;
7986     return EmitStructByval(MI, BB);
7987   }
7988 }
7989
7990 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7991                                                       SDNode *Node) const {
7992   if (!MI->hasPostISelHook()) {
7993     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7994            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7995     return;
7996   }
7997
7998   const MCInstrDesc *MCID = &MI->getDesc();
7999   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
8000   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
8001   // operand is still set to noreg. If needed, set the optional operand's
8002   // register to CPSR, and remove the redundant implicit def.
8003   //
8004   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
8005
8006   // Rename pseudo opcodes.
8007   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
8008   if (NewOpc) {
8009     const ARMBaseInstrInfo *TII =
8010       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
8011     MCID = &TII->get(NewOpc);
8012
8013     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
8014            "converted opcode should be the same except for cc_out");
8015
8016     MI->setDesc(*MCID);
8017
8018     // Add the optional cc_out operand
8019     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
8020   }
8021   unsigned ccOutIdx = MCID->getNumOperands() - 1;
8022
8023   // Any ARM instruction that sets the 's' bit should specify an optional
8024   // "cc_out" operand in the last operand position.
8025   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
8026     assert(!NewOpc && "Optional cc_out operand required");
8027     return;
8028   }
8029   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8030   // since we already have an optional CPSR def.
8031   bool definesCPSR = false;
8032   bool deadCPSR = false;
8033   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
8034        i != e; ++i) {
8035     const MachineOperand &MO = MI->getOperand(i);
8036     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8037       definesCPSR = true;
8038       if (MO.isDead())
8039         deadCPSR = true;
8040       MI->RemoveOperand(i);
8041       break;
8042     }
8043   }
8044   if (!definesCPSR) {
8045     assert(!NewOpc && "Optional cc_out operand required");
8046     return;
8047   }
8048   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8049   if (deadCPSR) {
8050     assert(!MI->getOperand(ccOutIdx).getReg() &&
8051            "expect uninitialized optional cc_out operand");
8052     return;
8053   }
8054
8055   // If this instruction was defined with an optional CPSR def and its dag node
8056   // had a live implicit CPSR def, then activate the optional CPSR def.
8057   MachineOperand &MO = MI->getOperand(ccOutIdx);
8058   MO.setReg(ARM::CPSR);
8059   MO.setIsDef(true);
8060 }
8061
8062 //===----------------------------------------------------------------------===//
8063 //                           ARM Optimization Hooks
8064 //===----------------------------------------------------------------------===//
8065
8066 // Helper function that checks if N is a null or all ones constant.
8067 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8068   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8069   if (!C)
8070     return false;
8071   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8072 }
8073
8074 // Return true if N is conditionally 0 or all ones.
8075 // Detects these expressions where cc is an i1 value:
8076 //
8077 //   (select cc 0, y)   [AllOnes=0]
8078 //   (select cc y, 0)   [AllOnes=0]
8079 //   (zext cc)          [AllOnes=0]
8080 //   (sext cc)          [AllOnes=0/1]
8081 //   (select cc -1, y)  [AllOnes=1]
8082 //   (select cc y, -1)  [AllOnes=1]
8083 //
8084 // Invert is set when N is the null/all ones constant when CC is false.
8085 // OtherOp is set to the alternative value of N.
8086 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8087                                        SDValue &CC, bool &Invert,
8088                                        SDValue &OtherOp,
8089                                        SelectionDAG &DAG) {
8090   switch (N->getOpcode()) {
8091   default: return false;
8092   case ISD::SELECT: {
8093     CC = N->getOperand(0);
8094     SDValue N1 = N->getOperand(1);
8095     SDValue N2 = N->getOperand(2);
8096     if (isZeroOrAllOnes(N1, AllOnes)) {
8097       Invert = false;
8098       OtherOp = N2;
8099       return true;
8100     }
8101     if (isZeroOrAllOnes(N2, AllOnes)) {
8102       Invert = true;
8103       OtherOp = N1;
8104       return true;
8105     }
8106     return false;
8107   }
8108   case ISD::ZERO_EXTEND:
8109     // (zext cc) can never be the all ones value.
8110     if (AllOnes)
8111       return false;
8112     // Fall through.
8113   case ISD::SIGN_EXTEND: {
8114     EVT VT = N->getValueType(0);
8115     CC = N->getOperand(0);
8116     if (CC.getValueType() != MVT::i1)
8117       return false;
8118     Invert = !AllOnes;
8119     if (AllOnes)
8120       // When looking for an AllOnes constant, N is an sext, and the 'other'
8121       // value is 0.
8122       OtherOp = DAG.getConstant(0, VT);
8123     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8124       // When looking for a 0 constant, N can be zext or sext.
8125       OtherOp = DAG.getConstant(1, VT);
8126     else
8127       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
8128     return true;
8129   }
8130   }
8131 }
8132
8133 // Combine a constant select operand into its use:
8134 //
8135 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
8136 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
8137 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
8138 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
8139 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
8140 //
8141 // The transform is rejected if the select doesn't have a constant operand that
8142 // is null, or all ones when AllOnes is set.
8143 //
8144 // Also recognize sext/zext from i1:
8145 //
8146 //   (add (zext cc), x) -> (select cc (add x, 1), x)
8147 //   (add (sext cc), x) -> (select cc (add x, -1), x)
8148 //
8149 // These transformations eventually create predicated instructions.
8150 //
8151 // @param N       The node to transform.
8152 // @param Slct    The N operand that is a select.
8153 // @param OtherOp The other N operand (x above).
8154 // @param DCI     Context.
8155 // @param AllOnes Require the select constant to be all ones instead of null.
8156 // @returns The new node, or SDValue() on failure.
8157 static
8158 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8159                             TargetLowering::DAGCombinerInfo &DCI,
8160                             bool AllOnes = false) {
8161   SelectionDAG &DAG = DCI.DAG;
8162   EVT VT = N->getValueType(0);
8163   SDValue NonConstantVal;
8164   SDValue CCOp;
8165   bool SwapSelectOps;
8166   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8167                                   NonConstantVal, DAG))
8168     return SDValue();
8169
8170   // Slct is now know to be the desired identity constant when CC is true.
8171   SDValue TrueVal = OtherOp;
8172   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8173                                  OtherOp, NonConstantVal);
8174   // Unless SwapSelectOps says CC should be false.
8175   if (SwapSelectOps)
8176     std::swap(TrueVal, FalseVal);
8177
8178   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8179                      CCOp, TrueVal, FalseVal);
8180 }
8181
8182 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8183 static
8184 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8185                                        TargetLowering::DAGCombinerInfo &DCI) {
8186   SDValue N0 = N->getOperand(0);
8187   SDValue N1 = N->getOperand(1);
8188   if (N0.getNode()->hasOneUse()) {
8189     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8190     if (Result.getNode())
8191       return Result;
8192   }
8193   if (N1.getNode()->hasOneUse()) {
8194     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8195     if (Result.getNode())
8196       return Result;
8197   }
8198   return SDValue();
8199 }
8200
8201 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8202 // (only after legalization).
8203 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8204                                  TargetLowering::DAGCombinerInfo &DCI,
8205                                  const ARMSubtarget *Subtarget) {
8206
8207   // Only perform optimization if after legalize, and if NEON is available. We
8208   // also expected both operands to be BUILD_VECTORs.
8209   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8210       || N0.getOpcode() != ISD::BUILD_VECTOR
8211       || N1.getOpcode() != ISD::BUILD_VECTOR)
8212     return SDValue();
8213
8214   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8215   EVT VT = N->getValueType(0);
8216   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8217     return SDValue();
8218
8219   // Check that the vector operands are of the right form.
8220   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8221   // operands, where N is the size of the formed vector.
8222   // Each EXTRACT_VECTOR should have the same input vector and odd or even
8223   // index such that we have a pair wise add pattern.
8224
8225   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8226   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8227     return SDValue();
8228   SDValue Vec = N0->getOperand(0)->getOperand(0);
8229   SDNode *V = Vec.getNode();
8230   unsigned nextIndex = 0;
8231
8232   // For each operands to the ADD which are BUILD_VECTORs,
8233   // check to see if each of their operands are an EXTRACT_VECTOR with
8234   // the same vector and appropriate index.
8235   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8236     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8237         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8238
8239       SDValue ExtVec0 = N0->getOperand(i);
8240       SDValue ExtVec1 = N1->getOperand(i);
8241
8242       // First operand is the vector, verify its the same.
8243       if (V != ExtVec0->getOperand(0).getNode() ||
8244           V != ExtVec1->getOperand(0).getNode())
8245         return SDValue();
8246
8247       // Second is the constant, verify its correct.
8248       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8249       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8250
8251       // For the constant, we want to see all the even or all the odd.
8252       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8253           || C1->getZExtValue() != nextIndex+1)
8254         return SDValue();
8255
8256       // Increment index.
8257       nextIndex+=2;
8258     } else
8259       return SDValue();
8260   }
8261
8262   // Create VPADDL node.
8263   SelectionDAG &DAG = DCI.DAG;
8264   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8265
8266   // Build operand list.
8267   SmallVector<SDValue, 8> Ops;
8268   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
8269                                 TLI.getPointerTy()));
8270
8271   // Input is the vector.
8272   Ops.push_back(Vec);
8273
8274   // Get widened type and narrowed type.
8275   MVT widenType;
8276   unsigned numElem = VT.getVectorNumElements();
8277   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8278     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8279     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8280     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8281     default:
8282       llvm_unreachable("Invalid vector element type for padd optimization.");
8283   }
8284
8285   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
8286                             widenType, &Ops[0], Ops.size());
8287   return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, tmp);
8288 }
8289
8290 static SDValue findMUL_LOHI(SDValue V) {
8291   if (V->getOpcode() == ISD::UMUL_LOHI ||
8292       V->getOpcode() == ISD::SMUL_LOHI)
8293     return V;
8294   return SDValue();
8295 }
8296
8297 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8298                                      TargetLowering::DAGCombinerInfo &DCI,
8299                                      const ARMSubtarget *Subtarget) {
8300
8301   if (Subtarget->isThumb1Only()) return SDValue();
8302
8303   // Only perform the checks after legalize when the pattern is available.
8304   if (DCI.isBeforeLegalize()) return SDValue();
8305
8306   // Look for multiply add opportunities.
8307   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8308   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8309   // a glue link from the first add to the second add.
8310   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8311   // a S/UMLAL instruction.
8312   //          loAdd   UMUL_LOHI
8313   //            \    / :lo    \ :hi
8314   //             \  /          \          [no multiline comment]
8315   //              ADDC         |  hiAdd
8316   //                 \ :glue  /  /
8317   //                  \      /  /
8318   //                    ADDE
8319   //
8320   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8321   SDValue AddcOp0 = AddcNode->getOperand(0);
8322   SDValue AddcOp1 = AddcNode->getOperand(1);
8323
8324   // Check if the two operands are from the same mul_lohi node.
8325   if (AddcOp0.getNode() == AddcOp1.getNode())
8326     return SDValue();
8327
8328   assert(AddcNode->getNumValues() == 2 &&
8329          AddcNode->getValueType(0) == MVT::i32 &&
8330          "Expect ADDC with two result values. First: i32");
8331
8332   // Check that we have a glued ADDC node.
8333   if (AddcNode->getValueType(1) != MVT::Glue)
8334     return SDValue();
8335
8336   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8337   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8338       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8339       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8340       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8341     return SDValue();
8342
8343   // Look for the glued ADDE.
8344   SDNode* AddeNode = AddcNode->getGluedUser();
8345   if (AddeNode == NULL)
8346     return SDValue();
8347
8348   // Make sure it is really an ADDE.
8349   if (AddeNode->getOpcode() != ISD::ADDE)
8350     return SDValue();
8351
8352   assert(AddeNode->getNumOperands() == 3 &&
8353          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8354          "ADDE node has the wrong inputs");
8355
8356   // Check for the triangle shape.
8357   SDValue AddeOp0 = AddeNode->getOperand(0);
8358   SDValue AddeOp1 = AddeNode->getOperand(1);
8359
8360   // Make sure that the ADDE operands are not coming from the same node.
8361   if (AddeOp0.getNode() == AddeOp1.getNode())
8362     return SDValue();
8363
8364   // Find the MUL_LOHI node walking up ADDE's operands.
8365   bool IsLeftOperandMUL = false;
8366   SDValue MULOp = findMUL_LOHI(AddeOp0);
8367   if (MULOp == SDValue())
8368    MULOp = findMUL_LOHI(AddeOp1);
8369   else
8370     IsLeftOperandMUL = true;
8371   if (MULOp == SDValue())
8372      return SDValue();
8373
8374   // Figure out the right opcode.
8375   unsigned Opc = MULOp->getOpcode();
8376   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8377
8378   // Figure out the high and low input values to the MLAL node.
8379   SDValue* HiMul = &MULOp;
8380   SDValue* HiAdd = NULL;
8381   SDValue* LoMul = NULL;
8382   SDValue* LowAdd = NULL;
8383
8384   if (IsLeftOperandMUL)
8385     HiAdd = &AddeOp1;
8386   else
8387     HiAdd = &AddeOp0;
8388
8389
8390   if (AddcOp0->getOpcode() == Opc) {
8391     LoMul = &AddcOp0;
8392     LowAdd = &AddcOp1;
8393   }
8394   if (AddcOp1->getOpcode() == Opc) {
8395     LoMul = &AddcOp1;
8396     LowAdd = &AddcOp0;
8397   }
8398
8399   if (LoMul == NULL)
8400     return SDValue();
8401
8402   if (LoMul->getNode() != HiMul->getNode())
8403     return SDValue();
8404
8405   // Create the merged node.
8406   SelectionDAG &DAG = DCI.DAG;
8407
8408   // Build operand list.
8409   SmallVector<SDValue, 8> Ops;
8410   Ops.push_back(LoMul->getOperand(0));
8411   Ops.push_back(LoMul->getOperand(1));
8412   Ops.push_back(*LowAdd);
8413   Ops.push_back(*HiAdd);
8414
8415   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8416                                  DAG.getVTList(MVT::i32, MVT::i32),
8417                                  &Ops[0], Ops.size());
8418
8419   // Replace the ADDs' nodes uses by the MLA node's values.
8420   SDValue HiMLALResult(MLALNode.getNode(), 1);
8421   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8422
8423   SDValue LoMLALResult(MLALNode.getNode(), 0);
8424   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8425
8426   // Return original node to notify the driver to stop replacing.
8427   SDValue resNode(AddcNode, 0);
8428   return resNode;
8429 }
8430
8431 /// PerformADDCCombine - Target-specific dag combine transform from
8432 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8433 static SDValue PerformADDCCombine(SDNode *N,
8434                                  TargetLowering::DAGCombinerInfo &DCI,
8435                                  const ARMSubtarget *Subtarget) {
8436
8437   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8438
8439 }
8440
8441 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8442 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8443 /// called with the default operands, and if that fails, with commuted
8444 /// operands.
8445 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8446                                           TargetLowering::DAGCombinerInfo &DCI,
8447                                           const ARMSubtarget *Subtarget){
8448
8449   // Attempt to create vpaddl for this add.
8450   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8451   if (Result.getNode())
8452     return Result;
8453
8454   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8455   if (N0.getNode()->hasOneUse()) {
8456     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8457     if (Result.getNode()) return Result;
8458   }
8459   return SDValue();
8460 }
8461
8462 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8463 ///
8464 static SDValue PerformADDCombine(SDNode *N,
8465                                  TargetLowering::DAGCombinerInfo &DCI,
8466                                  const ARMSubtarget *Subtarget) {
8467   SDValue N0 = N->getOperand(0);
8468   SDValue N1 = N->getOperand(1);
8469
8470   // First try with the default operand order.
8471   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8472   if (Result.getNode())
8473     return Result;
8474
8475   // If that didn't work, try again with the operands commuted.
8476   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8477 }
8478
8479 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8480 ///
8481 static SDValue PerformSUBCombine(SDNode *N,
8482                                  TargetLowering::DAGCombinerInfo &DCI) {
8483   SDValue N0 = N->getOperand(0);
8484   SDValue N1 = N->getOperand(1);
8485
8486   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8487   if (N1.getNode()->hasOneUse()) {
8488     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8489     if (Result.getNode()) return Result;
8490   }
8491
8492   return SDValue();
8493 }
8494
8495 /// PerformVMULCombine
8496 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8497 /// special multiplier accumulator forwarding.
8498 ///   vmul d3, d0, d2
8499 ///   vmla d3, d1, d2
8500 /// is faster than
8501 ///   vadd d3, d0, d1
8502 ///   vmul d3, d3, d2
8503 //  However, for (A + B) * (A + B),
8504 //    vadd d2, d0, d1
8505 //    vmul d3, d0, d2
8506 //    vmla d3, d1, d2
8507 //  is slower than
8508 //    vadd d2, d0, d1
8509 //    vmul d3, d2, d2
8510 static SDValue PerformVMULCombine(SDNode *N,
8511                                   TargetLowering::DAGCombinerInfo &DCI,
8512                                   const ARMSubtarget *Subtarget) {
8513   if (!Subtarget->hasVMLxForwarding())
8514     return SDValue();
8515
8516   SelectionDAG &DAG = DCI.DAG;
8517   SDValue N0 = N->getOperand(0);
8518   SDValue N1 = N->getOperand(1);
8519   unsigned Opcode = N0.getOpcode();
8520   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8521       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8522     Opcode = N1.getOpcode();
8523     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8524         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8525       return SDValue();
8526     std::swap(N0, N1);
8527   }
8528
8529   if (N0 == N1)
8530     return SDValue();
8531
8532   EVT VT = N->getValueType(0);
8533   SDLoc DL(N);
8534   SDValue N00 = N0->getOperand(0);
8535   SDValue N01 = N0->getOperand(1);
8536   return DAG.getNode(Opcode, DL, VT,
8537                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8538                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8539 }
8540
8541 static SDValue PerformMULCombine(SDNode *N,
8542                                  TargetLowering::DAGCombinerInfo &DCI,
8543                                  const ARMSubtarget *Subtarget) {
8544   SelectionDAG &DAG = DCI.DAG;
8545
8546   if (Subtarget->isThumb1Only())
8547     return SDValue();
8548
8549   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8550     return SDValue();
8551
8552   EVT VT = N->getValueType(0);
8553   if (VT.is64BitVector() || VT.is128BitVector())
8554     return PerformVMULCombine(N, DCI, Subtarget);
8555   if (VT != MVT::i32)
8556     return SDValue();
8557
8558   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8559   if (!C)
8560     return SDValue();
8561
8562   int64_t MulAmt = C->getSExtValue();
8563   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8564
8565   ShiftAmt = ShiftAmt & (32 - 1);
8566   SDValue V = N->getOperand(0);
8567   SDLoc DL(N);
8568
8569   SDValue Res;
8570   MulAmt >>= ShiftAmt;
8571
8572   if (MulAmt >= 0) {
8573     if (isPowerOf2_32(MulAmt - 1)) {
8574       // (mul x, 2^N + 1) => (add (shl x, N), x)
8575       Res = DAG.getNode(ISD::ADD, DL, VT,
8576                         V,
8577                         DAG.getNode(ISD::SHL, DL, VT,
8578                                     V,
8579                                     DAG.getConstant(Log2_32(MulAmt - 1),
8580                                                     MVT::i32)));
8581     } else if (isPowerOf2_32(MulAmt + 1)) {
8582       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8583       Res = DAG.getNode(ISD::SUB, DL, VT,
8584                         DAG.getNode(ISD::SHL, DL, VT,
8585                                     V,
8586                                     DAG.getConstant(Log2_32(MulAmt + 1),
8587                                                     MVT::i32)),
8588                         V);
8589     } else
8590       return SDValue();
8591   } else {
8592     uint64_t MulAmtAbs = -MulAmt;
8593     if (isPowerOf2_32(MulAmtAbs + 1)) {
8594       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8595       Res = DAG.getNode(ISD::SUB, DL, VT,
8596                         V,
8597                         DAG.getNode(ISD::SHL, DL, VT,
8598                                     V,
8599                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8600                                                     MVT::i32)));
8601     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8602       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8603       Res = DAG.getNode(ISD::ADD, DL, VT,
8604                         V,
8605                         DAG.getNode(ISD::SHL, DL, VT,
8606                                     V,
8607                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8608                                                     MVT::i32)));
8609       Res = DAG.getNode(ISD::SUB, DL, VT,
8610                         DAG.getConstant(0, MVT::i32),Res);
8611
8612     } else
8613       return SDValue();
8614   }
8615
8616   if (ShiftAmt != 0)
8617     Res = DAG.getNode(ISD::SHL, DL, VT,
8618                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8619
8620   // Do not add new nodes to DAG combiner worklist.
8621   DCI.CombineTo(N, Res, false);
8622   return SDValue();
8623 }
8624
8625 static SDValue PerformANDCombine(SDNode *N,
8626                                  TargetLowering::DAGCombinerInfo &DCI,
8627                                  const ARMSubtarget *Subtarget) {
8628
8629   // Attempt to use immediate-form VBIC
8630   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8631   SDLoc dl(N);
8632   EVT VT = N->getValueType(0);
8633   SelectionDAG &DAG = DCI.DAG;
8634
8635   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8636     return SDValue();
8637
8638   APInt SplatBits, SplatUndef;
8639   unsigned SplatBitSize;
8640   bool HasAnyUndefs;
8641   if (BVN &&
8642       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8643     if (SplatBitSize <= 64) {
8644       EVT VbicVT;
8645       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8646                                       SplatUndef.getZExtValue(), SplatBitSize,
8647                                       DAG, VbicVT, VT.is128BitVector(),
8648                                       OtherModImm);
8649       if (Val.getNode()) {
8650         SDValue Input =
8651           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8652         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8653         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8654       }
8655     }
8656   }
8657
8658   if (!Subtarget->isThumb1Only()) {
8659     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8660     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8661     if (Result.getNode())
8662       return Result;
8663   }
8664
8665   return SDValue();
8666 }
8667
8668 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8669 static SDValue PerformORCombine(SDNode *N,
8670                                 TargetLowering::DAGCombinerInfo &DCI,
8671                                 const ARMSubtarget *Subtarget) {
8672   // Attempt to use immediate-form VORR
8673   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8674   SDLoc dl(N);
8675   EVT VT = N->getValueType(0);
8676   SelectionDAG &DAG = DCI.DAG;
8677
8678   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8679     return SDValue();
8680
8681   APInt SplatBits, SplatUndef;
8682   unsigned SplatBitSize;
8683   bool HasAnyUndefs;
8684   if (BVN && Subtarget->hasNEON() &&
8685       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8686     if (SplatBitSize <= 64) {
8687       EVT VorrVT;
8688       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8689                                       SplatUndef.getZExtValue(), SplatBitSize,
8690                                       DAG, VorrVT, VT.is128BitVector(),
8691                                       OtherModImm);
8692       if (Val.getNode()) {
8693         SDValue Input =
8694           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8695         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8696         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8697       }
8698     }
8699   }
8700
8701   if (!Subtarget->isThumb1Only()) {
8702     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8703     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8704     if (Result.getNode())
8705       return Result;
8706   }
8707
8708   // The code below optimizes (or (and X, Y), Z).
8709   // The AND operand needs to have a single user to make these optimizations
8710   // profitable.
8711   SDValue N0 = N->getOperand(0);
8712   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8713     return SDValue();
8714   SDValue N1 = N->getOperand(1);
8715
8716   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8717   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8718       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8719     APInt SplatUndef;
8720     unsigned SplatBitSize;
8721     bool HasAnyUndefs;
8722
8723     APInt SplatBits0, SplatBits1;
8724     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8725     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8726     // Ensure that the second operand of both ands are constants
8727     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8728                                       HasAnyUndefs) && !HasAnyUndefs) {
8729         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8730                                           HasAnyUndefs) && !HasAnyUndefs) {
8731             // Ensure that the bit width of the constants are the same and that
8732             // the splat arguments are logical inverses as per the pattern we
8733             // are trying to simplify.
8734             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8735                 SplatBits0 == ~SplatBits1) {
8736                 // Canonicalize the vector type to make instruction selection
8737                 // simpler.
8738                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8739                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8740                                              N0->getOperand(1),
8741                                              N0->getOperand(0),
8742                                              N1->getOperand(0));
8743                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8744             }
8745         }
8746     }
8747   }
8748
8749   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8750   // reasonable.
8751
8752   // BFI is only available on V6T2+
8753   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8754     return SDValue();
8755
8756   SDLoc DL(N);
8757   // 1) or (and A, mask), val => ARMbfi A, val, mask
8758   //      iff (val & mask) == val
8759   //
8760   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8761   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8762   //          && mask == ~mask2
8763   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8764   //          && ~mask == mask2
8765   //  (i.e., copy a bitfield value into another bitfield of the same width)
8766
8767   if (VT != MVT::i32)
8768     return SDValue();
8769
8770   SDValue N00 = N0.getOperand(0);
8771
8772   // The value and the mask need to be constants so we can verify this is
8773   // actually a bitfield set. If the mask is 0xffff, we can do better
8774   // via a movt instruction, so don't use BFI in that case.
8775   SDValue MaskOp = N0.getOperand(1);
8776   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8777   if (!MaskC)
8778     return SDValue();
8779   unsigned Mask = MaskC->getZExtValue();
8780   if (Mask == 0xffff)
8781     return SDValue();
8782   SDValue Res;
8783   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8784   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8785   if (N1C) {
8786     unsigned Val = N1C->getZExtValue();
8787     if ((Val & ~Mask) != Val)
8788       return SDValue();
8789
8790     if (ARM::isBitFieldInvertedMask(Mask)) {
8791       Val >>= countTrailingZeros(~Mask);
8792
8793       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8794                         DAG.getConstant(Val, MVT::i32),
8795                         DAG.getConstant(Mask, MVT::i32));
8796
8797       // Do not add new nodes to DAG combiner worklist.
8798       DCI.CombineTo(N, Res, false);
8799       return SDValue();
8800     }
8801   } else if (N1.getOpcode() == ISD::AND) {
8802     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8803     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8804     if (!N11C)
8805       return SDValue();
8806     unsigned Mask2 = N11C->getZExtValue();
8807
8808     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8809     // as is to match.
8810     if (ARM::isBitFieldInvertedMask(Mask) &&
8811         (Mask == ~Mask2)) {
8812       // The pack halfword instruction works better for masks that fit it,
8813       // so use that when it's available.
8814       if (Subtarget->hasT2ExtractPack() &&
8815           (Mask == 0xffff || Mask == 0xffff0000))
8816         return SDValue();
8817       // 2a
8818       unsigned amt = countTrailingZeros(Mask2);
8819       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8820                         DAG.getConstant(amt, MVT::i32));
8821       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8822                         DAG.getConstant(Mask, MVT::i32));
8823       // Do not add new nodes to DAG combiner worklist.
8824       DCI.CombineTo(N, Res, false);
8825       return SDValue();
8826     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8827                (~Mask == Mask2)) {
8828       // The pack halfword instruction works better for masks that fit it,
8829       // so use that when it's available.
8830       if (Subtarget->hasT2ExtractPack() &&
8831           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8832         return SDValue();
8833       // 2b
8834       unsigned lsb = countTrailingZeros(Mask);
8835       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8836                         DAG.getConstant(lsb, MVT::i32));
8837       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8838                         DAG.getConstant(Mask2, MVT::i32));
8839       // Do not add new nodes to DAG combiner worklist.
8840       DCI.CombineTo(N, Res, false);
8841       return SDValue();
8842     }
8843   }
8844
8845   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8846       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8847       ARM::isBitFieldInvertedMask(~Mask)) {
8848     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8849     // where lsb(mask) == #shamt and masked bits of B are known zero.
8850     SDValue ShAmt = N00.getOperand(1);
8851     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8852     unsigned LSB = countTrailingZeros(Mask);
8853     if (ShAmtC != LSB)
8854       return SDValue();
8855
8856     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8857                       DAG.getConstant(~Mask, MVT::i32));
8858
8859     // Do not add new nodes to DAG combiner worklist.
8860     DCI.CombineTo(N, Res, false);
8861   }
8862
8863   return SDValue();
8864 }
8865
8866 static SDValue PerformXORCombine(SDNode *N,
8867                                  TargetLowering::DAGCombinerInfo &DCI,
8868                                  const ARMSubtarget *Subtarget) {
8869   EVT VT = N->getValueType(0);
8870   SelectionDAG &DAG = DCI.DAG;
8871
8872   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8873     return SDValue();
8874
8875   if (!Subtarget->isThumb1Only()) {
8876     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8877     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8878     if (Result.getNode())
8879       return Result;
8880   }
8881
8882   return SDValue();
8883 }
8884
8885 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8886 /// the bits being cleared by the AND are not demanded by the BFI.
8887 static SDValue PerformBFICombine(SDNode *N,
8888                                  TargetLowering::DAGCombinerInfo &DCI) {
8889   SDValue N1 = N->getOperand(1);
8890   if (N1.getOpcode() == ISD::AND) {
8891     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8892     if (!N11C)
8893       return SDValue();
8894     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8895     unsigned LSB = countTrailingZeros(~InvMask);
8896     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8897     unsigned Mask = (1 << Width)-1;
8898     unsigned Mask2 = N11C->getZExtValue();
8899     if ((Mask & (~Mask2)) == 0)
8900       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8901                              N->getOperand(0), N1.getOperand(0),
8902                              N->getOperand(2));
8903   }
8904   return SDValue();
8905 }
8906
8907 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8908 /// ARMISD::VMOVRRD.
8909 static SDValue PerformVMOVRRDCombine(SDNode *N,
8910                                      TargetLowering::DAGCombinerInfo &DCI) {
8911   // vmovrrd(vmovdrr x, y) -> x,y
8912   SDValue InDouble = N->getOperand(0);
8913   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8914     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8915
8916   // vmovrrd(load f64) -> (load i32), (load i32)
8917   SDNode *InNode = InDouble.getNode();
8918   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8919       InNode->getValueType(0) == MVT::f64 &&
8920       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8921       !cast<LoadSDNode>(InNode)->isVolatile()) {
8922     // TODO: Should this be done for non-FrameIndex operands?
8923     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8924
8925     SelectionDAG &DAG = DCI.DAG;
8926     SDLoc DL(LD);
8927     SDValue BasePtr = LD->getBasePtr();
8928     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8929                                  LD->getPointerInfo(), LD->isVolatile(),
8930                                  LD->isNonTemporal(), LD->isInvariant(),
8931                                  LD->getAlignment());
8932
8933     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8934                                     DAG.getConstant(4, MVT::i32));
8935     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8936                                  LD->getPointerInfo(), LD->isVolatile(),
8937                                  LD->isNonTemporal(), LD->isInvariant(),
8938                                  std::min(4U, LD->getAlignment() / 2));
8939
8940     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8941     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8942     DCI.RemoveFromWorklist(LD);
8943     DAG.DeleteNode(LD);
8944     return Result;
8945   }
8946
8947   return SDValue();
8948 }
8949
8950 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8951 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8952 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8953   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8954   SDValue Op0 = N->getOperand(0);
8955   SDValue Op1 = N->getOperand(1);
8956   if (Op0.getOpcode() == ISD::BITCAST)
8957     Op0 = Op0.getOperand(0);
8958   if (Op1.getOpcode() == ISD::BITCAST)
8959     Op1 = Op1.getOperand(0);
8960   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8961       Op0.getNode() == Op1.getNode() &&
8962       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8963     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8964                        N->getValueType(0), Op0.getOperand(0));
8965   return SDValue();
8966 }
8967
8968 /// PerformSTORECombine - Target-specific dag combine xforms for
8969 /// ISD::STORE.
8970 static SDValue PerformSTORECombine(SDNode *N,
8971                                    TargetLowering::DAGCombinerInfo &DCI) {
8972   StoreSDNode *St = cast<StoreSDNode>(N);
8973   if (St->isVolatile())
8974     return SDValue();
8975
8976   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8977   // pack all of the elements in one place.  Next, store to memory in fewer
8978   // chunks.
8979   SDValue StVal = St->getValue();
8980   EVT VT = StVal.getValueType();
8981   if (St->isTruncatingStore() && VT.isVector()) {
8982     SelectionDAG &DAG = DCI.DAG;
8983     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8984     EVT StVT = St->getMemoryVT();
8985     unsigned NumElems = VT.getVectorNumElements();
8986     assert(StVT != VT && "Cannot truncate to the same type");
8987     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8988     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8989
8990     // From, To sizes and ElemCount must be pow of two
8991     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8992
8993     // We are going to use the original vector elt for storing.
8994     // Accumulated smaller vector elements must be a multiple of the store size.
8995     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8996
8997     unsigned SizeRatio  = FromEltSz / ToEltSz;
8998     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8999
9000     // Create a type on which we perform the shuffle.
9001     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9002                                      NumElems*SizeRatio);
9003     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9004
9005     SDLoc DL(St);
9006     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9007     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9008     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
9009
9010     // Can't shuffle using an illegal type.
9011     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9012
9013     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9014                                 DAG.getUNDEF(WideVec.getValueType()),
9015                                 ShuffleVec.data());
9016     // At this point all of the data is stored at the bottom of the
9017     // register. We now need to save it to mem.
9018
9019     // Find the largest store unit
9020     MVT StoreType = MVT::i8;
9021     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
9022          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
9023       MVT Tp = (MVT::SimpleValueType)tp;
9024       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9025         StoreType = Tp;
9026     }
9027     // Didn't find a legal store type.
9028     if (!TLI.isTypeLegal(StoreType))
9029       return SDValue();
9030
9031     // Bitcast the original vector into a vector of store-size units
9032     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9033             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9034     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9035     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9036     SmallVector<SDValue, 8> Chains;
9037     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
9038                                         TLI.getPointerTy());
9039     SDValue BasePtr = St->getBasePtr();
9040
9041     // Perform one or more big stores into memory.
9042     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9043     for (unsigned I = 0; I < E; I++) {
9044       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9045                                    StoreType, ShuffWide,
9046                                    DAG.getIntPtrConstant(I));
9047       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9048                                 St->getPointerInfo(), St->isVolatile(),
9049                                 St->isNonTemporal(), St->getAlignment());
9050       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9051                             Increment);
9052       Chains.push_back(Ch);
9053     }
9054     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
9055                        Chains.size());
9056   }
9057
9058   if (!ISD::isNormalStore(St))
9059     return SDValue();
9060
9061   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9062   // ARM stores of arguments in the same cache line.
9063   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9064       StVal.getNode()->hasOneUse()) {
9065     SelectionDAG  &DAG = DCI.DAG;
9066     SDLoc DL(St);
9067     SDValue BasePtr = St->getBasePtr();
9068     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9069                                   StVal.getNode()->getOperand(0), BasePtr,
9070                                   St->getPointerInfo(), St->isVolatile(),
9071                                   St->isNonTemporal(), St->getAlignment());
9072
9073     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9074                                     DAG.getConstant(4, MVT::i32));
9075     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
9076                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9077                         St->isNonTemporal(),
9078                         std::min(4U, St->getAlignment() / 2));
9079   }
9080
9081   if (StVal.getValueType() != MVT::i64 ||
9082       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9083     return SDValue();
9084
9085   // Bitcast an i64 store extracted from a vector to f64.
9086   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9087   SelectionDAG &DAG = DCI.DAG;
9088   SDLoc dl(StVal);
9089   SDValue IntVec = StVal.getOperand(0);
9090   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9091                                  IntVec.getValueType().getVectorNumElements());
9092   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9093   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9094                                Vec, StVal.getOperand(1));
9095   dl = SDLoc(N);
9096   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9097   // Make the DAGCombiner fold the bitcasts.
9098   DCI.AddToWorklist(Vec.getNode());
9099   DCI.AddToWorklist(ExtElt.getNode());
9100   DCI.AddToWorklist(V.getNode());
9101   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9102                       St->getPointerInfo(), St->isVolatile(),
9103                       St->isNonTemporal(), St->getAlignment(),
9104                       St->getTBAAInfo());
9105 }
9106
9107 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9108 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
9109 /// i64 vector to have f64 elements, since the value can then be loaded
9110 /// directly into a VFP register.
9111 static bool hasNormalLoadOperand(SDNode *N) {
9112   unsigned NumElts = N->getValueType(0).getVectorNumElements();
9113   for (unsigned i = 0; i < NumElts; ++i) {
9114     SDNode *Elt = N->getOperand(i).getNode();
9115     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9116       return true;
9117   }
9118   return false;
9119 }
9120
9121 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9122 /// ISD::BUILD_VECTOR.
9123 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9124                                           TargetLowering::DAGCombinerInfo &DCI){
9125   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9126   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
9127   // into a pair of GPRs, which is fine when the value is used as a scalar,
9128   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9129   SelectionDAG &DAG = DCI.DAG;
9130   if (N->getNumOperands() == 2) {
9131     SDValue RV = PerformVMOVDRRCombine(N, DAG);
9132     if (RV.getNode())
9133       return RV;
9134   }
9135
9136   // Load i64 elements as f64 values so that type legalization does not split
9137   // them up into i32 values.
9138   EVT VT = N->getValueType(0);
9139   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9140     return SDValue();
9141   SDLoc dl(N);
9142   SmallVector<SDValue, 8> Ops;
9143   unsigned NumElts = VT.getVectorNumElements();
9144   for (unsigned i = 0; i < NumElts; ++i) {
9145     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9146     Ops.push_back(V);
9147     // Make the DAGCombiner fold the bitcast.
9148     DCI.AddToWorklist(V.getNode());
9149   }
9150   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9151   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
9152   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9153 }
9154
9155 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9156 static SDValue
9157 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9158   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9159   // At that time, we may have inserted bitcasts from integer to float.
9160   // If these bitcasts have survived DAGCombine, change the lowering of this
9161   // BUILD_VECTOR in something more vector friendly, i.e., that does not
9162   // force to use floating point types.
9163
9164   // Make sure we can change the type of the vector.
9165   // This is possible iff:
9166   // 1. The vector is only used in a bitcast to a integer type. I.e.,
9167   //    1.1. Vector is used only once.
9168   //    1.2. Use is a bit convert to an integer type.
9169   // 2. The size of its operands are 32-bits (64-bits are not legal).
9170   EVT VT = N->getValueType(0);
9171   EVT EltVT = VT.getVectorElementType();
9172
9173   // Check 1.1. and 2.
9174   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9175     return SDValue();
9176
9177   // By construction, the input type must be float.
9178   assert(EltVT == MVT::f32 && "Unexpected type!");
9179
9180   // Check 1.2.
9181   SDNode *Use = *N->use_begin();
9182   if (Use->getOpcode() != ISD::BITCAST ||
9183       Use->getValueType(0).isFloatingPoint())
9184     return SDValue();
9185
9186   // Check profitability.
9187   // Model is, if more than half of the relevant operands are bitcast from
9188   // i32, turn the build_vector into a sequence of insert_vector_elt.
9189   // Relevant operands are everything that is not statically
9190   // (i.e., at compile time) bitcasted.
9191   unsigned NumOfBitCastedElts = 0;
9192   unsigned NumElts = VT.getVectorNumElements();
9193   unsigned NumOfRelevantElts = NumElts;
9194   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9195     SDValue Elt = N->getOperand(Idx);
9196     if (Elt->getOpcode() == ISD::BITCAST) {
9197       // Assume only bit cast to i32 will go away.
9198       if (Elt->getOperand(0).getValueType() == MVT::i32)
9199         ++NumOfBitCastedElts;
9200     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9201       // Constants are statically casted, thus do not count them as
9202       // relevant operands.
9203       --NumOfRelevantElts;
9204   }
9205
9206   // Check if more than half of the elements require a non-free bitcast.
9207   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9208     return SDValue();
9209
9210   SelectionDAG &DAG = DCI.DAG;
9211   // Create the new vector type.
9212   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9213   // Check if the type is legal.
9214   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9215   if (!TLI.isTypeLegal(VecVT))
9216     return SDValue();
9217
9218   // Combine:
9219   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9220   // => BITCAST INSERT_VECTOR_ELT
9221   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9222   //                      (BITCAST EN), N.
9223   SDValue Vec = DAG.getUNDEF(VecVT);
9224   SDLoc dl(N);
9225   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9226     SDValue V = N->getOperand(Idx);
9227     if (V.getOpcode() == ISD::UNDEF)
9228       continue;
9229     if (V.getOpcode() == ISD::BITCAST &&
9230         V->getOperand(0).getValueType() == MVT::i32)
9231       // Fold obvious case.
9232       V = V.getOperand(0);
9233     else {
9234       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 
9235       // Make the DAGCombiner fold the bitcasts.
9236       DCI.AddToWorklist(V.getNode());
9237     }
9238     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
9239     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9240   }
9241   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9242   // Make the DAGCombiner fold the bitcasts.
9243   DCI.AddToWorklist(Vec.getNode());
9244   return Vec;
9245 }
9246
9247 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9248 /// ISD::INSERT_VECTOR_ELT.
9249 static SDValue PerformInsertEltCombine(SDNode *N,
9250                                        TargetLowering::DAGCombinerInfo &DCI) {
9251   // Bitcast an i64 load inserted into a vector to f64.
9252   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9253   EVT VT = N->getValueType(0);
9254   SDNode *Elt = N->getOperand(1).getNode();
9255   if (VT.getVectorElementType() != MVT::i64 ||
9256       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9257     return SDValue();
9258
9259   SelectionDAG &DAG = DCI.DAG;
9260   SDLoc dl(N);
9261   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9262                                  VT.getVectorNumElements());
9263   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9264   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9265   // Make the DAGCombiner fold the bitcasts.
9266   DCI.AddToWorklist(Vec.getNode());
9267   DCI.AddToWorklist(V.getNode());
9268   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9269                                Vec, V, N->getOperand(2));
9270   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9271 }
9272
9273 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9274 /// ISD::VECTOR_SHUFFLE.
9275 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9276   // The LLVM shufflevector instruction does not require the shuffle mask
9277   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9278   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
9279   // operands do not match the mask length, they are extended by concatenating
9280   // them with undef vectors.  That is probably the right thing for other
9281   // targets, but for NEON it is better to concatenate two double-register
9282   // size vector operands into a single quad-register size vector.  Do that
9283   // transformation here:
9284   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
9285   //   shuffle(concat(v1, v2), undef)
9286   SDValue Op0 = N->getOperand(0);
9287   SDValue Op1 = N->getOperand(1);
9288   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9289       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9290       Op0.getNumOperands() != 2 ||
9291       Op1.getNumOperands() != 2)
9292     return SDValue();
9293   SDValue Concat0Op1 = Op0.getOperand(1);
9294   SDValue Concat1Op1 = Op1.getOperand(1);
9295   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9296       Concat1Op1.getOpcode() != ISD::UNDEF)
9297     return SDValue();
9298   // Skip the transformation if any of the types are illegal.
9299   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9300   EVT VT = N->getValueType(0);
9301   if (!TLI.isTypeLegal(VT) ||
9302       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9303       !TLI.isTypeLegal(Concat1Op1.getValueType()))
9304     return SDValue();
9305
9306   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9307                                   Op0.getOperand(0), Op1.getOperand(0));
9308   // Translate the shuffle mask.
9309   SmallVector<int, 16> NewMask;
9310   unsigned NumElts = VT.getVectorNumElements();
9311   unsigned HalfElts = NumElts/2;
9312   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9313   for (unsigned n = 0; n < NumElts; ++n) {
9314     int MaskElt = SVN->getMaskElt(n);
9315     int NewElt = -1;
9316     if (MaskElt < (int)HalfElts)
9317       NewElt = MaskElt;
9318     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9319       NewElt = HalfElts + MaskElt - NumElts;
9320     NewMask.push_back(NewElt);
9321   }
9322   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9323                               DAG.getUNDEF(VT), NewMask.data());
9324 }
9325
9326 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
9327 /// NEON load/store intrinsics to merge base address updates.
9328 static SDValue CombineBaseUpdate(SDNode *N,
9329                                  TargetLowering::DAGCombinerInfo &DCI) {
9330   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9331     return SDValue();
9332
9333   SelectionDAG &DAG = DCI.DAG;
9334   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9335                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9336   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
9337   SDValue Addr = N->getOperand(AddrOpIdx);
9338
9339   // Search for a use of the address operand that is an increment.
9340   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9341          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9342     SDNode *User = *UI;
9343     if (User->getOpcode() != ISD::ADD ||
9344         UI.getUse().getResNo() != Addr.getResNo())
9345       continue;
9346
9347     // Check that the add is independent of the load/store.  Otherwise, folding
9348     // it would create a cycle.
9349     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9350       continue;
9351
9352     // Find the new opcode for the updating load/store.
9353     bool isLoad = true;
9354     bool isLaneOp = false;
9355     unsigned NewOpc = 0;
9356     unsigned NumVecs = 0;
9357     if (isIntrinsic) {
9358       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9359       switch (IntNo) {
9360       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9361       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9362         NumVecs = 1; break;
9363       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9364         NumVecs = 2; break;
9365       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9366         NumVecs = 3; break;
9367       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9368         NumVecs = 4; break;
9369       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9370         NumVecs = 2; isLaneOp = true; break;
9371       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9372         NumVecs = 3; isLaneOp = true; break;
9373       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9374         NumVecs = 4; isLaneOp = true; break;
9375       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9376         NumVecs = 1; isLoad = false; break;
9377       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9378         NumVecs = 2; isLoad = false; break;
9379       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9380         NumVecs = 3; isLoad = false; break;
9381       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9382         NumVecs = 4; isLoad = false; break;
9383       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9384         NumVecs = 2; isLoad = false; isLaneOp = true; break;
9385       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9386         NumVecs = 3; isLoad = false; isLaneOp = true; break;
9387       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9388         NumVecs = 4; isLoad = false; isLaneOp = true; break;
9389       }
9390     } else {
9391       isLaneOp = true;
9392       switch (N->getOpcode()) {
9393       default: llvm_unreachable("unexpected opcode for Neon base update");
9394       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9395       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9396       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9397       }
9398     }
9399
9400     // Find the size of memory referenced by the load/store.
9401     EVT VecTy;
9402     if (isLoad)
9403       VecTy = N->getValueType(0);
9404     else
9405       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9406     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9407     if (isLaneOp)
9408       NumBytes /= VecTy.getVectorNumElements();
9409
9410     // If the increment is a constant, it must match the memory ref size.
9411     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9412     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9413       uint64_t IncVal = CInc->getZExtValue();
9414       if (IncVal != NumBytes)
9415         continue;
9416     } else if (NumBytes >= 3 * 16) {
9417       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9418       // separate instructions that make it harder to use a non-constant update.
9419       continue;
9420     }
9421
9422     // Create the new updating load/store node.
9423     EVT Tys[6];
9424     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
9425     unsigned n;
9426     for (n = 0; n < NumResultVecs; ++n)
9427       Tys[n] = VecTy;
9428     Tys[n++] = MVT::i32;
9429     Tys[n] = MVT::Other;
9430     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
9431     SmallVector<SDValue, 8> Ops;
9432     Ops.push_back(N->getOperand(0)); // incoming chain
9433     Ops.push_back(N->getOperand(AddrOpIdx));
9434     Ops.push_back(Inc);
9435     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
9436       Ops.push_back(N->getOperand(i));
9437     }
9438     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9439     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9440                                            Ops.data(), Ops.size(),
9441                                            MemInt->getMemoryVT(),
9442                                            MemInt->getMemOperand());
9443
9444     // Update the uses.
9445     std::vector<SDValue> NewResults;
9446     for (unsigned i = 0; i < NumResultVecs; ++i) {
9447       NewResults.push_back(SDValue(UpdN.getNode(), i));
9448     }
9449     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9450     DCI.CombineTo(N, NewResults);
9451     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9452
9453     break;
9454   }
9455   return SDValue();
9456 }
9457
9458 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9459 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9460 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9461 /// return true.
9462 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9463   SelectionDAG &DAG = DCI.DAG;
9464   EVT VT = N->getValueType(0);
9465   // vldN-dup instructions only support 64-bit vectors for N > 1.
9466   if (!VT.is64BitVector())
9467     return false;
9468
9469   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9470   SDNode *VLD = N->getOperand(0).getNode();
9471   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9472     return false;
9473   unsigned NumVecs = 0;
9474   unsigned NewOpc = 0;
9475   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9476   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9477     NumVecs = 2;
9478     NewOpc = ARMISD::VLD2DUP;
9479   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9480     NumVecs = 3;
9481     NewOpc = ARMISD::VLD3DUP;
9482   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9483     NumVecs = 4;
9484     NewOpc = ARMISD::VLD4DUP;
9485   } else {
9486     return false;
9487   }
9488
9489   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9490   // numbers match the load.
9491   unsigned VLDLaneNo =
9492     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9493   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9494        UI != UE; ++UI) {
9495     // Ignore uses of the chain result.
9496     if (UI.getUse().getResNo() == NumVecs)
9497       continue;
9498     SDNode *User = *UI;
9499     if (User->getOpcode() != ARMISD::VDUPLANE ||
9500         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9501       return false;
9502   }
9503
9504   // Create the vldN-dup node.
9505   EVT Tys[5];
9506   unsigned n;
9507   for (n = 0; n < NumVecs; ++n)
9508     Tys[n] = VT;
9509   Tys[n] = MVT::Other;
9510   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
9511   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9512   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9513   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9514                                            Ops, 2, VLDMemInt->getMemoryVT(),
9515                                            VLDMemInt->getMemOperand());
9516
9517   // Update the uses.
9518   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9519        UI != UE; ++UI) {
9520     unsigned ResNo = UI.getUse().getResNo();
9521     // Ignore uses of the chain result.
9522     if (ResNo == NumVecs)
9523       continue;
9524     SDNode *User = *UI;
9525     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9526   }
9527
9528   // Now the vldN-lane intrinsic is dead except for its chain result.
9529   // Update uses of the chain.
9530   std::vector<SDValue> VLDDupResults;
9531   for (unsigned n = 0; n < NumVecs; ++n)
9532     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9533   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9534   DCI.CombineTo(VLD, VLDDupResults);
9535
9536   return true;
9537 }
9538
9539 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9540 /// ARMISD::VDUPLANE.
9541 static SDValue PerformVDUPLANECombine(SDNode *N,
9542                                       TargetLowering::DAGCombinerInfo &DCI) {
9543   SDValue Op = N->getOperand(0);
9544
9545   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9546   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9547   if (CombineVLDDUP(N, DCI))
9548     return SDValue(N, 0);
9549
9550   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9551   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9552   while (Op.getOpcode() == ISD::BITCAST)
9553     Op = Op.getOperand(0);
9554   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9555     return SDValue();
9556
9557   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9558   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9559   // The canonical VMOV for a zero vector uses a 32-bit element size.
9560   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9561   unsigned EltBits;
9562   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9563     EltSize = 8;
9564   EVT VT = N->getValueType(0);
9565   if (EltSize > VT.getVectorElementType().getSizeInBits())
9566     return SDValue();
9567
9568   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9569 }
9570
9571 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9572 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9573 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9574 {
9575   integerPart cN;
9576   integerPart c0 = 0;
9577   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9578        I != E; I++) {
9579     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9580     if (!C)
9581       return false;
9582
9583     bool isExact;
9584     APFloat APF = C->getValueAPF();
9585     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9586         != APFloat::opOK || !isExact)
9587       return false;
9588
9589     c0 = (I == 0) ? cN : c0;
9590     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9591       return false;
9592   }
9593   C = c0;
9594   return true;
9595 }
9596
9597 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9598 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9599 /// when the VMUL has a constant operand that is a power of 2.
9600 ///
9601 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9602 ///  vmul.f32        d16, d17, d16
9603 ///  vcvt.s32.f32    d16, d16
9604 /// becomes:
9605 ///  vcvt.s32.f32    d16, d16, #3
9606 static SDValue PerformVCVTCombine(SDNode *N,
9607                                   TargetLowering::DAGCombinerInfo &DCI,
9608                                   const ARMSubtarget *Subtarget) {
9609   SelectionDAG &DAG = DCI.DAG;
9610   SDValue Op = N->getOperand(0);
9611
9612   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9613       Op.getOpcode() != ISD::FMUL)
9614     return SDValue();
9615
9616   uint64_t C;
9617   SDValue N0 = Op->getOperand(0);
9618   SDValue ConstVec = Op->getOperand(1);
9619   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9620
9621   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9622       !isConstVecPow2(ConstVec, isSigned, C))
9623     return SDValue();
9624
9625   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9626   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9627   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9628     // These instructions only exist converting from f32 to i32. We can handle
9629     // smaller integers by generating an extra truncate, but larger ones would
9630     // be lossy.
9631     return SDValue();
9632   }
9633
9634   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9635     Intrinsic::arm_neon_vcvtfp2fxu;
9636   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9637   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9638                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9639                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9640                                  DAG.getConstant(Log2_64(C), MVT::i32));
9641
9642   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9643     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9644
9645   return FixConv;
9646 }
9647
9648 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9649 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9650 /// when the VDIV has a constant operand that is a power of 2.
9651 ///
9652 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9653 ///  vcvt.f32.s32    d16, d16
9654 ///  vdiv.f32        d16, d17, d16
9655 /// becomes:
9656 ///  vcvt.f32.s32    d16, d16, #3
9657 static SDValue PerformVDIVCombine(SDNode *N,
9658                                   TargetLowering::DAGCombinerInfo &DCI,
9659                                   const ARMSubtarget *Subtarget) {
9660   SelectionDAG &DAG = DCI.DAG;
9661   SDValue Op = N->getOperand(0);
9662   unsigned OpOpcode = Op.getNode()->getOpcode();
9663
9664   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9665       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9666     return SDValue();
9667
9668   uint64_t C;
9669   SDValue ConstVec = N->getOperand(1);
9670   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9671
9672   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9673       !isConstVecPow2(ConstVec, isSigned, C))
9674     return SDValue();
9675
9676   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9677   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9678   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9679     // These instructions only exist converting from i32 to f32. We can handle
9680     // smaller integers by generating an extra extend, but larger ones would
9681     // be lossy.
9682     return SDValue();
9683   }
9684
9685   SDValue ConvInput = Op.getOperand(0);
9686   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9687   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9688     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9689                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9690                             ConvInput);
9691
9692   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9693     Intrinsic::arm_neon_vcvtfxu2fp;
9694   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9695                      Op.getValueType(),
9696                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9697                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9698 }
9699
9700 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9701 /// operand of a vector shift operation, where all the elements of the
9702 /// build_vector must have the same constant integer value.
9703 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9704   // Ignore bit_converts.
9705   while (Op.getOpcode() == ISD::BITCAST)
9706     Op = Op.getOperand(0);
9707   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9708   APInt SplatBits, SplatUndef;
9709   unsigned SplatBitSize;
9710   bool HasAnyUndefs;
9711   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9712                                       HasAnyUndefs, ElementBits) ||
9713       SplatBitSize > ElementBits)
9714     return false;
9715   Cnt = SplatBits.getSExtValue();
9716   return true;
9717 }
9718
9719 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9720 /// operand of a vector shift left operation.  That value must be in the range:
9721 ///   0 <= Value < ElementBits for a left shift; or
9722 ///   0 <= Value <= ElementBits for a long left shift.
9723 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9724   assert(VT.isVector() && "vector shift count is not a vector type");
9725   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9726   if (! getVShiftImm(Op, ElementBits, Cnt))
9727     return false;
9728   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9729 }
9730
9731 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9732 /// operand of a vector shift right operation.  For a shift opcode, the value
9733 /// is positive, but for an intrinsic the value count must be negative. The
9734 /// absolute value must be in the range:
9735 ///   1 <= |Value| <= ElementBits for a right shift; or
9736 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9737 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9738                          int64_t &Cnt) {
9739   assert(VT.isVector() && "vector shift count is not a vector type");
9740   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9741   if (! getVShiftImm(Op, ElementBits, Cnt))
9742     return false;
9743   if (isIntrinsic)
9744     Cnt = -Cnt;
9745   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9746 }
9747
9748 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9749 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9750   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9751   switch (IntNo) {
9752   default:
9753     // Don't do anything for most intrinsics.
9754     break;
9755
9756   // Vector shifts: check for immediate versions and lower them.
9757   // Note: This is done during DAG combining instead of DAG legalizing because
9758   // the build_vectors for 64-bit vector element shift counts are generally
9759   // not legal, and it is hard to see their values after they get legalized to
9760   // loads from a constant pool.
9761   case Intrinsic::arm_neon_vshifts:
9762   case Intrinsic::arm_neon_vshiftu:
9763   case Intrinsic::arm_neon_vshiftls:
9764   case Intrinsic::arm_neon_vshiftlu:
9765   case Intrinsic::arm_neon_vshiftn:
9766   case Intrinsic::arm_neon_vrshifts:
9767   case Intrinsic::arm_neon_vrshiftu:
9768   case Intrinsic::arm_neon_vrshiftn:
9769   case Intrinsic::arm_neon_vqshifts:
9770   case Intrinsic::arm_neon_vqshiftu:
9771   case Intrinsic::arm_neon_vqshiftsu:
9772   case Intrinsic::arm_neon_vqshiftns:
9773   case Intrinsic::arm_neon_vqshiftnu:
9774   case Intrinsic::arm_neon_vqshiftnsu:
9775   case Intrinsic::arm_neon_vqrshiftns:
9776   case Intrinsic::arm_neon_vqrshiftnu:
9777   case Intrinsic::arm_neon_vqrshiftnsu: {
9778     EVT VT = N->getOperand(1).getValueType();
9779     int64_t Cnt;
9780     unsigned VShiftOpc = 0;
9781
9782     switch (IntNo) {
9783     case Intrinsic::arm_neon_vshifts:
9784     case Intrinsic::arm_neon_vshiftu:
9785       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9786         VShiftOpc = ARMISD::VSHL;
9787         break;
9788       }
9789       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9790         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9791                      ARMISD::VSHRs : ARMISD::VSHRu);
9792         break;
9793       }
9794       return SDValue();
9795
9796     case Intrinsic::arm_neon_vshiftls:
9797     case Intrinsic::arm_neon_vshiftlu:
9798       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
9799         break;
9800       llvm_unreachable("invalid shift count for vshll intrinsic");
9801
9802     case Intrinsic::arm_neon_vrshifts:
9803     case Intrinsic::arm_neon_vrshiftu:
9804       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9805         break;
9806       return SDValue();
9807
9808     case Intrinsic::arm_neon_vqshifts:
9809     case Intrinsic::arm_neon_vqshiftu:
9810       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9811         break;
9812       return SDValue();
9813
9814     case Intrinsic::arm_neon_vqshiftsu:
9815       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9816         break;
9817       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9818
9819     case Intrinsic::arm_neon_vshiftn:
9820     case Intrinsic::arm_neon_vrshiftn:
9821     case Intrinsic::arm_neon_vqshiftns:
9822     case Intrinsic::arm_neon_vqshiftnu:
9823     case Intrinsic::arm_neon_vqshiftnsu:
9824     case Intrinsic::arm_neon_vqrshiftns:
9825     case Intrinsic::arm_neon_vqrshiftnu:
9826     case Intrinsic::arm_neon_vqrshiftnsu:
9827       // Narrowing shifts require an immediate right shift.
9828       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9829         break;
9830       llvm_unreachable("invalid shift count for narrowing vector shift "
9831                        "intrinsic");
9832
9833     default:
9834       llvm_unreachable("unhandled vector shift");
9835     }
9836
9837     switch (IntNo) {
9838     case Intrinsic::arm_neon_vshifts:
9839     case Intrinsic::arm_neon_vshiftu:
9840       // Opcode already set above.
9841       break;
9842     case Intrinsic::arm_neon_vshiftls:
9843     case Intrinsic::arm_neon_vshiftlu:
9844       if (Cnt == VT.getVectorElementType().getSizeInBits())
9845         VShiftOpc = ARMISD::VSHLLi;
9846       else
9847         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
9848                      ARMISD::VSHLLs : ARMISD::VSHLLu);
9849       break;
9850     case Intrinsic::arm_neon_vshiftn:
9851       VShiftOpc = ARMISD::VSHRN; break;
9852     case Intrinsic::arm_neon_vrshifts:
9853       VShiftOpc = ARMISD::VRSHRs; break;
9854     case Intrinsic::arm_neon_vrshiftu:
9855       VShiftOpc = ARMISD::VRSHRu; break;
9856     case Intrinsic::arm_neon_vrshiftn:
9857       VShiftOpc = ARMISD::VRSHRN; break;
9858     case Intrinsic::arm_neon_vqshifts:
9859       VShiftOpc = ARMISD::VQSHLs; break;
9860     case Intrinsic::arm_neon_vqshiftu:
9861       VShiftOpc = ARMISD::VQSHLu; break;
9862     case Intrinsic::arm_neon_vqshiftsu:
9863       VShiftOpc = ARMISD::VQSHLsu; break;
9864     case Intrinsic::arm_neon_vqshiftns:
9865       VShiftOpc = ARMISD::VQSHRNs; break;
9866     case Intrinsic::arm_neon_vqshiftnu:
9867       VShiftOpc = ARMISD::VQSHRNu; break;
9868     case Intrinsic::arm_neon_vqshiftnsu:
9869       VShiftOpc = ARMISD::VQSHRNsu; break;
9870     case Intrinsic::arm_neon_vqrshiftns:
9871       VShiftOpc = ARMISD::VQRSHRNs; break;
9872     case Intrinsic::arm_neon_vqrshiftnu:
9873       VShiftOpc = ARMISD::VQRSHRNu; break;
9874     case Intrinsic::arm_neon_vqrshiftnsu:
9875       VShiftOpc = ARMISD::VQRSHRNsu; break;
9876     }
9877
9878     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9879                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9880   }
9881
9882   case Intrinsic::arm_neon_vshiftins: {
9883     EVT VT = N->getOperand(1).getValueType();
9884     int64_t Cnt;
9885     unsigned VShiftOpc = 0;
9886
9887     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9888       VShiftOpc = ARMISD::VSLI;
9889     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9890       VShiftOpc = ARMISD::VSRI;
9891     else {
9892       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9893     }
9894
9895     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9896                        N->getOperand(1), N->getOperand(2),
9897                        DAG.getConstant(Cnt, MVT::i32));
9898   }
9899
9900   case Intrinsic::arm_neon_vqrshifts:
9901   case Intrinsic::arm_neon_vqrshiftu:
9902     // No immediate versions of these to check for.
9903     break;
9904   }
9905
9906   return SDValue();
9907 }
9908
9909 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9910 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9911 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9912 /// vector element shift counts are generally not legal, and it is hard to see
9913 /// their values after they get legalized to loads from a constant pool.
9914 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9915                                    const ARMSubtarget *ST) {
9916   EVT VT = N->getValueType(0);
9917   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9918     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9919     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9920     SDValue N1 = N->getOperand(1);
9921     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9922       SDValue N0 = N->getOperand(0);
9923       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9924           DAG.MaskedValueIsZero(N0.getOperand(0),
9925                                 APInt::getHighBitsSet(32, 16)))
9926         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9927     }
9928   }
9929
9930   // Nothing to be done for scalar shifts.
9931   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9932   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9933     return SDValue();
9934
9935   assert(ST->hasNEON() && "unexpected vector shift");
9936   int64_t Cnt;
9937
9938   switch (N->getOpcode()) {
9939   default: llvm_unreachable("unexpected shift opcode");
9940
9941   case ISD::SHL:
9942     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9943       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9944                          DAG.getConstant(Cnt, MVT::i32));
9945     break;
9946
9947   case ISD::SRA:
9948   case ISD::SRL:
9949     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9950       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9951                             ARMISD::VSHRs : ARMISD::VSHRu);
9952       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9953                          DAG.getConstant(Cnt, MVT::i32));
9954     }
9955   }
9956   return SDValue();
9957 }
9958
9959 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9960 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9961 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9962                                     const ARMSubtarget *ST) {
9963   SDValue N0 = N->getOperand(0);
9964
9965   // Check for sign- and zero-extensions of vector extract operations of 8-
9966   // and 16-bit vector elements.  NEON supports these directly.  They are
9967   // handled during DAG combining because type legalization will promote them
9968   // to 32-bit types and it is messy to recognize the operations after that.
9969   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9970     SDValue Vec = N0.getOperand(0);
9971     SDValue Lane = N0.getOperand(1);
9972     EVT VT = N->getValueType(0);
9973     EVT EltVT = N0.getValueType();
9974     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9975
9976     if (VT == MVT::i32 &&
9977         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9978         TLI.isTypeLegal(Vec.getValueType()) &&
9979         isa<ConstantSDNode>(Lane)) {
9980
9981       unsigned Opc = 0;
9982       switch (N->getOpcode()) {
9983       default: llvm_unreachable("unexpected opcode");
9984       case ISD::SIGN_EXTEND:
9985         Opc = ARMISD::VGETLANEs;
9986         break;
9987       case ISD::ZERO_EXTEND:
9988       case ISD::ANY_EXTEND:
9989         Opc = ARMISD::VGETLANEu;
9990         break;
9991       }
9992       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9993     }
9994   }
9995
9996   return SDValue();
9997 }
9998
9999 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
10000 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
10001 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
10002                                        const ARMSubtarget *ST) {
10003   // If the target supports NEON, try to use vmax/vmin instructions for f32
10004   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
10005   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
10006   // a NaN; only do the transformation when it matches that behavior.
10007
10008   // For now only do this when using NEON for FP operations; if using VFP, it
10009   // is not obvious that the benefit outweighs the cost of switching to the
10010   // NEON pipeline.
10011   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
10012       N->getValueType(0) != MVT::f32)
10013     return SDValue();
10014
10015   SDValue CondLHS = N->getOperand(0);
10016   SDValue CondRHS = N->getOperand(1);
10017   SDValue LHS = N->getOperand(2);
10018   SDValue RHS = N->getOperand(3);
10019   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
10020
10021   unsigned Opcode = 0;
10022   bool IsReversed;
10023   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
10024     IsReversed = false; // x CC y ? x : y
10025   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
10026     IsReversed = true ; // x CC y ? y : x
10027   } else {
10028     return SDValue();
10029   }
10030
10031   bool IsUnordered;
10032   switch (CC) {
10033   default: break;
10034   case ISD::SETOLT:
10035   case ISD::SETOLE:
10036   case ISD::SETLT:
10037   case ISD::SETLE:
10038   case ISD::SETULT:
10039   case ISD::SETULE:
10040     // If LHS is NaN, an ordered comparison will be false and the result will
10041     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
10042     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
10043     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
10044     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10045       break;
10046     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
10047     // will return -0, so vmin can only be used for unsafe math or if one of
10048     // the operands is known to be nonzero.
10049     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
10050         !DAG.getTarget().Options.UnsafeFPMath &&
10051         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10052       break;
10053     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
10054     break;
10055
10056   case ISD::SETOGT:
10057   case ISD::SETOGE:
10058   case ISD::SETGT:
10059   case ISD::SETGE:
10060   case ISD::SETUGT:
10061   case ISD::SETUGE:
10062     // If LHS is NaN, an ordered comparison will be false and the result will
10063     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
10064     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
10065     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
10066     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10067       break;
10068     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
10069     // will return +0, so vmax can only be used for unsafe math or if one of
10070     // the operands is known to be nonzero.
10071     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
10072         !DAG.getTarget().Options.UnsafeFPMath &&
10073         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10074       break;
10075     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
10076     break;
10077   }
10078
10079   if (!Opcode)
10080     return SDValue();
10081   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
10082 }
10083
10084 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10085 SDValue
10086 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10087   SDValue Cmp = N->getOperand(4);
10088   if (Cmp.getOpcode() != ARMISD::CMPZ)
10089     // Only looking at EQ and NE cases.
10090     return SDValue();
10091
10092   EVT VT = N->getValueType(0);
10093   SDLoc dl(N);
10094   SDValue LHS = Cmp.getOperand(0);
10095   SDValue RHS = Cmp.getOperand(1);
10096   SDValue FalseVal = N->getOperand(0);
10097   SDValue TrueVal = N->getOperand(1);
10098   SDValue ARMcc = N->getOperand(2);
10099   ARMCC::CondCodes CC =
10100     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10101
10102   // Simplify
10103   //   mov     r1, r0
10104   //   cmp     r1, x
10105   //   mov     r0, y
10106   //   moveq   r0, x
10107   // to
10108   //   cmp     r0, x
10109   //   movne   r0, y
10110   //
10111   //   mov     r1, r0
10112   //   cmp     r1, x
10113   //   mov     r0, x
10114   //   movne   r0, y
10115   // to
10116   //   cmp     r0, x
10117   //   movne   r0, y
10118   /// FIXME: Turn this into a target neutral optimization?
10119   SDValue Res;
10120   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10121     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10122                       N->getOperand(3), Cmp);
10123   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10124     SDValue ARMcc;
10125     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10126     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10127                       N->getOperand(3), NewCmp);
10128   }
10129
10130   if (Res.getNode()) {
10131     APInt KnownZero, KnownOne;
10132     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
10133     // Capture demanded bits information that would be otherwise lost.
10134     if (KnownZero == 0xfffffffe)
10135       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10136                         DAG.getValueType(MVT::i1));
10137     else if (KnownZero == 0xffffff00)
10138       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10139                         DAG.getValueType(MVT::i8));
10140     else if (KnownZero == 0xffff0000)
10141       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10142                         DAG.getValueType(MVT::i16));
10143   }
10144
10145   return Res;
10146 }
10147
10148 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10149                                              DAGCombinerInfo &DCI) const {
10150   switch (N->getOpcode()) {
10151   default: break;
10152   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
10153   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
10154   case ISD::SUB:        return PerformSUBCombine(N, DCI);
10155   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
10156   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
10157   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
10158   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
10159   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
10160   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
10161   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10162   case ISD::STORE:      return PerformSTORECombine(N, DCI);
10163   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
10164   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10165   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10166   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10167   case ISD::FP_TO_SINT:
10168   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10169   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
10170   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10171   case ISD::SHL:
10172   case ISD::SRA:
10173   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10174   case ISD::SIGN_EXTEND:
10175   case ISD::ZERO_EXTEND:
10176   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10177   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
10178   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10179   case ARMISD::VLD2DUP:
10180   case ARMISD::VLD3DUP:
10181   case ARMISD::VLD4DUP:
10182     return CombineBaseUpdate(N, DCI);
10183   case ARMISD::BUILD_VECTOR:
10184     return PerformARMBUILD_VECTORCombine(N, DCI);
10185   case ISD::INTRINSIC_VOID:
10186   case ISD::INTRINSIC_W_CHAIN:
10187     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10188     case Intrinsic::arm_neon_vld1:
10189     case Intrinsic::arm_neon_vld2:
10190     case Intrinsic::arm_neon_vld3:
10191     case Intrinsic::arm_neon_vld4:
10192     case Intrinsic::arm_neon_vld2lane:
10193     case Intrinsic::arm_neon_vld3lane:
10194     case Intrinsic::arm_neon_vld4lane:
10195     case Intrinsic::arm_neon_vst1:
10196     case Intrinsic::arm_neon_vst2:
10197     case Intrinsic::arm_neon_vst3:
10198     case Intrinsic::arm_neon_vst4:
10199     case Intrinsic::arm_neon_vst2lane:
10200     case Intrinsic::arm_neon_vst3lane:
10201     case Intrinsic::arm_neon_vst4lane:
10202       return CombineBaseUpdate(N, DCI);
10203     default: break;
10204     }
10205     break;
10206   }
10207   return SDValue();
10208 }
10209
10210 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10211                                                           EVT VT) const {
10212   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10213 }
10214
10215 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
10216   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10217   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10218
10219   switch (VT.getSimpleVT().SimpleTy) {
10220   default:
10221     return false;
10222   case MVT::i8:
10223   case MVT::i16:
10224   case MVT::i32: {
10225     // Unaligned access can use (for example) LRDB, LRDH, LDR
10226     if (AllowsUnaligned) {
10227       if (Fast)
10228         *Fast = Subtarget->hasV7Ops();
10229       return true;
10230     }
10231     return false;
10232   }
10233   case MVT::f64:
10234   case MVT::v2f64: {
10235     // For any little-endian targets with neon, we can support unaligned ld/st
10236     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10237     // A big-endian target may also explictly support unaligned accesses
10238     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
10239       if (Fast)
10240         *Fast = true;
10241       return true;
10242     }
10243     return false;
10244   }
10245   }
10246 }
10247
10248 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10249                        unsigned AlignCheck) {
10250   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10251           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10252 }
10253
10254 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10255                                            unsigned DstAlign, unsigned SrcAlign,
10256                                            bool IsMemset, bool ZeroMemset,
10257                                            bool MemcpyStrSrc,
10258                                            MachineFunction &MF) const {
10259   const Function *F = MF.getFunction();
10260
10261   // See if we can use NEON instructions for this...
10262   if ((!IsMemset || ZeroMemset) &&
10263       Subtarget->hasNEON() &&
10264       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
10265                                        Attribute::NoImplicitFloat)) {
10266     bool Fast;
10267     if (Size >= 16 &&
10268         (memOpAlign(SrcAlign, DstAlign, 16) ||
10269          (allowsUnalignedMemoryAccesses(MVT::v2f64, &Fast) && Fast))) {
10270       return MVT::v2f64;
10271     } else if (Size >= 8 &&
10272                (memOpAlign(SrcAlign, DstAlign, 8) ||
10273                 (allowsUnalignedMemoryAccesses(MVT::f64, &Fast) && Fast))) {
10274       return MVT::f64;
10275     }
10276   }
10277
10278   // Lowering to i32/i16 if the size permits.
10279   if (Size >= 4)
10280     return MVT::i32;
10281   else if (Size >= 2)
10282     return MVT::i16;
10283
10284   // Let the target-independent logic figure it out.
10285   return MVT::Other;
10286 }
10287
10288 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10289   if (Val.getOpcode() != ISD::LOAD)
10290     return false;
10291
10292   EVT VT1 = Val.getValueType();
10293   if (!VT1.isSimple() || !VT1.isInteger() ||
10294       !VT2.isSimple() || !VT2.isInteger())
10295     return false;
10296
10297   switch (VT1.getSimpleVT().SimpleTy) {
10298   default: break;
10299   case MVT::i1:
10300   case MVT::i8:
10301   case MVT::i16:
10302     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10303     return true;
10304   }
10305
10306   return false;
10307 }
10308
10309 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10310   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10311     return false;
10312
10313   if (!isTypeLegal(EVT::getEVT(Ty1)))
10314     return false;
10315
10316   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10317
10318   // Assuming the caller doesn't have a zeroext or signext return parameter,
10319   // truncation all the way down to i1 is valid.
10320   return true;
10321 }
10322
10323
10324 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10325   if (V < 0)
10326     return false;
10327
10328   unsigned Scale = 1;
10329   switch (VT.getSimpleVT().SimpleTy) {
10330   default: return false;
10331   case MVT::i1:
10332   case MVT::i8:
10333     // Scale == 1;
10334     break;
10335   case MVT::i16:
10336     // Scale == 2;
10337     Scale = 2;
10338     break;
10339   case MVT::i32:
10340     // Scale == 4;
10341     Scale = 4;
10342     break;
10343   }
10344
10345   if ((V & (Scale - 1)) != 0)
10346     return false;
10347   V /= Scale;
10348   return V == (V & ((1LL << 5) - 1));
10349 }
10350
10351 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10352                                       const ARMSubtarget *Subtarget) {
10353   bool isNeg = false;
10354   if (V < 0) {
10355     isNeg = true;
10356     V = - V;
10357   }
10358
10359   switch (VT.getSimpleVT().SimpleTy) {
10360   default: return false;
10361   case MVT::i1:
10362   case MVT::i8:
10363   case MVT::i16:
10364   case MVT::i32:
10365     // + imm12 or - imm8
10366     if (isNeg)
10367       return V == (V & ((1LL << 8) - 1));
10368     return V == (V & ((1LL << 12) - 1));
10369   case MVT::f32:
10370   case MVT::f64:
10371     // Same as ARM mode. FIXME: NEON?
10372     if (!Subtarget->hasVFP2())
10373       return false;
10374     if ((V & 3) != 0)
10375       return false;
10376     V >>= 2;
10377     return V == (V & ((1LL << 8) - 1));
10378   }
10379 }
10380
10381 /// isLegalAddressImmediate - Return true if the integer value can be used
10382 /// as the offset of the target addressing mode for load / store of the
10383 /// given type.
10384 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10385                                     const ARMSubtarget *Subtarget) {
10386   if (V == 0)
10387     return true;
10388
10389   if (!VT.isSimple())
10390     return false;
10391
10392   if (Subtarget->isThumb1Only())
10393     return isLegalT1AddressImmediate(V, VT);
10394   else if (Subtarget->isThumb2())
10395     return isLegalT2AddressImmediate(V, VT, Subtarget);
10396
10397   // ARM mode.
10398   if (V < 0)
10399     V = - V;
10400   switch (VT.getSimpleVT().SimpleTy) {
10401   default: return false;
10402   case MVT::i1:
10403   case MVT::i8:
10404   case MVT::i32:
10405     // +- imm12
10406     return V == (V & ((1LL << 12) - 1));
10407   case MVT::i16:
10408     // +- imm8
10409     return V == (V & ((1LL << 8) - 1));
10410   case MVT::f32:
10411   case MVT::f64:
10412     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10413       return false;
10414     if ((V & 3) != 0)
10415       return false;
10416     V >>= 2;
10417     return V == (V & ((1LL << 8) - 1));
10418   }
10419 }
10420
10421 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10422                                                       EVT VT) const {
10423   int Scale = AM.Scale;
10424   if (Scale < 0)
10425     return false;
10426
10427   switch (VT.getSimpleVT().SimpleTy) {
10428   default: return false;
10429   case MVT::i1:
10430   case MVT::i8:
10431   case MVT::i16:
10432   case MVT::i32:
10433     if (Scale == 1)
10434       return true;
10435     // r + r << imm
10436     Scale = Scale & ~1;
10437     return Scale == 2 || Scale == 4 || Scale == 8;
10438   case MVT::i64:
10439     // r + r
10440     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10441       return true;
10442     return false;
10443   case MVT::isVoid:
10444     // Note, we allow "void" uses (basically, uses that aren't loads or
10445     // stores), because arm allows folding a scale into many arithmetic
10446     // operations.  This should be made more precise and revisited later.
10447
10448     // Allow r << imm, but the imm has to be a multiple of two.
10449     if (Scale & 1) return false;
10450     return isPowerOf2_32(Scale);
10451   }
10452 }
10453
10454 /// isLegalAddressingMode - Return true if the addressing mode represented
10455 /// by AM is legal for this target, for a load/store of the specified type.
10456 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10457                                               Type *Ty) const {
10458   EVT VT = getValueType(Ty, true);
10459   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10460     return false;
10461
10462   // Can never fold addr of global into load/store.
10463   if (AM.BaseGV)
10464     return false;
10465
10466   switch (AM.Scale) {
10467   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10468     break;
10469   case 1:
10470     if (Subtarget->isThumb1Only())
10471       return false;
10472     // FALL THROUGH.
10473   default:
10474     // ARM doesn't support any R+R*scale+imm addr modes.
10475     if (AM.BaseOffs)
10476       return false;
10477
10478     if (!VT.isSimple())
10479       return false;
10480
10481     if (Subtarget->isThumb2())
10482       return isLegalT2ScaledAddressingMode(AM, VT);
10483
10484     int Scale = AM.Scale;
10485     switch (VT.getSimpleVT().SimpleTy) {
10486     default: return false;
10487     case MVT::i1:
10488     case MVT::i8:
10489     case MVT::i32:
10490       if (Scale < 0) Scale = -Scale;
10491       if (Scale == 1)
10492         return true;
10493       // r + r << imm
10494       return isPowerOf2_32(Scale & ~1);
10495     case MVT::i16:
10496     case MVT::i64:
10497       // r + r
10498       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10499         return true;
10500       return false;
10501
10502     case MVT::isVoid:
10503       // Note, we allow "void" uses (basically, uses that aren't loads or
10504       // stores), because arm allows folding a scale into many arithmetic
10505       // operations.  This should be made more precise and revisited later.
10506
10507       // Allow r << imm, but the imm has to be a multiple of two.
10508       if (Scale & 1) return false;
10509       return isPowerOf2_32(Scale);
10510     }
10511   }
10512   return true;
10513 }
10514
10515 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10516 /// icmp immediate, that is the target has icmp instructions which can compare
10517 /// a register against the immediate without having to materialize the
10518 /// immediate into a register.
10519 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10520   // Thumb2 and ARM modes can use cmn for negative immediates.
10521   if (!Subtarget->isThumb())
10522     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10523   if (Subtarget->isThumb2())
10524     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10525   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10526   return Imm >= 0 && Imm <= 255;
10527 }
10528
10529 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10530 /// *or sub* immediate, that is the target has add or sub instructions which can
10531 /// add a register with the immediate without having to materialize the
10532 /// immediate into a register.
10533 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10534   // Same encoding for add/sub, just flip the sign.
10535   int64_t AbsImm = llvm::abs64(Imm);
10536   if (!Subtarget->isThumb())
10537     return ARM_AM::getSOImmVal(AbsImm) != -1;
10538   if (Subtarget->isThumb2())
10539     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10540   // Thumb1 only has 8-bit unsigned immediate.
10541   return AbsImm >= 0 && AbsImm <= 255;
10542 }
10543
10544 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10545                                       bool isSEXTLoad, SDValue &Base,
10546                                       SDValue &Offset, bool &isInc,
10547                                       SelectionDAG &DAG) {
10548   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10549     return false;
10550
10551   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10552     // AddressingMode 3
10553     Base = Ptr->getOperand(0);
10554     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10555       int RHSC = (int)RHS->getZExtValue();
10556       if (RHSC < 0 && RHSC > -256) {
10557         assert(Ptr->getOpcode() == ISD::ADD);
10558         isInc = false;
10559         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10560         return true;
10561       }
10562     }
10563     isInc = (Ptr->getOpcode() == ISD::ADD);
10564     Offset = Ptr->getOperand(1);
10565     return true;
10566   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10567     // AddressingMode 2
10568     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10569       int RHSC = (int)RHS->getZExtValue();
10570       if (RHSC < 0 && RHSC > -0x1000) {
10571         assert(Ptr->getOpcode() == ISD::ADD);
10572         isInc = false;
10573         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10574         Base = Ptr->getOperand(0);
10575         return true;
10576       }
10577     }
10578
10579     if (Ptr->getOpcode() == ISD::ADD) {
10580       isInc = true;
10581       ARM_AM::ShiftOpc ShOpcVal=
10582         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10583       if (ShOpcVal != ARM_AM::no_shift) {
10584         Base = Ptr->getOperand(1);
10585         Offset = Ptr->getOperand(0);
10586       } else {
10587         Base = Ptr->getOperand(0);
10588         Offset = Ptr->getOperand(1);
10589       }
10590       return true;
10591     }
10592
10593     isInc = (Ptr->getOpcode() == ISD::ADD);
10594     Base = Ptr->getOperand(0);
10595     Offset = Ptr->getOperand(1);
10596     return true;
10597   }
10598
10599   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10600   return false;
10601 }
10602
10603 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10604                                      bool isSEXTLoad, SDValue &Base,
10605                                      SDValue &Offset, bool &isInc,
10606                                      SelectionDAG &DAG) {
10607   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10608     return false;
10609
10610   Base = Ptr->getOperand(0);
10611   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10612     int RHSC = (int)RHS->getZExtValue();
10613     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10614       assert(Ptr->getOpcode() == ISD::ADD);
10615       isInc = false;
10616       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10617       return true;
10618     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10619       isInc = Ptr->getOpcode() == ISD::ADD;
10620       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10621       return true;
10622     }
10623   }
10624
10625   return false;
10626 }
10627
10628 /// getPreIndexedAddressParts - returns true by value, base pointer and
10629 /// offset pointer and addressing mode by reference if the node's address
10630 /// can be legally represented as pre-indexed load / store address.
10631 bool
10632 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10633                                              SDValue &Offset,
10634                                              ISD::MemIndexedMode &AM,
10635                                              SelectionDAG &DAG) const {
10636   if (Subtarget->isThumb1Only())
10637     return false;
10638
10639   EVT VT;
10640   SDValue Ptr;
10641   bool isSEXTLoad = false;
10642   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10643     Ptr = LD->getBasePtr();
10644     VT  = LD->getMemoryVT();
10645     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10646   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10647     Ptr = ST->getBasePtr();
10648     VT  = ST->getMemoryVT();
10649   } else
10650     return false;
10651
10652   bool isInc;
10653   bool isLegal = false;
10654   if (Subtarget->isThumb2())
10655     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10656                                        Offset, isInc, DAG);
10657   else
10658     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10659                                         Offset, isInc, DAG);
10660   if (!isLegal)
10661     return false;
10662
10663   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10664   return true;
10665 }
10666
10667 /// getPostIndexedAddressParts - returns true by value, base pointer and
10668 /// offset pointer and addressing mode by reference if this node can be
10669 /// combined with a load / store to form a post-indexed load / store.
10670 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10671                                                    SDValue &Base,
10672                                                    SDValue &Offset,
10673                                                    ISD::MemIndexedMode &AM,
10674                                                    SelectionDAG &DAG) const {
10675   if (Subtarget->isThumb1Only())
10676     return false;
10677
10678   EVT VT;
10679   SDValue Ptr;
10680   bool isSEXTLoad = false;
10681   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10682     VT  = LD->getMemoryVT();
10683     Ptr = LD->getBasePtr();
10684     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10685   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10686     VT  = ST->getMemoryVT();
10687     Ptr = ST->getBasePtr();
10688   } else
10689     return false;
10690
10691   bool isInc;
10692   bool isLegal = false;
10693   if (Subtarget->isThumb2())
10694     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10695                                        isInc, DAG);
10696   else
10697     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10698                                         isInc, DAG);
10699   if (!isLegal)
10700     return false;
10701
10702   if (Ptr != Base) {
10703     // Swap base ptr and offset to catch more post-index load / store when
10704     // it's legal. In Thumb2 mode, offset must be an immediate.
10705     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10706         !Subtarget->isThumb2())
10707       std::swap(Base, Offset);
10708
10709     // Post-indexed load / store update the base pointer.
10710     if (Ptr != Base)
10711       return false;
10712   }
10713
10714   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10715   return true;
10716 }
10717
10718 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10719                                                        APInt &KnownZero,
10720                                                        APInt &KnownOne,
10721                                                        const SelectionDAG &DAG,
10722                                                        unsigned Depth) const {
10723   unsigned BitWidth = KnownOne.getBitWidth();
10724   KnownZero = KnownOne = APInt(BitWidth, 0);
10725   switch (Op.getOpcode()) {
10726   default: break;
10727   case ARMISD::ADDC:
10728   case ARMISD::ADDE:
10729   case ARMISD::SUBC:
10730   case ARMISD::SUBE:
10731     // These nodes' second result is a boolean
10732     if (Op.getResNo() == 0)
10733       break;
10734     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10735     break;
10736   case ARMISD::CMOV: {
10737     // Bits are known zero/one if known on the LHS and RHS.
10738     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10739     if (KnownZero == 0 && KnownOne == 0) return;
10740
10741     APInt KnownZeroRHS, KnownOneRHS;
10742     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10743     KnownZero &= KnownZeroRHS;
10744     KnownOne  &= KnownOneRHS;
10745     return;
10746   }
10747   }
10748 }
10749
10750 //===----------------------------------------------------------------------===//
10751 //                           ARM Inline Assembly Support
10752 //===----------------------------------------------------------------------===//
10753
10754 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10755   // Looking for "rev" which is V6+.
10756   if (!Subtarget->hasV6Ops())
10757     return false;
10758
10759   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10760   std::string AsmStr = IA->getAsmString();
10761   SmallVector<StringRef, 4> AsmPieces;
10762   SplitString(AsmStr, AsmPieces, ";\n");
10763
10764   switch (AsmPieces.size()) {
10765   default: return false;
10766   case 1:
10767     AsmStr = AsmPieces[0];
10768     AsmPieces.clear();
10769     SplitString(AsmStr, AsmPieces, " \t,");
10770
10771     // rev $0, $1
10772     if (AsmPieces.size() == 3 &&
10773         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10774         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10775       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10776       if (Ty && Ty->getBitWidth() == 32)
10777         return IntrinsicLowering::LowerToByteSwap(CI);
10778     }
10779     break;
10780   }
10781
10782   return false;
10783 }
10784
10785 /// getConstraintType - Given a constraint letter, return the type of
10786 /// constraint it is for this target.
10787 ARMTargetLowering::ConstraintType
10788 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10789   if (Constraint.size() == 1) {
10790     switch (Constraint[0]) {
10791     default:  break;
10792     case 'l': return C_RegisterClass;
10793     case 'w': return C_RegisterClass;
10794     case 'h': return C_RegisterClass;
10795     case 'x': return C_RegisterClass;
10796     case 't': return C_RegisterClass;
10797     case 'j': return C_Other; // Constant for movw.
10798       // An address with a single base register. Due to the way we
10799       // currently handle addresses it is the same as an 'r' memory constraint.
10800     case 'Q': return C_Memory;
10801     }
10802   } else if (Constraint.size() == 2) {
10803     switch (Constraint[0]) {
10804     default: break;
10805     // All 'U+' constraints are addresses.
10806     case 'U': return C_Memory;
10807     }
10808   }
10809   return TargetLowering::getConstraintType(Constraint);
10810 }
10811
10812 /// Examine constraint type and operand type and determine a weight value.
10813 /// This object must already have been set up with the operand type
10814 /// and the current alternative constraint selected.
10815 TargetLowering::ConstraintWeight
10816 ARMTargetLowering::getSingleConstraintMatchWeight(
10817     AsmOperandInfo &info, const char *constraint) const {
10818   ConstraintWeight weight = CW_Invalid;
10819   Value *CallOperandVal = info.CallOperandVal;
10820     // If we don't have a value, we can't do a match,
10821     // but allow it at the lowest weight.
10822   if (CallOperandVal == NULL)
10823     return CW_Default;
10824   Type *type = CallOperandVal->getType();
10825   // Look at the constraint type.
10826   switch (*constraint) {
10827   default:
10828     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10829     break;
10830   case 'l':
10831     if (type->isIntegerTy()) {
10832       if (Subtarget->isThumb())
10833         weight = CW_SpecificReg;
10834       else
10835         weight = CW_Register;
10836     }
10837     break;
10838   case 'w':
10839     if (type->isFloatingPointTy())
10840       weight = CW_Register;
10841     break;
10842   }
10843   return weight;
10844 }
10845
10846 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10847 RCPair
10848 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10849                                                 MVT VT) const {
10850   if (Constraint.size() == 1) {
10851     // GCC ARM Constraint Letters
10852     switch (Constraint[0]) {
10853     case 'l': // Low regs or general regs.
10854       if (Subtarget->isThumb())
10855         return RCPair(0U, &ARM::tGPRRegClass);
10856       return RCPair(0U, &ARM::GPRRegClass);
10857     case 'h': // High regs or no regs.
10858       if (Subtarget->isThumb())
10859         return RCPair(0U, &ARM::hGPRRegClass);
10860       break;
10861     case 'r':
10862       return RCPair(0U, &ARM::GPRRegClass);
10863     case 'w':
10864       if (VT == MVT::Other)
10865         break;
10866       if (VT == MVT::f32)
10867         return RCPair(0U, &ARM::SPRRegClass);
10868       if (VT.getSizeInBits() == 64)
10869         return RCPair(0U, &ARM::DPRRegClass);
10870       if (VT.getSizeInBits() == 128)
10871         return RCPair(0U, &ARM::QPRRegClass);
10872       break;
10873     case 'x':
10874       if (VT == MVT::Other)
10875         break;
10876       if (VT == MVT::f32)
10877         return RCPair(0U, &ARM::SPR_8RegClass);
10878       if (VT.getSizeInBits() == 64)
10879         return RCPair(0U, &ARM::DPR_8RegClass);
10880       if (VT.getSizeInBits() == 128)
10881         return RCPair(0U, &ARM::QPR_8RegClass);
10882       break;
10883     case 't':
10884       if (VT == MVT::f32)
10885         return RCPair(0U, &ARM::SPRRegClass);
10886       break;
10887     }
10888   }
10889   if (StringRef("{cc}").equals_lower(Constraint))
10890     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10891
10892   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10893 }
10894
10895 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10896 /// vector.  If it is invalid, don't add anything to Ops.
10897 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10898                                                      std::string &Constraint,
10899                                                      std::vector<SDValue>&Ops,
10900                                                      SelectionDAG &DAG) const {
10901   SDValue Result(0, 0);
10902
10903   // Currently only support length 1 constraints.
10904   if (Constraint.length() != 1) return;
10905
10906   char ConstraintLetter = Constraint[0];
10907   switch (ConstraintLetter) {
10908   default: break;
10909   case 'j':
10910   case 'I': case 'J': case 'K': case 'L':
10911   case 'M': case 'N': case 'O':
10912     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10913     if (!C)
10914       return;
10915
10916     int64_t CVal64 = C->getSExtValue();
10917     int CVal = (int) CVal64;
10918     // None of these constraints allow values larger than 32 bits.  Check
10919     // that the value fits in an int.
10920     if (CVal != CVal64)
10921       return;
10922
10923     switch (ConstraintLetter) {
10924       case 'j':
10925         // Constant suitable for movw, must be between 0 and
10926         // 65535.
10927         if (Subtarget->hasV6T2Ops())
10928           if (CVal >= 0 && CVal <= 65535)
10929             break;
10930         return;
10931       case 'I':
10932         if (Subtarget->isThumb1Only()) {
10933           // This must be a constant between 0 and 255, for ADD
10934           // immediates.
10935           if (CVal >= 0 && CVal <= 255)
10936             break;
10937         } else if (Subtarget->isThumb2()) {
10938           // A constant that can be used as an immediate value in a
10939           // data-processing instruction.
10940           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10941             break;
10942         } else {
10943           // A constant that can be used as an immediate value in a
10944           // data-processing instruction.
10945           if (ARM_AM::getSOImmVal(CVal) != -1)
10946             break;
10947         }
10948         return;
10949
10950       case 'J':
10951         if (Subtarget->isThumb()) {  // FIXME thumb2
10952           // This must be a constant between -255 and -1, for negated ADD
10953           // immediates. This can be used in GCC with an "n" modifier that
10954           // prints the negated value, for use with SUB instructions. It is
10955           // not useful otherwise but is implemented for compatibility.
10956           if (CVal >= -255 && CVal <= -1)
10957             break;
10958         } else {
10959           // This must be a constant between -4095 and 4095. It is not clear
10960           // what this constraint is intended for. Implemented for
10961           // compatibility with GCC.
10962           if (CVal >= -4095 && CVal <= 4095)
10963             break;
10964         }
10965         return;
10966
10967       case 'K':
10968         if (Subtarget->isThumb1Only()) {
10969           // A 32-bit value where only one byte has a nonzero value. Exclude
10970           // zero to match GCC. This constraint is used by GCC internally for
10971           // constants that can be loaded with a move/shift combination.
10972           // It is not useful otherwise but is implemented for compatibility.
10973           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10974             break;
10975         } else if (Subtarget->isThumb2()) {
10976           // A constant whose bitwise inverse can be used as an immediate
10977           // value in a data-processing instruction. This can be used in GCC
10978           // with a "B" modifier that prints the inverted value, for use with
10979           // BIC and MVN instructions. It is not useful otherwise but is
10980           // implemented for compatibility.
10981           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10982             break;
10983         } else {
10984           // A constant whose bitwise inverse can be used as an immediate
10985           // value in a data-processing instruction. This can be used in GCC
10986           // with a "B" modifier that prints the inverted value, for use with
10987           // BIC and MVN instructions. It is not useful otherwise but is
10988           // implemented for compatibility.
10989           if (ARM_AM::getSOImmVal(~CVal) != -1)
10990             break;
10991         }
10992         return;
10993
10994       case 'L':
10995         if (Subtarget->isThumb1Only()) {
10996           // This must be a constant between -7 and 7,
10997           // for 3-operand ADD/SUB immediate instructions.
10998           if (CVal >= -7 && CVal < 7)
10999             break;
11000         } else if (Subtarget->isThumb2()) {
11001           // A constant whose negation can be used as an immediate value in a
11002           // data-processing instruction. This can be used in GCC with an "n"
11003           // modifier that prints the negated value, for use with SUB
11004           // instructions. It is not useful otherwise but is implemented for
11005           // compatibility.
11006           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11007             break;
11008         } else {
11009           // A constant whose negation can be used as an immediate value in a
11010           // data-processing instruction. This can be used in GCC with an "n"
11011           // modifier that prints the negated value, for use with SUB
11012           // instructions. It is not useful otherwise but is implemented for
11013           // compatibility.
11014           if (ARM_AM::getSOImmVal(-CVal) != -1)
11015             break;
11016         }
11017         return;
11018
11019       case 'M':
11020         if (Subtarget->isThumb()) { // FIXME thumb2
11021           // This must be a multiple of 4 between 0 and 1020, for
11022           // ADD sp + immediate.
11023           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11024             break;
11025         } else {
11026           // A power of two or a constant between 0 and 32.  This is used in
11027           // GCC for the shift amount on shifted register operands, but it is
11028           // useful in general for any shift amounts.
11029           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11030             break;
11031         }
11032         return;
11033
11034       case 'N':
11035         if (Subtarget->isThumb()) {  // FIXME thumb2
11036           // This must be a constant between 0 and 31, for shift amounts.
11037           if (CVal >= 0 && CVal <= 31)
11038             break;
11039         }
11040         return;
11041
11042       case 'O':
11043         if (Subtarget->isThumb()) {  // FIXME thumb2
11044           // This must be a multiple of 4 between -508 and 508, for
11045           // ADD/SUB sp = sp + immediate.
11046           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11047             break;
11048         }
11049         return;
11050     }
11051     Result = DAG.getTargetConstant(CVal, Op.getValueType());
11052     break;
11053   }
11054
11055   if (Result.getNode()) {
11056     Ops.push_back(Result);
11057     return;
11058   }
11059   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11060 }
11061
11062 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11063   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
11064   unsigned Opcode = Op->getOpcode();
11065   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11066       "Invalid opcode for Div/Rem lowering");
11067   bool isSigned = (Opcode == ISD::SDIVREM);
11068   EVT VT = Op->getValueType(0);
11069   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11070
11071   RTLIB::Libcall LC;
11072   switch (VT.getSimpleVT().SimpleTy) {
11073   default: llvm_unreachable("Unexpected request for libcall!");
11074   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
11075   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11076   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11077   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11078   }
11079
11080   SDValue InChain = DAG.getEntryNode();
11081
11082   TargetLowering::ArgListTy Args;
11083   TargetLowering::ArgListEntry Entry;
11084   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
11085     EVT ArgVT = Op->getOperand(i).getValueType();
11086     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11087     Entry.Node = Op->getOperand(i);
11088     Entry.Ty = ArgTy;
11089     Entry.isSExt = isSigned;
11090     Entry.isZExt = !isSigned;
11091     Args.push_back(Entry);
11092   }
11093
11094   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11095                                          getPointerTy());
11096
11097   Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
11098
11099   SDLoc dl(Op);
11100   TargetLowering::
11101   CallLoweringInfo CLI(InChain, RetTy, isSigned, !isSigned, false, true,
11102                     0, getLibcallCallingConv(LC), /*isTailCall=*/false,
11103                     /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
11104                     Callee, Args, DAG, dl);
11105   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11106
11107   return CallInfo.first;
11108 }
11109
11110 bool
11111 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11112   // The ARM target isn't yet aware of offsets.
11113   return false;
11114 }
11115
11116 bool ARM::isBitFieldInvertedMask(unsigned v) {
11117   if (v == 0xffffffff)
11118     return false;
11119
11120   // there can be 1's on either or both "outsides", all the "inside"
11121   // bits must be 0's
11122   unsigned TO = CountTrailingOnes_32(v);
11123   unsigned LO = CountLeadingOnes_32(v);
11124   v = (v >> TO) << TO;
11125   v = (v << LO) >> LO;
11126   return v == 0;
11127 }
11128
11129 /// isFPImmLegal - Returns true if the target can instruction select the
11130 /// specified FP immediate natively. If false, the legalizer will
11131 /// materialize the FP immediate as a load from a constant pool.
11132 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11133   if (!Subtarget->hasVFP3())
11134     return false;
11135   if (VT == MVT::f32)
11136     return ARM_AM::getFP32Imm(Imm) != -1;
11137   if (VT == MVT::f64)
11138     return ARM_AM::getFP64Imm(Imm) != -1;
11139   return false;
11140 }
11141
11142 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11143 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11144 /// specified in the intrinsic calls.
11145 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11146                                            const CallInst &I,
11147                                            unsigned Intrinsic) const {
11148   switch (Intrinsic) {
11149   case Intrinsic::arm_neon_vld1:
11150   case Intrinsic::arm_neon_vld2:
11151   case Intrinsic::arm_neon_vld3:
11152   case Intrinsic::arm_neon_vld4:
11153   case Intrinsic::arm_neon_vld2lane:
11154   case Intrinsic::arm_neon_vld3lane:
11155   case Intrinsic::arm_neon_vld4lane: {
11156     Info.opc = ISD::INTRINSIC_W_CHAIN;
11157     // Conservatively set memVT to the entire set of vectors loaded.
11158     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
11159     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11160     Info.ptrVal = I.getArgOperand(0);
11161     Info.offset = 0;
11162     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11163     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11164     Info.vol = false; // volatile loads with NEON intrinsics not supported
11165     Info.readMem = true;
11166     Info.writeMem = false;
11167     return true;
11168   }
11169   case Intrinsic::arm_neon_vst1:
11170   case Intrinsic::arm_neon_vst2:
11171   case Intrinsic::arm_neon_vst3:
11172   case Intrinsic::arm_neon_vst4:
11173   case Intrinsic::arm_neon_vst2lane:
11174   case Intrinsic::arm_neon_vst3lane:
11175   case Intrinsic::arm_neon_vst4lane: {
11176     Info.opc = ISD::INTRINSIC_VOID;
11177     // Conservatively set memVT to the entire set of vectors stored.
11178     unsigned NumElts = 0;
11179     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11180       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11181       if (!ArgTy->isVectorTy())
11182         break;
11183       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
11184     }
11185     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11186     Info.ptrVal = I.getArgOperand(0);
11187     Info.offset = 0;
11188     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11189     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11190     Info.vol = false; // volatile stores with NEON intrinsics not supported
11191     Info.readMem = false;
11192     Info.writeMem = true;
11193     return true;
11194   }
11195   case Intrinsic::arm_ldrex: {
11196     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11197     Info.opc = ISD::INTRINSIC_W_CHAIN;
11198     Info.memVT = MVT::getVT(PtrTy->getElementType());
11199     Info.ptrVal = I.getArgOperand(0);
11200     Info.offset = 0;
11201     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11202     Info.vol = true;
11203     Info.readMem = true;
11204     Info.writeMem = false;
11205     return true;
11206   }
11207   case Intrinsic::arm_strex: {
11208     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11209     Info.opc = ISD::INTRINSIC_W_CHAIN;
11210     Info.memVT = MVT::getVT(PtrTy->getElementType());
11211     Info.ptrVal = I.getArgOperand(1);
11212     Info.offset = 0;
11213     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11214     Info.vol = true;
11215     Info.readMem = false;
11216     Info.writeMem = true;
11217     return true;
11218   }
11219   case Intrinsic::arm_strexd: {
11220     Info.opc = ISD::INTRINSIC_W_CHAIN;
11221     Info.memVT = MVT::i64;
11222     Info.ptrVal = I.getArgOperand(2);
11223     Info.offset = 0;
11224     Info.align = 8;
11225     Info.vol = true;
11226     Info.readMem = false;
11227     Info.writeMem = true;
11228     return true;
11229   }
11230   case Intrinsic::arm_ldrexd: {
11231     Info.opc = ISD::INTRINSIC_W_CHAIN;
11232     Info.memVT = MVT::i64;
11233     Info.ptrVal = I.getArgOperand(0);
11234     Info.offset = 0;
11235     Info.align = 8;
11236     Info.vol = true;
11237     Info.readMem = true;
11238     Info.writeMem = false;
11239     return true;
11240   }
11241   default:
11242     break;
11243   }
11244
11245   return false;
11246 }