Legalize: Improve legalization of long vector extends.
[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   // We have target-specific dag combine patterns for the following nodes:
874   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
875   setTargetDAGCombine(ISD::ADD);
876   setTargetDAGCombine(ISD::SUB);
877   setTargetDAGCombine(ISD::MUL);
878   setTargetDAGCombine(ISD::AND);
879   setTargetDAGCombine(ISD::OR);
880   setTargetDAGCombine(ISD::XOR);
881
882   if (Subtarget->hasV6Ops())
883     setTargetDAGCombine(ISD::SRL);
884
885   setStackPointerRegisterToSaveRestore(ARM::SP);
886
887   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
888       !Subtarget->hasVFP2())
889     setSchedulingPreference(Sched::RegPressure);
890   else
891     setSchedulingPreference(Sched::Hybrid);
892
893   //// temporary - rewrite interface to use type
894   MaxStoresPerMemset = 8;
895   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
896   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
897   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
898   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
899   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
900
901   // On ARM arguments smaller than 4 bytes are extended, so all arguments
902   // are at least 4 bytes aligned.
903   setMinStackArgumentAlignment(4);
904
905   // Prefer likely predicted branches to selects on out-of-order cores.
906   PredictableSelectIsExpensive = Subtarget->isLikeA9();
907
908   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
909 }
910
911 static void getExclusiveOperation(unsigned Size, AtomicOrdering Ord,
912                                   bool isThumb2, unsigned &LdrOpc,
913                                   unsigned &StrOpc) {
914   static const unsigned LoadBares[4][2] =  {{ARM::LDREXB, ARM::t2LDREXB},
915                                             {ARM::LDREXH, ARM::t2LDREXH},
916                                             {ARM::LDREX,  ARM::t2LDREX},
917                                             {ARM::LDREXD, ARM::t2LDREXD}};
918   static const unsigned LoadAcqs[4][2] =   {{ARM::LDAEXB, ARM::t2LDAEXB},
919                                             {ARM::LDAEXH, ARM::t2LDAEXH},
920                                             {ARM::LDAEX,  ARM::t2LDAEX},
921                                             {ARM::LDAEXD, ARM::t2LDAEXD}};
922   static const unsigned StoreBares[4][2] = {{ARM::STREXB, ARM::t2STREXB},
923                                             {ARM::STREXH, ARM::t2STREXH},
924                                             {ARM::STREX,  ARM::t2STREX},
925                                             {ARM::STREXD, ARM::t2STREXD}};
926   static const unsigned StoreRels[4][2] =  {{ARM::STLEXB, ARM::t2STLEXB},
927                                             {ARM::STLEXH, ARM::t2STLEXH},
928                                             {ARM::STLEX,  ARM::t2STLEX},
929                                             {ARM::STLEXD, ARM::t2STLEXD}};
930
931   const unsigned (*LoadOps)[2], (*StoreOps)[2];
932   if (Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent)
933     LoadOps = LoadAcqs;
934   else
935     LoadOps = LoadBares;
936
937   if (Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent)
938     StoreOps = StoreRels;
939   else
940     StoreOps = StoreBares;
941
942   assert(isPowerOf2_32(Size) && Size <= 8 &&
943          "unsupported size for atomic binary op!");
944
945   LdrOpc = LoadOps[Log2_32(Size)][isThumb2];
946   StrOpc = StoreOps[Log2_32(Size)][isThumb2];
947 }
948
949 // FIXME: It might make sense to define the representative register class as the
950 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
951 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
952 // SPR's representative would be DPR_VFP2. This should work well if register
953 // pressure tracking were modified such that a register use would increment the
954 // pressure of the register class's representative and all of it's super
955 // classes' representatives transitively. We have not implemented this because
956 // of the difficulty prior to coalescing of modeling operand register classes
957 // due to the common occurrence of cross class copies and subregister insertions
958 // and extractions.
959 std::pair<const TargetRegisterClass*, uint8_t>
960 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
961   const TargetRegisterClass *RRC = 0;
962   uint8_t Cost = 1;
963   switch (VT.SimpleTy) {
964   default:
965     return TargetLowering::findRepresentativeClass(VT);
966   // Use DPR as representative register class for all floating point
967   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
968   // the cost is 1 for both f32 and f64.
969   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
970   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
971     RRC = &ARM::DPRRegClass;
972     // When NEON is used for SP, only half of the register file is available
973     // because operations that define both SP and DP results will be constrained
974     // to the VFP2 class (D0-D15). We currently model this constraint prior to
975     // coalescing by double-counting the SP regs. See the FIXME above.
976     if (Subtarget->useNEONForSinglePrecisionFP())
977       Cost = 2;
978     break;
979   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
980   case MVT::v4f32: case MVT::v2f64:
981     RRC = &ARM::DPRRegClass;
982     Cost = 2;
983     break;
984   case MVT::v4i64:
985     RRC = &ARM::DPRRegClass;
986     Cost = 4;
987     break;
988   case MVT::v8i64:
989     RRC = &ARM::DPRRegClass;
990     Cost = 8;
991     break;
992   }
993   return std::make_pair(RRC, Cost);
994 }
995
996 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
997   switch (Opcode) {
998   default: return 0;
999   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1000   case ARMISD::WrapperDYN:    return "ARMISD::WrapperDYN";
1001   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1002   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1003   case ARMISD::CALL:          return "ARMISD::CALL";
1004   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1005   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1006   case ARMISD::tCALL:         return "ARMISD::tCALL";
1007   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1008   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1009   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1010   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1011   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1012   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1013   case ARMISD::CMP:           return "ARMISD::CMP";
1014   case ARMISD::CMN:           return "ARMISD::CMN";
1015   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1016   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1017   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1018   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1019   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1020
1021   case ARMISD::CMOV:          return "ARMISD::CMOV";
1022
1023   case ARMISD::RBIT:          return "ARMISD::RBIT";
1024
1025   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
1026   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
1027   case ARMISD::SITOF:         return "ARMISD::SITOF";
1028   case ARMISD::UITOF:         return "ARMISD::UITOF";
1029
1030   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1031   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1032   case ARMISD::RRX:           return "ARMISD::RRX";
1033
1034   case ARMISD::ADDC:          return "ARMISD::ADDC";
1035   case ARMISD::ADDE:          return "ARMISD::ADDE";
1036   case ARMISD::SUBC:          return "ARMISD::SUBC";
1037   case ARMISD::SUBE:          return "ARMISD::SUBE";
1038
1039   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1040   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1041
1042   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1043   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1044
1045   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1046
1047   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1048
1049   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1050
1051   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1052
1053   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1054
1055   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1056   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1057   case ARMISD::VCGE:          return "ARMISD::VCGE";
1058   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1059   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1060   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1061   case ARMISD::VCGT:          return "ARMISD::VCGT";
1062   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1063   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1064   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1065   case ARMISD::VTST:          return "ARMISD::VTST";
1066
1067   case ARMISD::VSHL:          return "ARMISD::VSHL";
1068   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1069   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1070   case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
1071   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
1072   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
1073   case ARMISD::VSHRN:         return "ARMISD::VSHRN";
1074   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1075   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1076   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1077   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1078   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1079   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1080   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1081   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1082   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1083   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1084   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1085   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1086   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1087   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1088   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1089   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1090   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1091   case ARMISD::VDUP:          return "ARMISD::VDUP";
1092   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1093   case ARMISD::VEXT:          return "ARMISD::VEXT";
1094   case ARMISD::VREV64:        return "ARMISD::VREV64";
1095   case ARMISD::VREV32:        return "ARMISD::VREV32";
1096   case ARMISD::VREV16:        return "ARMISD::VREV16";
1097   case ARMISD::VZIP:          return "ARMISD::VZIP";
1098   case ARMISD::VUZP:          return "ARMISD::VUZP";
1099   case ARMISD::VTRN:          return "ARMISD::VTRN";
1100   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1101   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1102   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1103   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1104   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1105   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1106   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1107   case ARMISD::FMAX:          return "ARMISD::FMAX";
1108   case ARMISD::FMIN:          return "ARMISD::FMIN";
1109   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1110   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1111   case ARMISD::BFI:           return "ARMISD::BFI";
1112   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1113   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1114   case ARMISD::VBSL:          return "ARMISD::VBSL";
1115   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1116   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1117   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1118   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1119   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1120   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1121   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1122   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1123   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1124   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1125   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1126   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1127   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1128   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1129   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1130   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1131   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1132   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1133   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1134   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1135   }
1136 }
1137
1138 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1139   if (!VT.isVector()) return getPointerTy();
1140   return VT.changeVectorElementTypeToInteger();
1141 }
1142
1143 /// getRegClassFor - Return the register class that should be used for the
1144 /// specified value type.
1145 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1146   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1147   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1148   // load / store 4 to 8 consecutive D registers.
1149   if (Subtarget->hasNEON()) {
1150     if (VT == MVT::v4i64)
1151       return &ARM::QQPRRegClass;
1152     if (VT == MVT::v8i64)
1153       return &ARM::QQQQPRRegClass;
1154   }
1155   return TargetLowering::getRegClassFor(VT);
1156 }
1157
1158 // Create a fast isel object.
1159 FastISel *
1160 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1161                                   const TargetLibraryInfo *libInfo) const {
1162   return ARM::createFastISel(funcInfo, libInfo);
1163 }
1164
1165 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1166 /// be used for loads / stores from the global.
1167 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1168   return (Subtarget->isThumb1Only() ? 127 : 4095);
1169 }
1170
1171 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1172   unsigned NumVals = N->getNumValues();
1173   if (!NumVals)
1174     return Sched::RegPressure;
1175
1176   for (unsigned i = 0; i != NumVals; ++i) {
1177     EVT VT = N->getValueType(i);
1178     if (VT == MVT::Glue || VT == MVT::Other)
1179       continue;
1180     if (VT.isFloatingPoint() || VT.isVector())
1181       return Sched::ILP;
1182   }
1183
1184   if (!N->isMachineOpcode())
1185     return Sched::RegPressure;
1186
1187   // Load are scheduled for latency even if there instruction itinerary
1188   // is not available.
1189   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1190   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1191
1192   if (MCID.getNumDefs() == 0)
1193     return Sched::RegPressure;
1194   if (!Itins->isEmpty() &&
1195       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1196     return Sched::ILP;
1197
1198   return Sched::RegPressure;
1199 }
1200
1201 //===----------------------------------------------------------------------===//
1202 // Lowering Code
1203 //===----------------------------------------------------------------------===//
1204
1205 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1206 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1207   switch (CC) {
1208   default: llvm_unreachable("Unknown condition code!");
1209   case ISD::SETNE:  return ARMCC::NE;
1210   case ISD::SETEQ:  return ARMCC::EQ;
1211   case ISD::SETGT:  return ARMCC::GT;
1212   case ISD::SETGE:  return ARMCC::GE;
1213   case ISD::SETLT:  return ARMCC::LT;
1214   case ISD::SETLE:  return ARMCC::LE;
1215   case ISD::SETUGT: return ARMCC::HI;
1216   case ISD::SETUGE: return ARMCC::HS;
1217   case ISD::SETULT: return ARMCC::LO;
1218   case ISD::SETULE: return ARMCC::LS;
1219   }
1220 }
1221
1222 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1223 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1224                         ARMCC::CondCodes &CondCode2) {
1225   CondCode2 = ARMCC::AL;
1226   switch (CC) {
1227   default: llvm_unreachable("Unknown FP condition!");
1228   case ISD::SETEQ:
1229   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1230   case ISD::SETGT:
1231   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1232   case ISD::SETGE:
1233   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1234   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1235   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1236   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1237   case ISD::SETO:   CondCode = ARMCC::VC; break;
1238   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1239   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1240   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1241   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1242   case ISD::SETLT:
1243   case ISD::SETULT: CondCode = ARMCC::LT; break;
1244   case ISD::SETLE:
1245   case ISD::SETULE: CondCode = ARMCC::LE; break;
1246   case ISD::SETNE:
1247   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1248   }
1249 }
1250
1251 //===----------------------------------------------------------------------===//
1252 //                      Calling Convention Implementation
1253 //===----------------------------------------------------------------------===//
1254
1255 #include "ARMGenCallingConv.inc"
1256
1257 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1258 /// given CallingConvention value.
1259 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1260                                                  bool Return,
1261                                                  bool isVarArg) const {
1262   switch (CC) {
1263   default:
1264     llvm_unreachable("Unsupported calling convention");
1265   case CallingConv::Fast:
1266     if (Subtarget->hasVFP2() && !isVarArg) {
1267       if (!Subtarget->isAAPCS_ABI())
1268         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1269       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1270       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1271     }
1272     // Fallthrough
1273   case CallingConv::C: {
1274     // Use target triple & subtarget features to do actual dispatch.
1275     if (!Subtarget->isAAPCS_ABI())
1276       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1277     else if (Subtarget->hasVFP2() &&
1278              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1279              !isVarArg)
1280       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1281     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1282   }
1283   case CallingConv::ARM_AAPCS_VFP:
1284     if (!isVarArg)
1285       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1286     // Fallthrough
1287   case CallingConv::ARM_AAPCS:
1288     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1289   case CallingConv::ARM_APCS:
1290     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1291   case CallingConv::GHC:
1292     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1293   }
1294 }
1295
1296 /// LowerCallResult - Lower the result values of a call into the
1297 /// appropriate copies out of appropriate physical registers.
1298 SDValue
1299 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1300                                    CallingConv::ID CallConv, bool isVarArg,
1301                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1302                                    SDLoc dl, SelectionDAG &DAG,
1303                                    SmallVectorImpl<SDValue> &InVals,
1304                                    bool isThisReturn, SDValue ThisVal) const {
1305
1306   // Assign locations to each value returned by this call.
1307   SmallVector<CCValAssign, 16> RVLocs;
1308   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1309                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1310   CCInfo.AnalyzeCallResult(Ins,
1311                            CCAssignFnForNode(CallConv, /* Return*/ true,
1312                                              isVarArg));
1313
1314   // Copy all of the result registers out of their specified physreg.
1315   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1316     CCValAssign VA = RVLocs[i];
1317
1318     // Pass 'this' value directly from the argument to return value, to avoid
1319     // reg unit interference
1320     if (i == 0 && isThisReturn) {
1321       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1322              "unexpected return calling convention register assignment");
1323       InVals.push_back(ThisVal);
1324       continue;
1325     }
1326
1327     SDValue Val;
1328     if (VA.needsCustom()) {
1329       // Handle f64 or half of a v2f64.
1330       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1331                                       InFlag);
1332       Chain = Lo.getValue(1);
1333       InFlag = Lo.getValue(2);
1334       VA = RVLocs[++i]; // skip ahead to next loc
1335       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1336                                       InFlag);
1337       Chain = Hi.getValue(1);
1338       InFlag = Hi.getValue(2);
1339       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1340
1341       if (VA.getLocVT() == MVT::v2f64) {
1342         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1343         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1344                           DAG.getConstant(0, MVT::i32));
1345
1346         VA = RVLocs[++i]; // skip ahead to next loc
1347         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1348         Chain = Lo.getValue(1);
1349         InFlag = Lo.getValue(2);
1350         VA = RVLocs[++i]; // skip ahead to next loc
1351         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1352         Chain = Hi.getValue(1);
1353         InFlag = Hi.getValue(2);
1354         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1355         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1356                           DAG.getConstant(1, MVT::i32));
1357       }
1358     } else {
1359       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1360                                InFlag);
1361       Chain = Val.getValue(1);
1362       InFlag = Val.getValue(2);
1363     }
1364
1365     switch (VA.getLocInfo()) {
1366     default: llvm_unreachable("Unknown loc info!");
1367     case CCValAssign::Full: break;
1368     case CCValAssign::BCvt:
1369       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1370       break;
1371     }
1372
1373     InVals.push_back(Val);
1374   }
1375
1376   return Chain;
1377 }
1378
1379 /// LowerMemOpCallTo - Store the argument to the stack.
1380 SDValue
1381 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1382                                     SDValue StackPtr, SDValue Arg,
1383                                     SDLoc dl, SelectionDAG &DAG,
1384                                     const CCValAssign &VA,
1385                                     ISD::ArgFlagsTy Flags) const {
1386   unsigned LocMemOffset = VA.getLocMemOffset();
1387   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1388   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1389   return DAG.getStore(Chain, dl, Arg, PtrOff,
1390                       MachinePointerInfo::getStack(LocMemOffset),
1391                       false, false, 0);
1392 }
1393
1394 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1395                                          SDValue Chain, SDValue &Arg,
1396                                          RegsToPassVector &RegsToPass,
1397                                          CCValAssign &VA, CCValAssign &NextVA,
1398                                          SDValue &StackPtr,
1399                                          SmallVectorImpl<SDValue> &MemOpChains,
1400                                          ISD::ArgFlagsTy Flags) const {
1401
1402   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1403                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1404   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1405
1406   if (NextVA.isRegLoc())
1407     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1408   else {
1409     assert(NextVA.isMemLoc());
1410     if (StackPtr.getNode() == 0)
1411       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1412
1413     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1414                                            dl, DAG, NextVA,
1415                                            Flags));
1416   }
1417 }
1418
1419 /// LowerCall - Lowering a call into a callseq_start <-
1420 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1421 /// nodes.
1422 SDValue
1423 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1424                              SmallVectorImpl<SDValue> &InVals) const {
1425   SelectionDAG &DAG                     = CLI.DAG;
1426   SDLoc &dl                          = CLI.DL;
1427   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1428   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1429   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1430   SDValue Chain                         = CLI.Chain;
1431   SDValue Callee                        = CLI.Callee;
1432   bool &isTailCall                      = CLI.IsTailCall;
1433   CallingConv::ID CallConv              = CLI.CallConv;
1434   bool doesNotRet                       = CLI.DoesNotReturn;
1435   bool isVarArg                         = CLI.IsVarArg;
1436
1437   MachineFunction &MF = DAG.getMachineFunction();
1438   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1439   bool isThisReturn   = false;
1440   bool isSibCall      = false;
1441   // Disable tail calls if they're not supported.
1442   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1443     isTailCall = false;
1444   if (isTailCall) {
1445     // Check if it's really possible to do a tail call.
1446     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1447                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1448                                                    Outs, OutVals, Ins, DAG);
1449     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1450     // detected sibcalls.
1451     if (isTailCall) {
1452       ++NumTailCalls;
1453       isSibCall = true;
1454     }
1455   }
1456
1457   // Analyze operands of the call, assigning locations to each operand.
1458   SmallVector<CCValAssign, 16> ArgLocs;
1459   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1460                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1461   CCInfo.AnalyzeCallOperands(Outs,
1462                              CCAssignFnForNode(CallConv, /* Return*/ false,
1463                                                isVarArg));
1464
1465   // Get a count of how many bytes are to be pushed on the stack.
1466   unsigned NumBytes = CCInfo.getNextStackOffset();
1467
1468   // For tail calls, memory operands are available in our caller's stack.
1469   if (isSibCall)
1470     NumBytes = 0;
1471
1472   // Adjust the stack pointer for the new arguments...
1473   // These operations are automatically eliminated by the prolog/epilog pass
1474   if (!isSibCall)
1475     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1476                                  dl);
1477
1478   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1479
1480   RegsToPassVector RegsToPass;
1481   SmallVector<SDValue, 8> MemOpChains;
1482
1483   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1484   // of tail call optimization, arguments are handled later.
1485   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1486        i != e;
1487        ++i, ++realArgIdx) {
1488     CCValAssign &VA = ArgLocs[i];
1489     SDValue Arg = OutVals[realArgIdx];
1490     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1491     bool isByVal = Flags.isByVal();
1492
1493     // Promote the value if needed.
1494     switch (VA.getLocInfo()) {
1495     default: llvm_unreachable("Unknown loc info!");
1496     case CCValAssign::Full: break;
1497     case CCValAssign::SExt:
1498       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1499       break;
1500     case CCValAssign::ZExt:
1501       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1502       break;
1503     case CCValAssign::AExt:
1504       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1505       break;
1506     case CCValAssign::BCvt:
1507       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1508       break;
1509     }
1510
1511     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1512     if (VA.needsCustom()) {
1513       if (VA.getLocVT() == MVT::v2f64) {
1514         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1515                                   DAG.getConstant(0, MVT::i32));
1516         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1517                                   DAG.getConstant(1, MVT::i32));
1518
1519         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1520                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1521
1522         VA = ArgLocs[++i]; // skip ahead to next loc
1523         if (VA.isRegLoc()) {
1524           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1525                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1526         } else {
1527           assert(VA.isMemLoc());
1528
1529           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1530                                                  dl, DAG, VA, Flags));
1531         }
1532       } else {
1533         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1534                          StackPtr, MemOpChains, Flags);
1535       }
1536     } else if (VA.isRegLoc()) {
1537       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1538         assert(VA.getLocVT() == MVT::i32 &&
1539                "unexpected calling convention register assignment");
1540         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1541                "unexpected use of 'returned'");
1542         isThisReturn = true;
1543       }
1544       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1545     } else if (isByVal) {
1546       assert(VA.isMemLoc());
1547       unsigned offset = 0;
1548
1549       // True if this byval aggregate will be split between registers
1550       // and memory.
1551       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1552       unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1553
1554       if (CurByValIdx < ByValArgsCount) {
1555
1556         unsigned RegBegin, RegEnd;
1557         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1558
1559         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1560         unsigned int i, j;
1561         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1562           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1563           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1564           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1565                                      MachinePointerInfo(),
1566                                      false, false, false,
1567                                      DAG.InferPtrAlignment(AddArg));
1568           MemOpChains.push_back(Load.getValue(1));
1569           RegsToPass.push_back(std::make_pair(j, Load));
1570         }
1571
1572         // If parameter size outsides register area, "offset" value
1573         // helps us to calculate stack slot for remained part properly.
1574         offset = RegEnd - RegBegin;
1575
1576         CCInfo.nextInRegsParam();
1577       }
1578
1579       if (Flags.getByValSize() > 4*offset) {
1580         unsigned LocMemOffset = VA.getLocMemOffset();
1581         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1582         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1583                                   StkPtrOff);
1584         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1585         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1586         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1587                                            MVT::i32);
1588         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1589
1590         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1591         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1592         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1593                                           Ops, array_lengthof(Ops)));
1594       }
1595     } else if (!isSibCall) {
1596       assert(VA.isMemLoc());
1597
1598       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1599                                              dl, DAG, VA, Flags));
1600     }
1601   }
1602
1603   if (!MemOpChains.empty())
1604     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1605                         &MemOpChains[0], MemOpChains.size());
1606
1607   // Build a sequence of copy-to-reg nodes chained together with token chain
1608   // and flag operands which copy the outgoing args into the appropriate regs.
1609   SDValue InFlag;
1610   // Tail call byval lowering might overwrite argument registers so in case of
1611   // tail call optimization the copies to registers are lowered later.
1612   if (!isTailCall)
1613     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1614       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1615                                RegsToPass[i].second, InFlag);
1616       InFlag = Chain.getValue(1);
1617     }
1618
1619   // For tail calls lower the arguments to the 'real' stack slot.
1620   if (isTailCall) {
1621     // Force all the incoming stack arguments to be loaded from the stack
1622     // before any new outgoing arguments are stored to the stack, because the
1623     // outgoing stack slots may alias the incoming argument stack slots, and
1624     // the alias isn't otherwise explicit. This is slightly more conservative
1625     // than necessary, because it means that each store effectively depends
1626     // on every argument instead of just those arguments it would clobber.
1627
1628     // Do not flag preceding copytoreg stuff together with the following stuff.
1629     InFlag = SDValue();
1630     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1631       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1632                                RegsToPass[i].second, InFlag);
1633       InFlag = Chain.getValue(1);
1634     }
1635     InFlag = SDValue();
1636   }
1637
1638   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1639   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1640   // node so that legalize doesn't hack it.
1641   bool isDirect = false;
1642   bool isARMFunc = false;
1643   bool isLocalARMFunc = false;
1644   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1645
1646   if (EnableARMLongCalls) {
1647     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1648             && "long-calls with non-static relocation model!");
1649     // Handle a global address or an external symbol. If it's not one of
1650     // those, the target's already in a register, so we don't need to do
1651     // anything extra.
1652     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1653       const GlobalValue *GV = G->getGlobal();
1654       // Create a constant pool entry for the callee address
1655       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1656       ARMConstantPoolValue *CPV =
1657         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1658
1659       // Get the address of the callee into a register
1660       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1661       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1662       Callee = DAG.getLoad(getPointerTy(), dl,
1663                            DAG.getEntryNode(), CPAddr,
1664                            MachinePointerInfo::getConstantPool(),
1665                            false, false, false, 0);
1666     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1667       const char *Sym = S->getSymbol();
1668
1669       // Create a constant pool entry for the callee address
1670       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1671       ARMConstantPoolValue *CPV =
1672         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1673                                       ARMPCLabelIndex, 0);
1674       // Get the address of the callee into a register
1675       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1676       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1677       Callee = DAG.getLoad(getPointerTy(), dl,
1678                            DAG.getEntryNode(), CPAddr,
1679                            MachinePointerInfo::getConstantPool(),
1680                            false, false, false, 0);
1681     }
1682   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1683     const GlobalValue *GV = G->getGlobal();
1684     isDirect = true;
1685     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1686     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1687                    getTargetMachine().getRelocationModel() != Reloc::Static;
1688     isARMFunc = !Subtarget->isThumb() || isStub;
1689     // ARM call to a local ARM function is predicable.
1690     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1691     // tBX takes a register source operand.
1692     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1693       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1694       ARMConstantPoolValue *CPV =
1695         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1696       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1697       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1698       Callee = DAG.getLoad(getPointerTy(), dl,
1699                            DAG.getEntryNode(), CPAddr,
1700                            MachinePointerInfo::getConstantPool(),
1701                            false, false, false, 0);
1702       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1703       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1704                            getPointerTy(), Callee, PICLabel);
1705     } else {
1706       // On ELF targets for PIC code, direct calls should go through the PLT
1707       unsigned OpFlags = 0;
1708       if (Subtarget->isTargetELF() &&
1709           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1710         OpFlags = ARMII::MO_PLT;
1711       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1712     }
1713   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1714     isDirect = true;
1715     bool isStub = Subtarget->isTargetDarwin() &&
1716                   getTargetMachine().getRelocationModel() != Reloc::Static;
1717     isARMFunc = !Subtarget->isThumb() || isStub;
1718     // tBX takes a register source operand.
1719     const char *Sym = S->getSymbol();
1720     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1721       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1722       ARMConstantPoolValue *CPV =
1723         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1724                                       ARMPCLabelIndex, 4);
1725       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1726       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1727       Callee = DAG.getLoad(getPointerTy(), dl,
1728                            DAG.getEntryNode(), CPAddr,
1729                            MachinePointerInfo::getConstantPool(),
1730                            false, false, false, 0);
1731       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1732       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1733                            getPointerTy(), Callee, PICLabel);
1734     } else {
1735       unsigned OpFlags = 0;
1736       // On ELF targets for PIC code, direct calls should go through the PLT
1737       if (Subtarget->isTargetELF() &&
1738                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1739         OpFlags = ARMII::MO_PLT;
1740       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1741     }
1742   }
1743
1744   // FIXME: handle tail calls differently.
1745   unsigned CallOpc;
1746   bool HasMinSizeAttr = MF.getFunction()->getAttributes().
1747     hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
1748   if (Subtarget->isThumb()) {
1749     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1750       CallOpc = ARMISD::CALL_NOLINK;
1751     else
1752       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1753   } else {
1754     if (!isDirect && !Subtarget->hasV5TOps())
1755       CallOpc = ARMISD::CALL_NOLINK;
1756     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1757                // Emit regular call when code size is the priority
1758                !HasMinSizeAttr)
1759       // "mov lr, pc; b _foo" to avoid confusing the RSP
1760       CallOpc = ARMISD::CALL_NOLINK;
1761     else
1762       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1763   }
1764
1765   std::vector<SDValue> Ops;
1766   Ops.push_back(Chain);
1767   Ops.push_back(Callee);
1768
1769   // Add argument registers to the end of the list so that they are known live
1770   // into the call.
1771   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1772     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1773                                   RegsToPass[i].second.getValueType()));
1774
1775   // Add a register mask operand representing the call-preserved registers.
1776   if (!isTailCall) {
1777     const uint32_t *Mask;
1778     const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1779     const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1780     if (isThisReturn) {
1781       // For 'this' returns, use the R0-preserving mask if applicable
1782       Mask = ARI->getThisReturnPreservedMask(CallConv);
1783       if (!Mask) {
1784         // Set isThisReturn to false if the calling convention is not one that
1785         // allows 'returned' to be modeled in this way, so LowerCallResult does
1786         // not try to pass 'this' straight through
1787         isThisReturn = false;
1788         Mask = ARI->getCallPreservedMask(CallConv);
1789       }
1790     } else
1791       Mask = ARI->getCallPreservedMask(CallConv);
1792
1793     assert(Mask && "Missing call preserved mask for calling convention");
1794     Ops.push_back(DAG.getRegisterMask(Mask));
1795   }
1796
1797   if (InFlag.getNode())
1798     Ops.push_back(InFlag);
1799
1800   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1801   if (isTailCall)
1802     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1803
1804   // Returns a chain and a flag for retval copy to use.
1805   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1806   InFlag = Chain.getValue(1);
1807
1808   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1809                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1810   if (!Ins.empty())
1811     InFlag = Chain.getValue(1);
1812
1813   // Handle result values, copying them out of physregs into vregs that we
1814   // return.
1815   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1816                          InVals, isThisReturn,
1817                          isThisReturn ? OutVals[0] : SDValue());
1818 }
1819
1820 /// HandleByVal - Every parameter *after* a byval parameter is passed
1821 /// on the stack.  Remember the next parameter register to allocate,
1822 /// and then confiscate the rest of the parameter registers to insure
1823 /// this.
1824 void
1825 ARMTargetLowering::HandleByVal(
1826     CCState *State, unsigned &size, unsigned Align) const {
1827   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1828   assert((State->getCallOrPrologue() == Prologue ||
1829           State->getCallOrPrologue() == Call) &&
1830          "unhandled ParmContext");
1831
1832   // For in-prologue parameters handling, we also introduce stack offset
1833   // for byval registers: see CallingConvLower.cpp, CCState::HandleByVal.
1834   // This behaviour outsides AAPCS rules (5.5 Parameters Passing) of how
1835   // NSAA should be evaluted (NSAA means "next stacked argument address").
1836   // So: NextStackOffset = NSAAOffset + SizeOfByValParamsStoredInRegs.
1837   // Then: NSAAOffset = NextStackOffset - SizeOfByValParamsStoredInRegs.
1838   unsigned NSAAOffset = State->getNextStackOffset();
1839   if (State->getCallOrPrologue() != Call) {
1840     for (unsigned i = 0, e = State->getInRegsParamsCount(); i != e; ++i) {
1841       unsigned RB, RE;
1842       State->getInRegsParamInfo(i, RB, RE);
1843       assert(NSAAOffset >= (RE-RB)*4 &&
1844              "Stack offset for byval regs doesn't introduced anymore?");
1845       NSAAOffset -= (RE-RB)*4;
1846     }
1847   }
1848   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1849     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1850       unsigned AlignInRegs = Align / 4;
1851       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1852       for (unsigned i = 0; i < Waste; ++i)
1853         reg = State->AllocateReg(GPRArgRegs, 4);
1854     }
1855     if (reg != 0) {
1856       unsigned excess = 4 * (ARM::R4 - reg);
1857
1858       // Special case when NSAA != SP and parameter size greater than size of
1859       // all remained GPR regs. In that case we can't split parameter, we must
1860       // send it to stack. We also must set NCRN to R4, so waste all
1861       // remained registers.
1862       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1863         while (State->AllocateReg(GPRArgRegs, 4))
1864           ;
1865         return;
1866       }
1867
1868       // First register for byval parameter is the first register that wasn't
1869       // allocated before this method call, so it would be "reg".
1870       // If parameter is small enough to be saved in range [reg, r4), then
1871       // the end (first after last) register would be reg + param-size-in-regs,
1872       // else parameter would be splitted between registers and stack,
1873       // end register would be r4 in this case.
1874       unsigned ByValRegBegin = reg;
1875       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1876       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1877       // Note, first register is allocated in the beginning of function already,
1878       // allocate remained amount of registers we need.
1879       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1880         State->AllocateReg(GPRArgRegs, 4);
1881       // At a call site, a byval parameter that is split between
1882       // registers and memory needs its size truncated here.  In a
1883       // function prologue, such byval parameters are reassembled in
1884       // memory, and are not truncated.
1885       if (State->getCallOrPrologue() == Call) {
1886         // Make remained size equal to 0 in case, when
1887         // the whole structure may be stored into registers.
1888         if (size < excess)
1889           size = 0;
1890         else
1891           size -= excess;
1892       }
1893     }
1894   }
1895 }
1896
1897 /// MatchingStackOffset - Return true if the given stack call argument is
1898 /// already available in the same position (relatively) of the caller's
1899 /// incoming argument stack.
1900 static
1901 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1902                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1903                          const TargetInstrInfo *TII) {
1904   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1905   int FI = INT_MAX;
1906   if (Arg.getOpcode() == ISD::CopyFromReg) {
1907     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1908     if (!TargetRegisterInfo::isVirtualRegister(VR))
1909       return false;
1910     MachineInstr *Def = MRI->getVRegDef(VR);
1911     if (!Def)
1912       return false;
1913     if (!Flags.isByVal()) {
1914       if (!TII->isLoadFromStackSlot(Def, FI))
1915         return false;
1916     } else {
1917       return false;
1918     }
1919   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1920     if (Flags.isByVal())
1921       // ByVal argument is passed in as a pointer but it's now being
1922       // dereferenced. e.g.
1923       // define @foo(%struct.X* %A) {
1924       //   tail call @bar(%struct.X* byval %A)
1925       // }
1926       return false;
1927     SDValue Ptr = Ld->getBasePtr();
1928     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1929     if (!FINode)
1930       return false;
1931     FI = FINode->getIndex();
1932   } else
1933     return false;
1934
1935   assert(FI != INT_MAX);
1936   if (!MFI->isFixedObjectIndex(FI))
1937     return false;
1938   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1939 }
1940
1941 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1942 /// for tail call optimization. Targets which want to do tail call
1943 /// optimization should implement this function.
1944 bool
1945 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1946                                                      CallingConv::ID CalleeCC,
1947                                                      bool isVarArg,
1948                                                      bool isCalleeStructRet,
1949                                                      bool isCallerStructRet,
1950                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1951                                     const SmallVectorImpl<SDValue> &OutVals,
1952                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1953                                                      SelectionDAG& DAG) const {
1954   const Function *CallerF = DAG.getMachineFunction().getFunction();
1955   CallingConv::ID CallerCC = CallerF->getCallingConv();
1956   bool CCMatch = CallerCC == CalleeCC;
1957
1958   // Look for obvious safe cases to perform tail call optimization that do not
1959   // require ABI changes. This is what gcc calls sibcall.
1960
1961   // Do not sibcall optimize vararg calls unless the call site is not passing
1962   // any arguments.
1963   if (isVarArg && !Outs.empty())
1964     return false;
1965
1966   // Exception-handling functions need a special set of instructions to indicate
1967   // a return to the hardware. Tail-calling another function would probably
1968   // break this.
1969   if (CallerF->hasFnAttribute("interrupt"))
1970     return false;
1971
1972   // Also avoid sibcall optimization if either caller or callee uses struct
1973   // return semantics.
1974   if (isCalleeStructRet || isCallerStructRet)
1975     return false;
1976
1977   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1978   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1979   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1980   // support in the assembler and linker to be used. This would need to be
1981   // fixed to fully support tail calls in Thumb1.
1982   //
1983   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1984   // LR.  This means if we need to reload LR, it takes an extra instructions,
1985   // which outweighs the value of the tail call; but here we don't know yet
1986   // whether LR is going to be used.  Probably the right approach is to
1987   // generate the tail call here and turn it back into CALL/RET in
1988   // emitEpilogue if LR is used.
1989
1990   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1991   // but we need to make sure there are enough registers; the only valid
1992   // registers are the 4 used for parameters.  We don't currently do this
1993   // case.
1994   if (Subtarget->isThumb1Only())
1995     return false;
1996
1997   // If the calling conventions do not match, then we'd better make sure the
1998   // results are returned in the same way as what the caller expects.
1999   if (!CCMatch) {
2000     SmallVector<CCValAssign, 16> RVLocs1;
2001     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2002                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
2003     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2004
2005     SmallVector<CCValAssign, 16> RVLocs2;
2006     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2007                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
2008     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2009
2010     if (RVLocs1.size() != RVLocs2.size())
2011       return false;
2012     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2013       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2014         return false;
2015       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2016         return false;
2017       if (RVLocs1[i].isRegLoc()) {
2018         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2019           return false;
2020       } else {
2021         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2022           return false;
2023       }
2024     }
2025   }
2026
2027   // If Caller's vararg or byval argument has been split between registers and
2028   // stack, do not perform tail call, since part of the argument is in caller's
2029   // local frame.
2030   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2031                                       getInfo<ARMFunctionInfo>();
2032   if (AFI_Caller->getArgRegsSaveSize())
2033     return false;
2034
2035   // If the callee takes no arguments then go on to check the results of the
2036   // call.
2037   if (!Outs.empty()) {
2038     // Check if stack adjustment is needed. For now, do not do this if any
2039     // argument is passed on the stack.
2040     SmallVector<CCValAssign, 16> ArgLocs;
2041     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2042                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
2043     CCInfo.AnalyzeCallOperands(Outs,
2044                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2045     if (CCInfo.getNextStackOffset()) {
2046       MachineFunction &MF = DAG.getMachineFunction();
2047
2048       // Check if the arguments are already laid out in the right way as
2049       // the caller's fixed stack objects.
2050       MachineFrameInfo *MFI = MF.getFrameInfo();
2051       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2052       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2053       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2054            i != e;
2055            ++i, ++realArgIdx) {
2056         CCValAssign &VA = ArgLocs[i];
2057         EVT RegVT = VA.getLocVT();
2058         SDValue Arg = OutVals[realArgIdx];
2059         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2060         if (VA.getLocInfo() == CCValAssign::Indirect)
2061           return false;
2062         if (VA.needsCustom()) {
2063           // f64 and vector types are split into multiple registers or
2064           // register/stack-slot combinations.  The types will not match
2065           // the registers; give up on memory f64 refs until we figure
2066           // out what to do about this.
2067           if (!VA.isRegLoc())
2068             return false;
2069           if (!ArgLocs[++i].isRegLoc())
2070             return false;
2071           if (RegVT == MVT::v2f64) {
2072             if (!ArgLocs[++i].isRegLoc())
2073               return false;
2074             if (!ArgLocs[++i].isRegLoc())
2075               return false;
2076           }
2077         } else if (!VA.isRegLoc()) {
2078           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2079                                    MFI, MRI, TII))
2080             return false;
2081         }
2082       }
2083     }
2084   }
2085
2086   return true;
2087 }
2088
2089 bool
2090 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2091                                   MachineFunction &MF, bool isVarArg,
2092                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2093                                   LLVMContext &Context) const {
2094   SmallVector<CCValAssign, 16> RVLocs;
2095   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2096   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2097                                                     isVarArg));
2098 }
2099
2100 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2101                                     SDLoc DL, SelectionDAG &DAG) {
2102   const MachineFunction &MF = DAG.getMachineFunction();
2103   const Function *F = MF.getFunction();
2104
2105   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2106
2107   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2108   // version of the "preferred return address". These offsets affect the return
2109   // instruction if this is a return from PL1 without hypervisor extensions.
2110   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2111   //    SWI:     0      "subs pc, lr, #0"
2112   //    ABORT:   +4     "subs pc, lr, #4"
2113   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2114   // UNDEF varies depending on where the exception came from ARM or Thumb
2115   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2116
2117   int64_t LROffset;
2118   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2119       IntKind == "ABORT")
2120     LROffset = 4;
2121   else if (IntKind == "SWI" || IntKind == "UNDEF")
2122     LROffset = 0;
2123   else
2124     report_fatal_error("Unsupported interrupt attribute. If present, value "
2125                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2126
2127   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2128
2129   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other,
2130                      RetOps.data(), RetOps.size());
2131 }
2132
2133 SDValue
2134 ARMTargetLowering::LowerReturn(SDValue Chain,
2135                                CallingConv::ID CallConv, bool isVarArg,
2136                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2137                                const SmallVectorImpl<SDValue> &OutVals,
2138                                SDLoc dl, SelectionDAG &DAG) const {
2139
2140   // CCValAssign - represent the assignment of the return value to a location.
2141   SmallVector<CCValAssign, 16> RVLocs;
2142
2143   // CCState - Info about the registers and stack slots.
2144   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2145                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2146
2147   // Analyze outgoing return values.
2148   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2149                                                isVarArg));
2150
2151   SDValue Flag;
2152   SmallVector<SDValue, 4> RetOps;
2153   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2154
2155   // Copy the result values into the output registers.
2156   for (unsigned i = 0, realRVLocIdx = 0;
2157        i != RVLocs.size();
2158        ++i, ++realRVLocIdx) {
2159     CCValAssign &VA = RVLocs[i];
2160     assert(VA.isRegLoc() && "Can only return in registers!");
2161
2162     SDValue Arg = OutVals[realRVLocIdx];
2163
2164     switch (VA.getLocInfo()) {
2165     default: llvm_unreachable("Unknown loc info!");
2166     case CCValAssign::Full: break;
2167     case CCValAssign::BCvt:
2168       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2169       break;
2170     }
2171
2172     if (VA.needsCustom()) {
2173       if (VA.getLocVT() == MVT::v2f64) {
2174         // Extract the first half and return it in two registers.
2175         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2176                                    DAG.getConstant(0, MVT::i32));
2177         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2178                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2179
2180         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
2181         Flag = Chain.getValue(1);
2182         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2183         VA = RVLocs[++i]; // skip ahead to next loc
2184         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2185                                  HalfGPRs.getValue(1), Flag);
2186         Flag = Chain.getValue(1);
2187         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2188         VA = RVLocs[++i]; // skip ahead to next loc
2189
2190         // Extract the 2nd half and fall through to handle it as an f64 value.
2191         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2192                           DAG.getConstant(1, MVT::i32));
2193       }
2194       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2195       // available.
2196       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2197                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
2198       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
2199       Flag = Chain.getValue(1);
2200       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2201       VA = RVLocs[++i]; // skip ahead to next loc
2202       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
2203                                Flag);
2204     } else
2205       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2206
2207     // Guarantee that all emitted copies are
2208     // stuck together, avoiding something bad.
2209     Flag = Chain.getValue(1);
2210     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2211   }
2212
2213   // Update chain and glue.
2214   RetOps[0] = Chain;
2215   if (Flag.getNode())
2216     RetOps.push_back(Flag);
2217
2218   // CPUs which aren't M-class use a special sequence to return from
2219   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2220   // though we use "subs pc, lr, #N").
2221   //
2222   // M-class CPUs actually use a normal return sequence with a special
2223   // (hardware-provided) value in LR, so the normal code path works.
2224   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2225       !Subtarget->isMClass()) {
2226     if (Subtarget->isThumb1Only())
2227       report_fatal_error("interrupt attribute is not supported in Thumb1");
2228     return LowerInterruptReturn(RetOps, dl, DAG);
2229   }
2230
2231   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
2232                      RetOps.data(), RetOps.size());
2233 }
2234
2235 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2236   if (N->getNumValues() != 1)
2237     return false;
2238   if (!N->hasNUsesOfValue(1, 0))
2239     return false;
2240
2241   SDValue TCChain = Chain;
2242   SDNode *Copy = *N->use_begin();
2243   if (Copy->getOpcode() == ISD::CopyToReg) {
2244     // If the copy has a glue operand, we conservatively assume it isn't safe to
2245     // perform a tail call.
2246     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2247       return false;
2248     TCChain = Copy->getOperand(0);
2249   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2250     SDNode *VMov = Copy;
2251     // f64 returned in a pair of GPRs.
2252     SmallPtrSet<SDNode*, 2> Copies;
2253     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2254          UI != UE; ++UI) {
2255       if (UI->getOpcode() != ISD::CopyToReg)
2256         return false;
2257       Copies.insert(*UI);
2258     }
2259     if (Copies.size() > 2)
2260       return false;
2261
2262     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2263          UI != UE; ++UI) {
2264       SDValue UseChain = UI->getOperand(0);
2265       if (Copies.count(UseChain.getNode()))
2266         // Second CopyToReg
2267         Copy = *UI;
2268       else
2269         // First CopyToReg
2270         TCChain = UseChain;
2271     }
2272   } else if (Copy->getOpcode() == ISD::BITCAST) {
2273     // f32 returned in a single GPR.
2274     if (!Copy->hasOneUse())
2275       return false;
2276     Copy = *Copy->use_begin();
2277     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2278       return false;
2279     TCChain = Copy->getOperand(0);
2280   } else {
2281     return false;
2282   }
2283
2284   bool HasRet = false;
2285   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2286        UI != UE; ++UI) {
2287     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2288         UI->getOpcode() != ARMISD::INTRET_FLAG)
2289       return false;
2290     HasRet = true;
2291   }
2292
2293   if (!HasRet)
2294     return false;
2295
2296   Chain = TCChain;
2297   return true;
2298 }
2299
2300 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2301   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2302     return false;
2303
2304   if (!CI->isTailCall())
2305     return false;
2306
2307   return !Subtarget->isThumb1Only();
2308 }
2309
2310 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2311 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2312 // one of the above mentioned nodes. It has to be wrapped because otherwise
2313 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2314 // be used to form addressing mode. These wrapped nodes will be selected
2315 // into MOVi.
2316 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2317   EVT PtrVT = Op.getValueType();
2318   // FIXME there is no actual debug info here
2319   SDLoc dl(Op);
2320   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2321   SDValue Res;
2322   if (CP->isMachineConstantPoolEntry())
2323     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2324                                     CP->getAlignment());
2325   else
2326     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2327                                     CP->getAlignment());
2328   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2329 }
2330
2331 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2332   return MachineJumpTableInfo::EK_Inline;
2333 }
2334
2335 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2336                                              SelectionDAG &DAG) const {
2337   MachineFunction &MF = DAG.getMachineFunction();
2338   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2339   unsigned ARMPCLabelIndex = 0;
2340   SDLoc DL(Op);
2341   EVT PtrVT = getPointerTy();
2342   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2343   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2344   SDValue CPAddr;
2345   if (RelocM == Reloc::Static) {
2346     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2347   } else {
2348     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2349     ARMPCLabelIndex = AFI->createPICLabelUId();
2350     ARMConstantPoolValue *CPV =
2351       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2352                                       ARMCP::CPBlockAddress, PCAdj);
2353     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2354   }
2355   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2356   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2357                                MachinePointerInfo::getConstantPool(),
2358                                false, false, false, 0);
2359   if (RelocM == Reloc::Static)
2360     return Result;
2361   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2362   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2363 }
2364
2365 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2366 SDValue
2367 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2368                                                  SelectionDAG &DAG) const {
2369   SDLoc dl(GA);
2370   EVT PtrVT = getPointerTy();
2371   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2372   MachineFunction &MF = DAG.getMachineFunction();
2373   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2374   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2375   ARMConstantPoolValue *CPV =
2376     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2377                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2378   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2379   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2380   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2381                          MachinePointerInfo::getConstantPool(),
2382                          false, false, false, 0);
2383   SDValue Chain = Argument.getValue(1);
2384
2385   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2386   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2387
2388   // call __tls_get_addr.
2389   ArgListTy Args;
2390   ArgListEntry Entry;
2391   Entry.Node = Argument;
2392   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2393   Args.push_back(Entry);
2394   // FIXME: is there useful debug info available here?
2395   TargetLowering::CallLoweringInfo CLI(Chain,
2396                 (Type *) Type::getInt32Ty(*DAG.getContext()),
2397                 false, false, false, false,
2398                 0, CallingConv::C, /*isTailCall=*/false,
2399                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2400                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2401   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2402   return CallResult.first;
2403 }
2404
2405 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2406 // "local exec" model.
2407 SDValue
2408 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2409                                         SelectionDAG &DAG,
2410                                         TLSModel::Model model) const {
2411   const GlobalValue *GV = GA->getGlobal();
2412   SDLoc dl(GA);
2413   SDValue Offset;
2414   SDValue Chain = DAG.getEntryNode();
2415   EVT PtrVT = getPointerTy();
2416   // Get the Thread Pointer
2417   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2418
2419   if (model == TLSModel::InitialExec) {
2420     MachineFunction &MF = DAG.getMachineFunction();
2421     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2422     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2423     // Initial exec model.
2424     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2425     ARMConstantPoolValue *CPV =
2426       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2427                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2428                                       true);
2429     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2430     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2431     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2432                          MachinePointerInfo::getConstantPool(),
2433                          false, false, false, 0);
2434     Chain = Offset.getValue(1);
2435
2436     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2437     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2438
2439     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2440                          MachinePointerInfo::getConstantPool(),
2441                          false, false, false, 0);
2442   } else {
2443     // local exec model
2444     assert(model == TLSModel::LocalExec);
2445     ARMConstantPoolValue *CPV =
2446       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2447     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2448     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2449     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2450                          MachinePointerInfo::getConstantPool(),
2451                          false, false, false, 0);
2452   }
2453
2454   // The address of the thread local variable is the add of the thread
2455   // pointer with the offset of the variable.
2456   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2457 }
2458
2459 SDValue
2460 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2461   // TODO: implement the "local dynamic" model
2462   assert(Subtarget->isTargetELF() &&
2463          "TLS not implemented for non-ELF targets");
2464   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2465
2466   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2467
2468   switch (model) {
2469     case TLSModel::GeneralDynamic:
2470     case TLSModel::LocalDynamic:
2471       return LowerToTLSGeneralDynamicModel(GA, DAG);
2472     case TLSModel::InitialExec:
2473     case TLSModel::LocalExec:
2474       return LowerToTLSExecModels(GA, DAG, model);
2475   }
2476   llvm_unreachable("bogus TLS model");
2477 }
2478
2479 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2480                                                  SelectionDAG &DAG) const {
2481   EVT PtrVT = getPointerTy();
2482   SDLoc dl(Op);
2483   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2484   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2485     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2486     ARMConstantPoolValue *CPV =
2487       ARMConstantPoolConstant::Create(GV,
2488                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2489     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2490     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2491     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2492                                  CPAddr,
2493                                  MachinePointerInfo::getConstantPool(),
2494                                  false, false, false, 0);
2495     SDValue Chain = Result.getValue(1);
2496     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2497     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2498     if (!UseGOTOFF)
2499       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2500                            MachinePointerInfo::getGOT(),
2501                            false, false, false, 0);
2502     return Result;
2503   }
2504
2505   // If we have T2 ops, we can materialize the address directly via movt/movw
2506   // pair. This is always cheaper.
2507   if (Subtarget->useMovt()) {
2508     ++NumMovwMovt;
2509     // FIXME: Once remat is capable of dealing with instructions with register
2510     // operands, expand this into two nodes.
2511     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2512                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2513   } else {
2514     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2515     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2516     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2517                        MachinePointerInfo::getConstantPool(),
2518                        false, false, false, 0);
2519   }
2520 }
2521
2522 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2523                                                     SelectionDAG &DAG) const {
2524   EVT PtrVT = getPointerTy();
2525   SDLoc dl(Op);
2526   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2527   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2528
2529   // FIXME: Enable this for static codegen when tool issues are fixed.  Also
2530   // update ARMFastISel::ARMMaterializeGV.
2531   if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2532     ++NumMovwMovt;
2533     // FIXME: Once remat is capable of dealing with instructions with register
2534     // operands, expand this into two nodes.
2535     if (RelocM == Reloc::Static)
2536       return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2537                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2538
2539     unsigned Wrapper = (RelocM == Reloc::PIC_)
2540       ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2541     SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2542                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2543     if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2544       Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2545                            MachinePointerInfo::getGOT(),
2546                            false, false, false, 0);
2547     return Result;
2548   }
2549
2550   unsigned ARMPCLabelIndex = 0;
2551   SDValue CPAddr;
2552   if (RelocM == Reloc::Static) {
2553     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2554   } else {
2555     ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2556     ARMPCLabelIndex = AFI->createPICLabelUId();
2557     unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2558     ARMConstantPoolValue *CPV =
2559       ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2560                                       PCAdj);
2561     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2562   }
2563   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2564
2565   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2566                                MachinePointerInfo::getConstantPool(),
2567                                false, false, false, 0);
2568   SDValue Chain = Result.getValue(1);
2569
2570   if (RelocM == Reloc::PIC_) {
2571     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2572     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2573   }
2574
2575   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2576     Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2577                          false, false, false, 0);
2578
2579   return Result;
2580 }
2581
2582 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2583                                                     SelectionDAG &DAG) const {
2584   assert(Subtarget->isTargetELF() &&
2585          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2586   MachineFunction &MF = DAG.getMachineFunction();
2587   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2588   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2589   EVT PtrVT = getPointerTy();
2590   SDLoc dl(Op);
2591   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2592   ARMConstantPoolValue *CPV =
2593     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2594                                   ARMPCLabelIndex, PCAdj);
2595   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2596   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2597   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2598                                MachinePointerInfo::getConstantPool(),
2599                                false, false, false, 0);
2600   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2601   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2602 }
2603
2604 SDValue
2605 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2606   SDLoc dl(Op);
2607   SDValue Val = DAG.getConstant(0, MVT::i32);
2608   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2609                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2610                      Op.getOperand(1), Val);
2611 }
2612
2613 SDValue
2614 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2615   SDLoc dl(Op);
2616   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2617                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2618 }
2619
2620 SDValue
2621 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2622                                           const ARMSubtarget *Subtarget) const {
2623   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2624   SDLoc dl(Op);
2625   switch (IntNo) {
2626   default: return SDValue();    // Don't custom lower most intrinsics.
2627   case Intrinsic::arm_thread_pointer: {
2628     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2629     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2630   }
2631   case Intrinsic::eh_sjlj_lsda: {
2632     MachineFunction &MF = DAG.getMachineFunction();
2633     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2634     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2635     EVT PtrVT = getPointerTy();
2636     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2637     SDValue CPAddr;
2638     unsigned PCAdj = (RelocM != Reloc::PIC_)
2639       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2640     ARMConstantPoolValue *CPV =
2641       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2642                                       ARMCP::CPLSDA, PCAdj);
2643     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2644     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2645     SDValue Result =
2646       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2647                   MachinePointerInfo::getConstantPool(),
2648                   false, false, false, 0);
2649
2650     if (RelocM == Reloc::PIC_) {
2651       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2652       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2653     }
2654     return Result;
2655   }
2656   case Intrinsic::arm_neon_vmulls:
2657   case Intrinsic::arm_neon_vmullu: {
2658     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2659       ? ARMISD::VMULLs : ARMISD::VMULLu;
2660     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2661                        Op.getOperand(1), Op.getOperand(2));
2662   }
2663   }
2664 }
2665
2666 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2667                                  const ARMSubtarget *Subtarget) {
2668   // FIXME: handle "fence singlethread" more efficiently.
2669   SDLoc dl(Op);
2670   if (!Subtarget->hasDataBarrier()) {
2671     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2672     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2673     // here.
2674     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2675            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2676     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2677                        DAG.getConstant(0, MVT::i32));
2678   }
2679
2680   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2681   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2682   unsigned Domain = ARM_MB::ISH;
2683   if (Subtarget->isMClass()) {
2684     // Only a full system barrier exists in the M-class architectures.
2685     Domain = ARM_MB::SY;
2686   } else if (Subtarget->isSwift() && Ord == Release) {
2687     // Swift happens to implement ISHST barriers in a way that's compatible with
2688     // Release semantics but weaker than ISH so we'd be fools not to use
2689     // it. Beware: other processors probably don't!
2690     Domain = ARM_MB::ISHST;
2691   }
2692
2693   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2694                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2695                      DAG.getConstant(Domain, MVT::i32));
2696 }
2697
2698 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2699                              const ARMSubtarget *Subtarget) {
2700   // ARM pre v5TE and Thumb1 does not have preload instructions.
2701   if (!(Subtarget->isThumb2() ||
2702         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2703     // Just preserve the chain.
2704     return Op.getOperand(0);
2705
2706   SDLoc dl(Op);
2707   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2708   if (!isRead &&
2709       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2710     // ARMv7 with MP extension has PLDW.
2711     return Op.getOperand(0);
2712
2713   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2714   if (Subtarget->isThumb()) {
2715     // Invert the bits.
2716     isRead = ~isRead & 1;
2717     isData = ~isData & 1;
2718   }
2719
2720   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2721                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2722                      DAG.getConstant(isData, MVT::i32));
2723 }
2724
2725 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2726   MachineFunction &MF = DAG.getMachineFunction();
2727   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2728
2729   // vastart just stores the address of the VarArgsFrameIndex slot into the
2730   // memory location argument.
2731   SDLoc dl(Op);
2732   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2733   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2734   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2735   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2736                       MachinePointerInfo(SV), false, false, 0);
2737 }
2738
2739 SDValue
2740 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2741                                         SDValue &Root, SelectionDAG &DAG,
2742                                         SDLoc dl) const {
2743   MachineFunction &MF = DAG.getMachineFunction();
2744   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2745
2746   const TargetRegisterClass *RC;
2747   if (AFI->isThumb1OnlyFunction())
2748     RC = &ARM::tGPRRegClass;
2749   else
2750     RC = &ARM::GPRRegClass;
2751
2752   // Transform the arguments stored in physical registers into virtual ones.
2753   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2754   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2755
2756   SDValue ArgValue2;
2757   if (NextVA.isMemLoc()) {
2758     MachineFrameInfo *MFI = MF.getFrameInfo();
2759     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2760
2761     // Create load node to retrieve arguments from the stack.
2762     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2763     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2764                             MachinePointerInfo::getFixedStack(FI),
2765                             false, false, false, 0);
2766   } else {
2767     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2768     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2769   }
2770
2771   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2772 }
2773
2774 void
2775 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2776                                   unsigned InRegsParamRecordIdx,
2777                                   unsigned ArgSize,
2778                                   unsigned &ArgRegsSize,
2779                                   unsigned &ArgRegsSaveSize)
2780   const {
2781   unsigned NumGPRs;
2782   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2783     unsigned RBegin, REnd;
2784     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2785     NumGPRs = REnd - RBegin;
2786   } else {
2787     unsigned int firstUnalloced;
2788     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2789                                                 sizeof(GPRArgRegs) /
2790                                                 sizeof(GPRArgRegs[0]));
2791     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2792   }
2793
2794   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2795   ArgRegsSize = NumGPRs * 4;
2796
2797   // If parameter is split between stack and GPRs...
2798   if (NumGPRs && Align == 8 &&
2799       (ArgRegsSize < ArgSize ||
2800         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2801     // Add padding for part of param recovered from GPRs, so
2802     // its last byte must be at address K*8 - 1.
2803     // We need to do it, since remained (stack) part of parameter has
2804     // stack alignment, and we need to "attach" "GPRs head" without gaps
2805     // to it:
2806     // Stack:
2807     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2808     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2809     //
2810     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2811     unsigned Padding =
2812         ((ArgRegsSize + AFI->getArgRegsSaveSize() + Align - 1) & ~(Align-1)) -
2813         (ArgRegsSize + AFI->getArgRegsSaveSize());
2814     ArgRegsSaveSize = ArgRegsSize + Padding;
2815   } else
2816     // We don't need to extend regs save size for byval parameters if they
2817     // are passed via GPRs only.
2818     ArgRegsSaveSize = ArgRegsSize;
2819 }
2820
2821 // The remaining GPRs hold either the beginning of variable-argument
2822 // data, or the beginning of an aggregate passed by value (usually
2823 // byval).  Either way, we allocate stack slots adjacent to the data
2824 // provided by our caller, and store the unallocated registers there.
2825 // If this is a variadic function, the va_list pointer will begin with
2826 // these values; otherwise, this reassembles a (byval) structure that
2827 // was split between registers and memory.
2828 // Return: The frame index registers were stored into.
2829 int
2830 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2831                                   SDLoc dl, SDValue &Chain,
2832                                   const Value *OrigArg,
2833                                   unsigned InRegsParamRecordIdx,
2834                                   unsigned OffsetFromOrigArg,
2835                                   unsigned ArgOffset,
2836                                   unsigned ArgSize,
2837                                   bool ForceMutable) const {
2838
2839   // Currently, two use-cases possible:
2840   // Case #1. Non var-args function, and we meet first byval parameter.
2841   //          Setup first unallocated register as first byval register;
2842   //          eat all remained registers
2843   //          (these two actions are performed by HandleByVal method).
2844   //          Then, here, we initialize stack frame with
2845   //          "store-reg" instructions.
2846   // Case #2. Var-args function, that doesn't contain byval parameters.
2847   //          The same: eat all remained unallocated registers,
2848   //          initialize stack frame.
2849
2850   MachineFunction &MF = DAG.getMachineFunction();
2851   MachineFrameInfo *MFI = MF.getFrameInfo();
2852   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2853   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2854   unsigned RBegin, REnd;
2855   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2856     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2857     firstRegToSaveIndex = RBegin - ARM::R0;
2858     lastRegToSaveIndex = REnd - ARM::R0;
2859   } else {
2860     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2861       (GPRArgRegs, array_lengthof(GPRArgRegs));
2862     lastRegToSaveIndex = 4;
2863   }
2864
2865   unsigned ArgRegsSize, ArgRegsSaveSize;
2866   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2867                  ArgRegsSize, ArgRegsSaveSize);
2868
2869   // Store any by-val regs to their spots on the stack so that they may be
2870   // loaded by deferencing the result of formal parameter pointer or va_next.
2871   // Note: once stack area for byval/varargs registers
2872   // was initialized, it can't be initialized again.
2873   if (ArgRegsSaveSize) {
2874
2875     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2876
2877     if (Padding) {
2878       assert(AFI->getStoredByValParamsPadding() == 0 &&
2879              "The only parameter may be padded.");
2880       AFI->setStoredByValParamsPadding(Padding);
2881     }
2882
2883     int FrameIndex = MFI->CreateFixedObject(
2884                       ArgRegsSaveSize,
2885                       Padding + ArgOffset,
2886                       false);
2887     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2888
2889     SmallVector<SDValue, 4> MemOps;
2890     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2891          ++firstRegToSaveIndex, ++i) {
2892       const TargetRegisterClass *RC;
2893       if (AFI->isThumb1OnlyFunction())
2894         RC = &ARM::tGPRRegClass;
2895       else
2896         RC = &ARM::GPRRegClass;
2897
2898       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2899       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2900       SDValue Store =
2901         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2902                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2903                      false, false, 0);
2904       MemOps.push_back(Store);
2905       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2906                         DAG.getConstant(4, getPointerTy()));
2907     }
2908
2909     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2910
2911     if (!MemOps.empty())
2912       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2913                           &MemOps[0], MemOps.size());
2914     return FrameIndex;
2915   } else
2916     // This will point to the next argument passed via stack.
2917     return MFI->CreateFixedObject(
2918         4, AFI->getStoredByValParamsPadding() + ArgOffset, !ForceMutable);
2919 }
2920
2921 // Setup stack frame, the va_list pointer will start from.
2922 void
2923 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2924                                         SDLoc dl, SDValue &Chain,
2925                                         unsigned ArgOffset,
2926                                         bool ForceMutable) const {
2927   MachineFunction &MF = DAG.getMachineFunction();
2928   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2929
2930   // Try to store any remaining integer argument regs
2931   // to their spots on the stack so that they may be loaded by deferencing
2932   // the result of va_next.
2933   // If there is no regs to be stored, just point address after last
2934   // argument passed via stack.
2935   int FrameIndex =
2936     StoreByValRegs(CCInfo, DAG, dl, Chain, 0, CCInfo.getInRegsParamsCount(),
2937                    0, ArgOffset, 0, ForceMutable);
2938
2939   AFI->setVarArgsFrameIndex(FrameIndex);
2940 }
2941
2942 SDValue
2943 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2944                                         CallingConv::ID CallConv, bool isVarArg,
2945                                         const SmallVectorImpl<ISD::InputArg>
2946                                           &Ins,
2947                                         SDLoc dl, SelectionDAG &DAG,
2948                                         SmallVectorImpl<SDValue> &InVals)
2949                                           const {
2950   MachineFunction &MF = DAG.getMachineFunction();
2951   MachineFrameInfo *MFI = MF.getFrameInfo();
2952
2953   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2954
2955   // Assign locations to all of the incoming arguments.
2956   SmallVector<CCValAssign, 16> ArgLocs;
2957   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2958                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2959   CCInfo.AnalyzeFormalArguments(Ins,
2960                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2961                                                   isVarArg));
2962
2963   SmallVector<SDValue, 16> ArgValues;
2964   int lastInsIndex = -1;
2965   SDValue ArgValue;
2966   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2967   unsigned CurArgIdx = 0;
2968
2969   // Initially ArgRegsSaveSize is zero.
2970   // Then we increase this value each time we meet byval parameter.
2971   // We also increase this value in case of varargs function.
2972   AFI->setArgRegsSaveSize(0);
2973
2974   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2975     CCValAssign &VA = ArgLocs[i];
2976     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2977     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2978     // Arguments stored in registers.
2979     if (VA.isRegLoc()) {
2980       EVT RegVT = VA.getLocVT();
2981
2982       if (VA.needsCustom()) {
2983         // f64 and vector types are split up into multiple registers or
2984         // combinations of registers and stack slots.
2985         if (VA.getLocVT() == MVT::v2f64) {
2986           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2987                                                    Chain, DAG, dl);
2988           VA = ArgLocs[++i]; // skip ahead to next loc
2989           SDValue ArgValue2;
2990           if (VA.isMemLoc()) {
2991             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2992             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2993             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2994                                     MachinePointerInfo::getFixedStack(FI),
2995                                     false, false, false, 0);
2996           } else {
2997             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2998                                              Chain, DAG, dl);
2999           }
3000           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3001           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3002                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3003           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3004                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3005         } else
3006           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3007
3008       } else {
3009         const TargetRegisterClass *RC;
3010
3011         if (RegVT == MVT::f32)
3012           RC = &ARM::SPRRegClass;
3013         else if (RegVT == MVT::f64)
3014           RC = &ARM::DPRRegClass;
3015         else if (RegVT == MVT::v2f64)
3016           RC = &ARM::QPRRegClass;
3017         else if (RegVT == MVT::i32)
3018           RC = AFI->isThumb1OnlyFunction() ?
3019             (const TargetRegisterClass*)&ARM::tGPRRegClass :
3020             (const TargetRegisterClass*)&ARM::GPRRegClass;
3021         else
3022           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3023
3024         // Transform the arguments in physical registers into virtual ones.
3025         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3026         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3027       }
3028
3029       // If this is an 8 or 16-bit value, it is really passed promoted
3030       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3031       // truncate to the right size.
3032       switch (VA.getLocInfo()) {
3033       default: llvm_unreachable("Unknown loc info!");
3034       case CCValAssign::Full: break;
3035       case CCValAssign::BCvt:
3036         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3037         break;
3038       case CCValAssign::SExt:
3039         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3040                                DAG.getValueType(VA.getValVT()));
3041         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3042         break;
3043       case CCValAssign::ZExt:
3044         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3045                                DAG.getValueType(VA.getValVT()));
3046         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3047         break;
3048       }
3049
3050       InVals.push_back(ArgValue);
3051
3052     } else { // VA.isRegLoc()
3053
3054       // sanity check
3055       assert(VA.isMemLoc());
3056       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3057
3058       int index = ArgLocs[i].getValNo();
3059
3060       // Some Ins[] entries become multiple ArgLoc[] entries.
3061       // Process them only once.
3062       if (index != lastInsIndex)
3063         {
3064           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3065           // FIXME: For now, all byval parameter objects are marked mutable.
3066           // This can be changed with more analysis.
3067           // In case of tail call optimization mark all arguments mutable.
3068           // Since they could be overwritten by lowering of arguments in case of
3069           // a tail call.
3070           if (Flags.isByVal()) {
3071             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3072             int FrameIndex = StoreByValRegs(
3073                 CCInfo, DAG, dl, Chain, CurOrigArg,
3074                 CurByValIndex,
3075                 Ins[VA.getValNo()].PartOffset,
3076                 VA.getLocMemOffset(),
3077                 Flags.getByValSize(),
3078                 true /*force mutable frames*/);
3079             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3080             CCInfo.nextInRegsParam();
3081           } else {
3082             unsigned FIOffset = VA.getLocMemOffset() +
3083                                 AFI->getStoredByValParamsPadding();
3084             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3085                                             FIOffset, true);
3086
3087             // Create load nodes to retrieve arguments from the stack.
3088             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3089             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3090                                          MachinePointerInfo::getFixedStack(FI),
3091                                          false, false, false, 0));
3092           }
3093           lastInsIndex = index;
3094         }
3095     }
3096   }
3097
3098   // varargs
3099   if (isVarArg)
3100     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3101                          CCInfo.getNextStackOffset());
3102
3103   return Chain;
3104 }
3105
3106 /// isFloatingPointZero - Return true if this is +0.0.
3107 static bool isFloatingPointZero(SDValue Op) {
3108   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3109     return CFP->getValueAPF().isPosZero();
3110   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3111     // Maybe this has already been legalized into the constant pool?
3112     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3113       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3114       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3115         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3116           return CFP->getValueAPF().isPosZero();
3117     }
3118   }
3119   return false;
3120 }
3121
3122 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3123 /// the given operands.
3124 SDValue
3125 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3126                              SDValue &ARMcc, SelectionDAG &DAG,
3127                              SDLoc dl) const {
3128   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3129     unsigned C = RHSC->getZExtValue();
3130     if (!isLegalICmpImmediate(C)) {
3131       // Constant does not fit, try adjusting it by one?
3132       switch (CC) {
3133       default: break;
3134       case ISD::SETLT:
3135       case ISD::SETGE:
3136         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3137           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3138           RHS = DAG.getConstant(C-1, MVT::i32);
3139         }
3140         break;
3141       case ISD::SETULT:
3142       case ISD::SETUGE:
3143         if (C != 0 && isLegalICmpImmediate(C-1)) {
3144           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3145           RHS = DAG.getConstant(C-1, MVT::i32);
3146         }
3147         break;
3148       case ISD::SETLE:
3149       case ISD::SETGT:
3150         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3151           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3152           RHS = DAG.getConstant(C+1, MVT::i32);
3153         }
3154         break;
3155       case ISD::SETULE:
3156       case ISD::SETUGT:
3157         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3158           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3159           RHS = DAG.getConstant(C+1, MVT::i32);
3160         }
3161         break;
3162       }
3163     }
3164   }
3165
3166   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3167   ARMISD::NodeType CompareType;
3168   switch (CondCode) {
3169   default:
3170     CompareType = ARMISD::CMP;
3171     break;
3172   case ARMCC::EQ:
3173   case ARMCC::NE:
3174     // Uses only Z Flag
3175     CompareType = ARMISD::CMPZ;
3176     break;
3177   }
3178   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3179   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3180 }
3181
3182 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3183 SDValue
3184 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3185                              SDLoc dl) const {
3186   SDValue Cmp;
3187   if (!isFloatingPointZero(RHS))
3188     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3189   else
3190     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3191   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3192 }
3193
3194 /// duplicateCmp - Glue values can have only one use, so this function
3195 /// duplicates a comparison node.
3196 SDValue
3197 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3198   unsigned Opc = Cmp.getOpcode();
3199   SDLoc DL(Cmp);
3200   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3201     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3202
3203   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3204   Cmp = Cmp.getOperand(0);
3205   Opc = Cmp.getOpcode();
3206   if (Opc == ARMISD::CMPFP)
3207     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3208   else {
3209     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3210     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3211   }
3212   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3213 }
3214
3215 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3216   SDValue Cond = Op.getOperand(0);
3217   SDValue SelectTrue = Op.getOperand(1);
3218   SDValue SelectFalse = Op.getOperand(2);
3219   SDLoc dl(Op);
3220
3221   // Convert:
3222   //
3223   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3224   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3225   //
3226   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3227     const ConstantSDNode *CMOVTrue =
3228       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3229     const ConstantSDNode *CMOVFalse =
3230       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3231
3232     if (CMOVTrue && CMOVFalse) {
3233       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3234       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3235
3236       SDValue True;
3237       SDValue False;
3238       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3239         True = SelectTrue;
3240         False = SelectFalse;
3241       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3242         True = SelectFalse;
3243         False = SelectTrue;
3244       }
3245
3246       if (True.getNode() && False.getNode()) {
3247         EVT VT = Op.getValueType();
3248         SDValue ARMcc = Cond.getOperand(2);
3249         SDValue CCR = Cond.getOperand(3);
3250         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3251         assert(True.getValueType() == VT);
3252         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3253       }
3254     }
3255   }
3256
3257   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3258   // undefined bits before doing a full-word comparison with zero.
3259   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3260                      DAG.getConstant(1, Cond.getValueType()));
3261
3262   return DAG.getSelectCC(dl, Cond,
3263                          DAG.getConstant(0, Cond.getValueType()),
3264                          SelectTrue, SelectFalse, ISD::SETNE);
3265 }
3266
3267 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3268   if (CC == ISD::SETNE)
3269     return ISD::SETEQ;
3270   return ISD::getSetCCSwappedOperands(CC);
3271 }
3272
3273 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3274                                  bool &swpCmpOps, bool &swpVselOps) {
3275   // Start by selecting the GE condition code for opcodes that return true for
3276   // 'equality'
3277   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3278       CC == ISD::SETULE)
3279     CondCode = ARMCC::GE;
3280
3281   // and GT for opcodes that return false for 'equality'.
3282   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3283            CC == ISD::SETULT)
3284     CondCode = ARMCC::GT;
3285
3286   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3287   // to swap the compare operands.
3288   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3289       CC == ISD::SETULT)
3290     swpCmpOps = true;
3291
3292   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3293   // If we have an unordered opcode, we need to swap the operands to the VSEL
3294   // instruction (effectively negating the condition).
3295   //
3296   // This also has the effect of swapping which one of 'less' or 'greater'
3297   // returns true, so we also swap the compare operands. It also switches
3298   // whether we return true for 'equality', so we compensate by picking the
3299   // opposite condition code to our original choice.
3300   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3301       CC == ISD::SETUGT) {
3302     swpCmpOps = !swpCmpOps;
3303     swpVselOps = !swpVselOps;
3304     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3305   }
3306
3307   // 'ordered' is 'anything but unordered', so use the VS condition code and
3308   // swap the VSEL operands.
3309   if (CC == ISD::SETO) {
3310     CondCode = ARMCC::VS;
3311     swpVselOps = true;
3312   }
3313
3314   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3315   // code and swap the VSEL operands.
3316   if (CC == ISD::SETUNE) {
3317     CondCode = ARMCC::EQ;
3318     swpVselOps = true;
3319   }
3320 }
3321
3322 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3323   EVT VT = Op.getValueType();
3324   SDValue LHS = Op.getOperand(0);
3325   SDValue RHS = Op.getOperand(1);
3326   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3327   SDValue TrueVal = Op.getOperand(2);
3328   SDValue FalseVal = Op.getOperand(3);
3329   SDLoc dl(Op);
3330
3331   if (LHS.getValueType() == MVT::i32) {
3332     // Try to generate VSEL on ARMv8.
3333     // The VSEL instruction can't use all the usual ARM condition
3334     // codes: it only has two bits to select the condition code, so it's
3335     // constrained to use only GE, GT, VS and EQ.
3336     //
3337     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3338     // swap the operands of the previous compare instruction (effectively
3339     // inverting the compare condition, swapping 'less' and 'greater') and
3340     // sometimes need to swap the operands to the VSEL (which inverts the
3341     // condition in the sense of firing whenever the previous condition didn't)
3342     if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3343                                       TrueVal.getValueType() == MVT::f64)) {
3344       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3345       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3346           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3347         CC = getInverseCCForVSEL(CC);
3348         std::swap(TrueVal, FalseVal);
3349       }
3350     }
3351
3352     SDValue ARMcc;
3353     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3354     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3355     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3356                        Cmp);
3357   }
3358
3359   ARMCC::CondCodes CondCode, CondCode2;
3360   FPCCToARMCC(CC, CondCode, CondCode2);
3361
3362   // Try to generate VSEL on ARMv8.
3363   if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3364                                     TrueVal.getValueType() == MVT::f64)) {
3365     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3366     // same operands, as follows:
3367     //   c = fcmp [ogt, olt, ugt, ult] a, b
3368     //   select c, a, b
3369     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3370     // handled differently than the original code sequence.
3371     if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3372         RHS == FalseVal) {
3373       if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3374         return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3375       if (CC == ISD::SETOLT || CC == ISD::SETULT)
3376         return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3377     }
3378
3379     bool swpCmpOps = false;
3380     bool swpVselOps = false;
3381     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3382
3383     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3384         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3385       if (swpCmpOps)
3386         std::swap(LHS, RHS);
3387       if (swpVselOps)
3388         std::swap(TrueVal, FalseVal);
3389     }
3390   }
3391
3392   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3393   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3394   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3395   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3396                                ARMcc, CCR, Cmp);
3397   if (CondCode2 != ARMCC::AL) {
3398     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3399     // FIXME: Needs another CMP because flag can have but one use.
3400     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3401     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3402                          Result, TrueVal, ARMcc2, CCR, Cmp2);
3403   }
3404   return Result;
3405 }
3406
3407 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3408 /// to morph to an integer compare sequence.
3409 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3410                            const ARMSubtarget *Subtarget) {
3411   SDNode *N = Op.getNode();
3412   if (!N->hasOneUse())
3413     // Otherwise it requires moving the value from fp to integer registers.
3414     return false;
3415   if (!N->getNumValues())
3416     return false;
3417   EVT VT = Op.getValueType();
3418   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3419     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3420     // vmrs are very slow, e.g. cortex-a8.
3421     return false;
3422
3423   if (isFloatingPointZero(Op)) {
3424     SeenZero = true;
3425     return true;
3426   }
3427   return ISD::isNormalLoad(N);
3428 }
3429
3430 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3431   if (isFloatingPointZero(Op))
3432     return DAG.getConstant(0, MVT::i32);
3433
3434   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3435     return DAG.getLoad(MVT::i32, SDLoc(Op),
3436                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3437                        Ld->isVolatile(), Ld->isNonTemporal(),
3438                        Ld->isInvariant(), Ld->getAlignment());
3439
3440   llvm_unreachable("Unknown VFP cmp argument!");
3441 }
3442
3443 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3444                            SDValue &RetVal1, SDValue &RetVal2) {
3445   if (isFloatingPointZero(Op)) {
3446     RetVal1 = DAG.getConstant(0, MVT::i32);
3447     RetVal2 = DAG.getConstant(0, MVT::i32);
3448     return;
3449   }
3450
3451   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3452     SDValue Ptr = Ld->getBasePtr();
3453     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3454                           Ld->getChain(), Ptr,
3455                           Ld->getPointerInfo(),
3456                           Ld->isVolatile(), Ld->isNonTemporal(),
3457                           Ld->isInvariant(), Ld->getAlignment());
3458
3459     EVT PtrType = Ptr.getValueType();
3460     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3461     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3462                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3463     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3464                           Ld->getChain(), NewPtr,
3465                           Ld->getPointerInfo().getWithOffset(4),
3466                           Ld->isVolatile(), Ld->isNonTemporal(),
3467                           Ld->isInvariant(), NewAlign);
3468     return;
3469   }
3470
3471   llvm_unreachable("Unknown VFP cmp argument!");
3472 }
3473
3474 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3475 /// f32 and even f64 comparisons to integer ones.
3476 SDValue
3477 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3478   SDValue Chain = Op.getOperand(0);
3479   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3480   SDValue LHS = Op.getOperand(2);
3481   SDValue RHS = Op.getOperand(3);
3482   SDValue Dest = Op.getOperand(4);
3483   SDLoc dl(Op);
3484
3485   bool LHSSeenZero = false;
3486   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3487   bool RHSSeenZero = false;
3488   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3489   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3490     // If unsafe fp math optimization is enabled and there are no other uses of
3491     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3492     // to an integer comparison.
3493     if (CC == ISD::SETOEQ)
3494       CC = ISD::SETEQ;
3495     else if (CC == ISD::SETUNE)
3496       CC = ISD::SETNE;
3497
3498     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3499     SDValue ARMcc;
3500     if (LHS.getValueType() == MVT::f32) {
3501       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3502                         bitcastf32Toi32(LHS, DAG), Mask);
3503       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3504                         bitcastf32Toi32(RHS, DAG), Mask);
3505       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3506       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3507       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3508                          Chain, Dest, ARMcc, CCR, Cmp);
3509     }
3510
3511     SDValue LHS1, LHS2;
3512     SDValue RHS1, RHS2;
3513     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3514     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3515     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3516     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3517     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3518     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3519     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3520     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3521     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3522   }
3523
3524   return SDValue();
3525 }
3526
3527 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3528   SDValue Chain = Op.getOperand(0);
3529   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3530   SDValue LHS = Op.getOperand(2);
3531   SDValue RHS = Op.getOperand(3);
3532   SDValue Dest = Op.getOperand(4);
3533   SDLoc dl(Op);
3534
3535   if (LHS.getValueType() == MVT::i32) {
3536     SDValue ARMcc;
3537     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3538     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3539     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3540                        Chain, Dest, ARMcc, CCR, Cmp);
3541   }
3542
3543   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3544
3545   if (getTargetMachine().Options.UnsafeFPMath &&
3546       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3547        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3548     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3549     if (Result.getNode())
3550       return Result;
3551   }
3552
3553   ARMCC::CondCodes CondCode, CondCode2;
3554   FPCCToARMCC(CC, CondCode, CondCode2);
3555
3556   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3557   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3558   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3559   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3560   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3561   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3562   if (CondCode2 != ARMCC::AL) {
3563     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3564     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3565     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3566   }
3567   return Res;
3568 }
3569
3570 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3571   SDValue Chain = Op.getOperand(0);
3572   SDValue Table = Op.getOperand(1);
3573   SDValue Index = Op.getOperand(2);
3574   SDLoc dl(Op);
3575
3576   EVT PTy = getPointerTy();
3577   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3578   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3579   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3580   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3581   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3582   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3583   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3584   if (Subtarget->isThumb2()) {
3585     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3586     // which does another jump to the destination. This also makes it easier
3587     // to translate it to TBB / TBH later.
3588     // FIXME: This might not work if the function is extremely large.
3589     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3590                        Addr, Op.getOperand(2), JTI, UId);
3591   }
3592   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3593     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3594                        MachinePointerInfo::getJumpTable(),
3595                        false, false, false, 0);
3596     Chain = Addr.getValue(1);
3597     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3598     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3599   } else {
3600     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3601                        MachinePointerInfo::getJumpTable(),
3602                        false, false, false, 0);
3603     Chain = Addr.getValue(1);
3604     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3605   }
3606 }
3607
3608 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3609   EVT VT = Op.getValueType();
3610   SDLoc dl(Op);
3611
3612   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3613     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3614       return Op;
3615     return DAG.UnrollVectorOp(Op.getNode());
3616   }
3617
3618   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3619          "Invalid type for custom lowering!");
3620   if (VT != MVT::v4i16)
3621     return DAG.UnrollVectorOp(Op.getNode());
3622
3623   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3624   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3625 }
3626
3627 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3628   EVT VT = Op.getValueType();
3629   if (VT.isVector())
3630     return LowerVectorFP_TO_INT(Op, DAG);
3631
3632   SDLoc dl(Op);
3633   unsigned Opc;
3634
3635   switch (Op.getOpcode()) {
3636   default: llvm_unreachable("Invalid opcode!");
3637   case ISD::FP_TO_SINT:
3638     Opc = ARMISD::FTOSI;
3639     break;
3640   case ISD::FP_TO_UINT:
3641     Opc = ARMISD::FTOUI;
3642     break;
3643   }
3644   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3645   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3646 }
3647
3648 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3649   EVT VT = Op.getValueType();
3650   SDLoc dl(Op);
3651
3652   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3653     if (VT.getVectorElementType() == MVT::f32)
3654       return Op;
3655     return DAG.UnrollVectorOp(Op.getNode());
3656   }
3657
3658   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3659          "Invalid type for custom lowering!");
3660   if (VT != MVT::v4f32)
3661     return DAG.UnrollVectorOp(Op.getNode());
3662
3663   unsigned CastOpc;
3664   unsigned Opc;
3665   switch (Op.getOpcode()) {
3666   default: llvm_unreachable("Invalid opcode!");
3667   case ISD::SINT_TO_FP:
3668     CastOpc = ISD::SIGN_EXTEND;
3669     Opc = ISD::SINT_TO_FP;
3670     break;
3671   case ISD::UINT_TO_FP:
3672     CastOpc = ISD::ZERO_EXTEND;
3673     Opc = ISD::UINT_TO_FP;
3674     break;
3675   }
3676
3677   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3678   return DAG.getNode(Opc, dl, VT, Op);
3679 }
3680
3681 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3682   EVT VT = Op.getValueType();
3683   if (VT.isVector())
3684     return LowerVectorINT_TO_FP(Op, DAG);
3685
3686   SDLoc dl(Op);
3687   unsigned Opc;
3688
3689   switch (Op.getOpcode()) {
3690   default: llvm_unreachable("Invalid opcode!");
3691   case ISD::SINT_TO_FP:
3692     Opc = ARMISD::SITOF;
3693     break;
3694   case ISD::UINT_TO_FP:
3695     Opc = ARMISD::UITOF;
3696     break;
3697   }
3698
3699   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3700   return DAG.getNode(Opc, dl, VT, Op);
3701 }
3702
3703 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3704   // Implement fcopysign with a fabs and a conditional fneg.
3705   SDValue Tmp0 = Op.getOperand(0);
3706   SDValue Tmp1 = Op.getOperand(1);
3707   SDLoc dl(Op);
3708   EVT VT = Op.getValueType();
3709   EVT SrcVT = Tmp1.getValueType();
3710   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3711     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3712   bool UseNEON = !InGPR && Subtarget->hasNEON();
3713
3714   if (UseNEON) {
3715     // Use VBSL to copy the sign bit.
3716     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3717     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3718                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3719     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3720     if (VT == MVT::f64)
3721       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3722                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3723                          DAG.getConstant(32, MVT::i32));
3724     else /*if (VT == MVT::f32)*/
3725       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3726     if (SrcVT == MVT::f32) {
3727       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3728       if (VT == MVT::f64)
3729         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3730                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3731                            DAG.getConstant(32, MVT::i32));
3732     } else if (VT == MVT::f32)
3733       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3734                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3735                          DAG.getConstant(32, MVT::i32));
3736     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3737     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3738
3739     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3740                                             MVT::i32);
3741     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3742     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3743                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3744
3745     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3746                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3747                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3748     if (VT == MVT::f32) {
3749       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3750       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3751                         DAG.getConstant(0, MVT::i32));
3752     } else {
3753       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3754     }
3755
3756     return Res;
3757   }
3758
3759   // Bitcast operand 1 to i32.
3760   if (SrcVT == MVT::f64)
3761     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3762                        &Tmp1, 1).getValue(1);
3763   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3764
3765   // Or in the signbit with integer operations.
3766   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3767   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3768   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3769   if (VT == MVT::f32) {
3770     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3771                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3772     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3773                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3774   }
3775
3776   // f64: Or the high part with signbit and then combine two parts.
3777   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3778                      &Tmp0, 1);
3779   SDValue Lo = Tmp0.getValue(0);
3780   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3781   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3782   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3783 }
3784
3785 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3786   MachineFunction &MF = DAG.getMachineFunction();
3787   MachineFrameInfo *MFI = MF.getFrameInfo();
3788   MFI->setReturnAddressIsTaken(true);
3789
3790   EVT VT = Op.getValueType();
3791   SDLoc dl(Op);
3792   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3793   if (Depth) {
3794     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3795     SDValue Offset = DAG.getConstant(4, MVT::i32);
3796     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3797                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3798                        MachinePointerInfo(), false, false, false, 0);
3799   }
3800
3801   // Return LR, which contains the return address. Mark it an implicit live-in.
3802   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3803   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3804 }
3805
3806 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3807   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3808   MFI->setFrameAddressIsTaken(true);
3809
3810   EVT VT = Op.getValueType();
3811   SDLoc dl(Op);  // FIXME probably not meaningful
3812   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3813   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3814     ? ARM::R7 : ARM::R11;
3815   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3816   while (Depth--)
3817     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3818                             MachinePointerInfo(),
3819                             false, false, false, 0);
3820   return FrameAddr;
3821 }
3822
3823 /// ExpandBITCAST - If the target supports VFP, this function is called to
3824 /// expand a bit convert where either the source or destination type is i64 to
3825 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3826 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3827 /// vectors), since the legalizer won't know what to do with that.
3828 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3829   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3830   SDLoc dl(N);
3831   SDValue Op = N->getOperand(0);
3832
3833   // This function is only supposed to be called for i64 types, either as the
3834   // source or destination of the bit convert.
3835   EVT SrcVT = Op.getValueType();
3836   EVT DstVT = N->getValueType(0);
3837   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3838          "ExpandBITCAST called for non-i64 type");
3839
3840   // Turn i64->f64 into VMOVDRR.
3841   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3842     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3843                              DAG.getConstant(0, MVT::i32));
3844     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3845                              DAG.getConstant(1, MVT::i32));
3846     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3847                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3848   }
3849
3850   // Turn f64->i64 into VMOVRRD.
3851   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3852     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3853                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3854     // Merge the pieces into a single i64 value.
3855     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3856   }
3857
3858   return SDValue();
3859 }
3860
3861 /// getZeroVector - Returns a vector of specified type with all zero elements.
3862 /// Zero vectors are used to represent vector negation and in those cases
3863 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3864 /// not support i64 elements, so sometimes the zero vectors will need to be
3865 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3866 /// zero vector.
3867 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3868   assert(VT.isVector() && "Expected a vector type");
3869   // The canonical modified immediate encoding of a zero vector is....0!
3870   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3871   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3872   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3873   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3874 }
3875
3876 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3877 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3878 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3879                                                 SelectionDAG &DAG) const {
3880   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3881   EVT VT = Op.getValueType();
3882   unsigned VTBits = VT.getSizeInBits();
3883   SDLoc dl(Op);
3884   SDValue ShOpLo = Op.getOperand(0);
3885   SDValue ShOpHi = Op.getOperand(1);
3886   SDValue ShAmt  = Op.getOperand(2);
3887   SDValue ARMcc;
3888   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3889
3890   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3891
3892   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3893                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3894   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3895   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3896                                    DAG.getConstant(VTBits, MVT::i32));
3897   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3898   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3899   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3900
3901   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3902   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3903                           ARMcc, DAG, dl);
3904   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3905   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3906                            CCR, Cmp);
3907
3908   SDValue Ops[2] = { Lo, Hi };
3909   return DAG.getMergeValues(Ops, 2, dl);
3910 }
3911
3912 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3913 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3914 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3915                                                SelectionDAG &DAG) const {
3916   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3917   EVT VT = Op.getValueType();
3918   unsigned VTBits = VT.getSizeInBits();
3919   SDLoc dl(Op);
3920   SDValue ShOpLo = Op.getOperand(0);
3921   SDValue ShOpHi = Op.getOperand(1);
3922   SDValue ShAmt  = Op.getOperand(2);
3923   SDValue ARMcc;
3924
3925   assert(Op.getOpcode() == ISD::SHL_PARTS);
3926   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3927                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3928   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3929   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3930                                    DAG.getConstant(VTBits, MVT::i32));
3931   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3932   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3933
3934   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3935   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3936   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3937                           ARMcc, DAG, dl);
3938   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3939   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3940                            CCR, Cmp);
3941
3942   SDValue Ops[2] = { Lo, Hi };
3943   return DAG.getMergeValues(Ops, 2, dl);
3944 }
3945
3946 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3947                                             SelectionDAG &DAG) const {
3948   // The rounding mode is in bits 23:22 of the FPSCR.
3949   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3950   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3951   // so that the shift + and get folded into a bitfield extract.
3952   SDLoc dl(Op);
3953   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3954                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3955                                               MVT::i32));
3956   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3957                                   DAG.getConstant(1U << 22, MVT::i32));
3958   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3959                               DAG.getConstant(22, MVT::i32));
3960   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3961                      DAG.getConstant(3, MVT::i32));
3962 }
3963
3964 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3965                          const ARMSubtarget *ST) {
3966   EVT VT = N->getValueType(0);
3967   SDLoc dl(N);
3968
3969   if (!ST->hasV6T2Ops())
3970     return SDValue();
3971
3972   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3973   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3974 }
3975
3976 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3977 /// for each 16-bit element from operand, repeated.  The basic idea is to
3978 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3979 ///
3980 /// Trace for v4i16:
3981 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
3982 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3983 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3984 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3985 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
3986 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
3987 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3988 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
3989 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3990   EVT VT = N->getValueType(0);
3991   SDLoc DL(N);
3992
3993   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
3994   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
3995   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
3996   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
3997   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
3998   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
3999 }
4000
4001 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4002 /// bit-count for each 16-bit element from the operand.  We need slightly
4003 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4004 /// 64/128-bit registers.
4005 ///
4006 /// Trace for v4i16:
4007 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4008 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4009 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4010 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4011 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4012   EVT VT = N->getValueType(0);
4013   SDLoc DL(N);
4014
4015   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4016   if (VT.is64BitVector()) {
4017     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4018     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4019                        DAG.getIntPtrConstant(0));
4020   } else {
4021     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4022                                     BitCounts, DAG.getIntPtrConstant(0));
4023     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4024   }
4025 }
4026
4027 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4028 /// bit-count for each 32-bit element from the operand.  The idea here is
4029 /// to split the vector into 16-bit elements, leverage the 16-bit count
4030 /// routine, and then combine the results.
4031 ///
4032 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4033 /// input    = [v0    v1    ] (vi: 32-bit elements)
4034 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4035 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4036 /// vrev: N0 = [k1 k0 k3 k2 ]
4037 ///            [k0 k1 k2 k3 ]
4038 ///       N1 =+[k1 k0 k3 k2 ]
4039 ///            [k0 k2 k1 k3 ]
4040 ///       N2 =+[k1 k3 k0 k2 ]
4041 ///            [k0    k2    k1    k3    ]
4042 /// Extended =+[k1    k3    k0    k2    ]
4043 ///            [k0    k2    ]
4044 /// Extracted=+[k1    k3    ]
4045 ///
4046 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4047   EVT VT = N->getValueType(0);
4048   SDLoc DL(N);
4049
4050   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4051
4052   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4053   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4054   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4055   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4056   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4057
4058   if (VT.is64BitVector()) {
4059     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4060     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4061                        DAG.getIntPtrConstant(0));
4062   } else {
4063     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4064                                     DAG.getIntPtrConstant(0));
4065     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4066   }
4067 }
4068
4069 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4070                           const ARMSubtarget *ST) {
4071   EVT VT = N->getValueType(0);
4072
4073   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4074   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4075           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4076          "Unexpected type for custom ctpop lowering");
4077
4078   if (VT.getVectorElementType() == MVT::i32)
4079     return lowerCTPOP32BitElements(N, DAG);
4080   else
4081     return lowerCTPOP16BitElements(N, DAG);
4082 }
4083
4084 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4085                           const ARMSubtarget *ST) {
4086   EVT VT = N->getValueType(0);
4087   SDLoc dl(N);
4088
4089   if (!VT.isVector())
4090     return SDValue();
4091
4092   // Lower vector shifts on NEON to use VSHL.
4093   assert(ST->hasNEON() && "unexpected vector shift");
4094
4095   // Left shifts translate directly to the vshiftu intrinsic.
4096   if (N->getOpcode() == ISD::SHL)
4097     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4098                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4099                        N->getOperand(0), N->getOperand(1));
4100
4101   assert((N->getOpcode() == ISD::SRA ||
4102           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4103
4104   // NEON uses the same intrinsics for both left and right shifts.  For
4105   // right shifts, the shift amounts are negative, so negate the vector of
4106   // shift amounts.
4107   EVT ShiftVT = N->getOperand(1).getValueType();
4108   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4109                                      getZeroVector(ShiftVT, DAG, dl),
4110                                      N->getOperand(1));
4111   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4112                              Intrinsic::arm_neon_vshifts :
4113                              Intrinsic::arm_neon_vshiftu);
4114   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4115                      DAG.getConstant(vshiftInt, MVT::i32),
4116                      N->getOperand(0), NegatedCount);
4117 }
4118
4119 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4120                                 const ARMSubtarget *ST) {
4121   EVT VT = N->getValueType(0);
4122   SDLoc dl(N);
4123
4124   // We can get here for a node like i32 = ISD::SHL i32, i64
4125   if (VT != MVT::i64)
4126     return SDValue();
4127
4128   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4129          "Unknown shift to lower!");
4130
4131   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4132   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4133       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4134     return SDValue();
4135
4136   // If we are in thumb mode, we don't have RRX.
4137   if (ST->isThumb1Only()) return SDValue();
4138
4139   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4140   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4141                            DAG.getConstant(0, MVT::i32));
4142   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4143                            DAG.getConstant(1, MVT::i32));
4144
4145   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4146   // captures the result into a carry flag.
4147   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4148   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
4149
4150   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4151   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4152
4153   // Merge the pieces into a single i64 value.
4154  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4155 }
4156
4157 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4158   SDValue TmpOp0, TmpOp1;
4159   bool Invert = false;
4160   bool Swap = false;
4161   unsigned Opc = 0;
4162
4163   SDValue Op0 = Op.getOperand(0);
4164   SDValue Op1 = Op.getOperand(1);
4165   SDValue CC = Op.getOperand(2);
4166   EVT VT = Op.getValueType();
4167   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4168   SDLoc dl(Op);
4169
4170   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4171     switch (SetCCOpcode) {
4172     default: llvm_unreachable("Illegal FP comparison");
4173     case ISD::SETUNE:
4174     case ISD::SETNE:  Invert = true; // Fallthrough
4175     case ISD::SETOEQ:
4176     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4177     case ISD::SETOLT:
4178     case ISD::SETLT: Swap = true; // Fallthrough
4179     case ISD::SETOGT:
4180     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4181     case ISD::SETOLE:
4182     case ISD::SETLE:  Swap = true; // Fallthrough
4183     case ISD::SETOGE:
4184     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4185     case ISD::SETUGE: Swap = true; // Fallthrough
4186     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4187     case ISD::SETUGT: Swap = true; // Fallthrough
4188     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4189     case ISD::SETUEQ: Invert = true; // Fallthrough
4190     case ISD::SETONE:
4191       // Expand this to (OLT | OGT).
4192       TmpOp0 = Op0;
4193       TmpOp1 = Op1;
4194       Opc = ISD::OR;
4195       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4196       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4197       break;
4198     case ISD::SETUO: Invert = true; // Fallthrough
4199     case ISD::SETO:
4200       // Expand this to (OLT | OGE).
4201       TmpOp0 = Op0;
4202       TmpOp1 = Op1;
4203       Opc = ISD::OR;
4204       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4205       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4206       break;
4207     }
4208   } else {
4209     // Integer comparisons.
4210     switch (SetCCOpcode) {
4211     default: llvm_unreachable("Illegal integer comparison");
4212     case ISD::SETNE:  Invert = true;
4213     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4214     case ISD::SETLT:  Swap = true;
4215     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4216     case ISD::SETLE:  Swap = true;
4217     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4218     case ISD::SETULT: Swap = true;
4219     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4220     case ISD::SETULE: Swap = true;
4221     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4222     }
4223
4224     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4225     if (Opc == ARMISD::VCEQ) {
4226
4227       SDValue AndOp;
4228       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4229         AndOp = Op0;
4230       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4231         AndOp = Op1;
4232
4233       // Ignore bitconvert.
4234       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4235         AndOp = AndOp.getOperand(0);
4236
4237       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4238         Opc = ARMISD::VTST;
4239         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4240         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4241         Invert = !Invert;
4242       }
4243     }
4244   }
4245
4246   if (Swap)
4247     std::swap(Op0, Op1);
4248
4249   // If one of the operands is a constant vector zero, attempt to fold the
4250   // comparison to a specialized compare-against-zero form.
4251   SDValue SingleOp;
4252   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4253     SingleOp = Op0;
4254   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4255     if (Opc == ARMISD::VCGE)
4256       Opc = ARMISD::VCLEZ;
4257     else if (Opc == ARMISD::VCGT)
4258       Opc = ARMISD::VCLTZ;
4259     SingleOp = Op1;
4260   }
4261
4262   SDValue Result;
4263   if (SingleOp.getNode()) {
4264     switch (Opc) {
4265     case ARMISD::VCEQ:
4266       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4267     case ARMISD::VCGE:
4268       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4269     case ARMISD::VCLEZ:
4270       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4271     case ARMISD::VCGT:
4272       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4273     case ARMISD::VCLTZ:
4274       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4275     default:
4276       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4277     }
4278   } else {
4279      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4280   }
4281
4282   if (Invert)
4283     Result = DAG.getNOT(dl, Result, VT);
4284
4285   return Result;
4286 }
4287
4288 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4289 /// valid vector constant for a NEON instruction with a "modified immediate"
4290 /// operand (e.g., VMOV).  If so, return the encoded value.
4291 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4292                                  unsigned SplatBitSize, SelectionDAG &DAG,
4293                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4294   unsigned OpCmode, Imm;
4295
4296   // SplatBitSize is set to the smallest size that splats the vector, so a
4297   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4298   // immediate instructions others than VMOV do not support the 8-bit encoding
4299   // of a zero vector, and the default encoding of zero is supposed to be the
4300   // 32-bit version.
4301   if (SplatBits == 0)
4302     SplatBitSize = 32;
4303
4304   switch (SplatBitSize) {
4305   case 8:
4306     if (type != VMOVModImm)
4307       return SDValue();
4308     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4309     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4310     OpCmode = 0xe;
4311     Imm = SplatBits;
4312     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4313     break;
4314
4315   case 16:
4316     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4317     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4318     if ((SplatBits & ~0xff) == 0) {
4319       // Value = 0x00nn: Op=x, Cmode=100x.
4320       OpCmode = 0x8;
4321       Imm = SplatBits;
4322       break;
4323     }
4324     if ((SplatBits & ~0xff00) == 0) {
4325       // Value = 0xnn00: Op=x, Cmode=101x.
4326       OpCmode = 0xa;
4327       Imm = SplatBits >> 8;
4328       break;
4329     }
4330     return SDValue();
4331
4332   case 32:
4333     // NEON's 32-bit VMOV supports splat values where:
4334     // * only one byte is nonzero, or
4335     // * the least significant byte is 0xff and the second byte is nonzero, or
4336     // * the least significant 2 bytes are 0xff and the third is nonzero.
4337     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4338     if ((SplatBits & ~0xff) == 0) {
4339       // Value = 0x000000nn: Op=x, Cmode=000x.
4340       OpCmode = 0;
4341       Imm = SplatBits;
4342       break;
4343     }
4344     if ((SplatBits & ~0xff00) == 0) {
4345       // Value = 0x0000nn00: Op=x, Cmode=001x.
4346       OpCmode = 0x2;
4347       Imm = SplatBits >> 8;
4348       break;
4349     }
4350     if ((SplatBits & ~0xff0000) == 0) {
4351       // Value = 0x00nn0000: Op=x, Cmode=010x.
4352       OpCmode = 0x4;
4353       Imm = SplatBits >> 16;
4354       break;
4355     }
4356     if ((SplatBits & ~0xff000000) == 0) {
4357       // Value = 0xnn000000: Op=x, Cmode=011x.
4358       OpCmode = 0x6;
4359       Imm = SplatBits >> 24;
4360       break;
4361     }
4362
4363     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4364     if (type == OtherModImm) return SDValue();
4365
4366     if ((SplatBits & ~0xffff) == 0 &&
4367         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4368       // Value = 0x0000nnff: Op=x, Cmode=1100.
4369       OpCmode = 0xc;
4370       Imm = SplatBits >> 8;
4371       SplatBits |= 0xff;
4372       break;
4373     }
4374
4375     if ((SplatBits & ~0xffffff) == 0 &&
4376         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4377       // Value = 0x00nnffff: Op=x, Cmode=1101.
4378       OpCmode = 0xd;
4379       Imm = SplatBits >> 16;
4380       SplatBits |= 0xffff;
4381       break;
4382     }
4383
4384     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4385     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4386     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4387     // and fall through here to test for a valid 64-bit splat.  But, then the
4388     // caller would also need to check and handle the change in size.
4389     return SDValue();
4390
4391   case 64: {
4392     if (type != VMOVModImm)
4393       return SDValue();
4394     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4395     uint64_t BitMask = 0xff;
4396     uint64_t Val = 0;
4397     unsigned ImmMask = 1;
4398     Imm = 0;
4399     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4400       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4401         Val |= BitMask;
4402         Imm |= ImmMask;
4403       } else if ((SplatBits & BitMask) != 0) {
4404         return SDValue();
4405       }
4406       BitMask <<= 8;
4407       ImmMask <<= 1;
4408     }
4409     // Op=1, Cmode=1110.
4410     OpCmode = 0x1e;
4411     SplatBits = Val;
4412     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4413     break;
4414   }
4415
4416   default:
4417     llvm_unreachable("unexpected size for isNEONModifiedImm");
4418   }
4419
4420   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4421   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4422 }
4423
4424 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4425                                            const ARMSubtarget *ST) const {
4426   if (!ST->hasVFP3())
4427     return SDValue();
4428
4429   bool IsDouble = Op.getValueType() == MVT::f64;
4430   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4431
4432   // Try splatting with a VMOV.f32...
4433   APFloat FPVal = CFP->getValueAPF();
4434   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4435
4436   if (ImmVal != -1) {
4437     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4438       // We have code in place to select a valid ConstantFP already, no need to
4439       // do any mangling.
4440       return Op;
4441     }
4442
4443     // It's a float and we are trying to use NEON operations where
4444     // possible. Lower it to a splat followed by an extract.
4445     SDLoc DL(Op);
4446     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4447     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4448                                       NewVal);
4449     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4450                        DAG.getConstant(0, MVT::i32));
4451   }
4452
4453   // The rest of our options are NEON only, make sure that's allowed before
4454   // proceeding..
4455   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4456     return SDValue();
4457
4458   EVT VMovVT;
4459   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4460
4461   // It wouldn't really be worth bothering for doubles except for one very
4462   // important value, which does happen to match: 0.0. So make sure we don't do
4463   // anything stupid.
4464   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4465     return SDValue();
4466
4467   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4468   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4469                                      false, VMOVModImm);
4470   if (NewVal != SDValue()) {
4471     SDLoc DL(Op);
4472     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4473                                       NewVal);
4474     if (IsDouble)
4475       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4476
4477     // It's a float: cast and extract a vector element.
4478     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4479                                        VecConstant);
4480     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4481                        DAG.getConstant(0, MVT::i32));
4482   }
4483
4484   // Finally, try a VMVN.i32
4485   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4486                              false, VMVNModImm);
4487   if (NewVal != SDValue()) {
4488     SDLoc DL(Op);
4489     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4490
4491     if (IsDouble)
4492       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4493
4494     // It's a float: cast and extract a vector element.
4495     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4496                                        VecConstant);
4497     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4498                        DAG.getConstant(0, MVT::i32));
4499   }
4500
4501   return SDValue();
4502 }
4503
4504 // check if an VEXT instruction can handle the shuffle mask when the
4505 // vector sources of the shuffle are the same.
4506 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4507   unsigned NumElts = VT.getVectorNumElements();
4508
4509   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4510   if (M[0] < 0)
4511     return false;
4512
4513   Imm = M[0];
4514
4515   // If this is a VEXT shuffle, the immediate value is the index of the first
4516   // element.  The other shuffle indices must be the successive elements after
4517   // the first one.
4518   unsigned ExpectedElt = Imm;
4519   for (unsigned i = 1; i < NumElts; ++i) {
4520     // Increment the expected index.  If it wraps around, just follow it
4521     // back to index zero and keep going.
4522     ++ExpectedElt;
4523     if (ExpectedElt == NumElts)
4524       ExpectedElt = 0;
4525
4526     if (M[i] < 0) continue; // ignore UNDEF indices
4527     if (ExpectedElt != static_cast<unsigned>(M[i]))
4528       return false;
4529   }
4530
4531   return true;
4532 }
4533
4534
4535 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4536                        bool &ReverseVEXT, unsigned &Imm) {
4537   unsigned NumElts = VT.getVectorNumElements();
4538   ReverseVEXT = false;
4539
4540   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4541   if (M[0] < 0)
4542     return false;
4543
4544   Imm = M[0];
4545
4546   // If this is a VEXT shuffle, the immediate value is the index of the first
4547   // element.  The other shuffle indices must be the successive elements after
4548   // the first one.
4549   unsigned ExpectedElt = Imm;
4550   for (unsigned i = 1; i < NumElts; ++i) {
4551     // Increment the expected index.  If it wraps around, it may still be
4552     // a VEXT but the source vectors must be swapped.
4553     ExpectedElt += 1;
4554     if (ExpectedElt == NumElts * 2) {
4555       ExpectedElt = 0;
4556       ReverseVEXT = true;
4557     }
4558
4559     if (M[i] < 0) continue; // ignore UNDEF indices
4560     if (ExpectedElt != static_cast<unsigned>(M[i]))
4561       return false;
4562   }
4563
4564   // Adjust the index value if the source operands will be swapped.
4565   if (ReverseVEXT)
4566     Imm -= NumElts;
4567
4568   return true;
4569 }
4570
4571 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4572 /// instruction with the specified blocksize.  (The order of the elements
4573 /// within each block of the vector is reversed.)
4574 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4575   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4576          "Only possible block sizes for VREV are: 16, 32, 64");
4577
4578   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4579   if (EltSz == 64)
4580     return false;
4581
4582   unsigned NumElts = VT.getVectorNumElements();
4583   unsigned BlockElts = M[0] + 1;
4584   // If the first shuffle index is UNDEF, be optimistic.
4585   if (M[0] < 0)
4586     BlockElts = BlockSize / EltSz;
4587
4588   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4589     return false;
4590
4591   for (unsigned i = 0; i < NumElts; ++i) {
4592     if (M[i] < 0) continue; // ignore UNDEF indices
4593     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4594       return false;
4595   }
4596
4597   return true;
4598 }
4599
4600 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4601   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4602   // range, then 0 is placed into the resulting vector. So pretty much any mask
4603   // of 8 elements can work here.
4604   return VT == MVT::v8i8 && M.size() == 8;
4605 }
4606
4607 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4608   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4609   if (EltSz == 64)
4610     return false;
4611
4612   unsigned NumElts = VT.getVectorNumElements();
4613   WhichResult = (M[0] == 0 ? 0 : 1);
4614   for (unsigned i = 0; i < NumElts; i += 2) {
4615     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4616         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4617       return false;
4618   }
4619   return true;
4620 }
4621
4622 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4623 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4624 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4625 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4626   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4627   if (EltSz == 64)
4628     return false;
4629
4630   unsigned NumElts = VT.getVectorNumElements();
4631   WhichResult = (M[0] == 0 ? 0 : 1);
4632   for (unsigned i = 0; i < NumElts; i += 2) {
4633     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4634         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4635       return false;
4636   }
4637   return true;
4638 }
4639
4640 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4641   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4642   if (EltSz == 64)
4643     return false;
4644
4645   unsigned NumElts = VT.getVectorNumElements();
4646   WhichResult = (M[0] == 0 ? 0 : 1);
4647   for (unsigned i = 0; i != NumElts; ++i) {
4648     if (M[i] < 0) continue; // ignore UNDEF indices
4649     if ((unsigned) M[i] != 2 * i + WhichResult)
4650       return false;
4651   }
4652
4653   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4654   if (VT.is64BitVector() && EltSz == 32)
4655     return false;
4656
4657   return true;
4658 }
4659
4660 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4661 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4662 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4663 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4664   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4665   if (EltSz == 64)
4666     return false;
4667
4668   unsigned Half = VT.getVectorNumElements() / 2;
4669   WhichResult = (M[0] == 0 ? 0 : 1);
4670   for (unsigned j = 0; j != 2; ++j) {
4671     unsigned Idx = WhichResult;
4672     for (unsigned i = 0; i != Half; ++i) {
4673       int MIdx = M[i + j * Half];
4674       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4675         return false;
4676       Idx += 2;
4677     }
4678   }
4679
4680   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4681   if (VT.is64BitVector() && EltSz == 32)
4682     return false;
4683
4684   return true;
4685 }
4686
4687 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4688   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4689   if (EltSz == 64)
4690     return false;
4691
4692   unsigned NumElts = VT.getVectorNumElements();
4693   WhichResult = (M[0] == 0 ? 0 : 1);
4694   unsigned Idx = WhichResult * NumElts / 2;
4695   for (unsigned i = 0; i != NumElts; i += 2) {
4696     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4697         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4698       return false;
4699     Idx += 1;
4700   }
4701
4702   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4703   if (VT.is64BitVector() && EltSz == 32)
4704     return false;
4705
4706   return true;
4707 }
4708
4709 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4710 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4711 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4712 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4713   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4714   if (EltSz == 64)
4715     return false;
4716
4717   unsigned NumElts = VT.getVectorNumElements();
4718   WhichResult = (M[0] == 0 ? 0 : 1);
4719   unsigned Idx = WhichResult * NumElts / 2;
4720   for (unsigned i = 0; i != NumElts; i += 2) {
4721     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4722         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4723       return false;
4724     Idx += 1;
4725   }
4726
4727   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4728   if (VT.is64BitVector() && EltSz == 32)
4729     return false;
4730
4731   return true;
4732 }
4733
4734 /// \return true if this is a reverse operation on an vector.
4735 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4736   unsigned NumElts = VT.getVectorNumElements();
4737   // Make sure the mask has the right size.
4738   if (NumElts != M.size())
4739       return false;
4740
4741   // Look for <15, ..., 3, -1, 1, 0>.
4742   for (unsigned i = 0; i != NumElts; ++i)
4743     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4744       return false;
4745
4746   return true;
4747 }
4748
4749 // If N is an integer constant that can be moved into a register in one
4750 // instruction, return an SDValue of such a constant (will become a MOV
4751 // instruction).  Otherwise return null.
4752 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4753                                      const ARMSubtarget *ST, SDLoc dl) {
4754   uint64_t Val;
4755   if (!isa<ConstantSDNode>(N))
4756     return SDValue();
4757   Val = cast<ConstantSDNode>(N)->getZExtValue();
4758
4759   if (ST->isThumb1Only()) {
4760     if (Val <= 255 || ~Val <= 255)
4761       return DAG.getConstant(Val, MVT::i32);
4762   } else {
4763     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4764       return DAG.getConstant(Val, MVT::i32);
4765   }
4766   return SDValue();
4767 }
4768
4769 // If this is a case we can't handle, return null and let the default
4770 // expansion code take care of it.
4771 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4772                                              const ARMSubtarget *ST) const {
4773   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4774   SDLoc dl(Op);
4775   EVT VT = Op.getValueType();
4776
4777   APInt SplatBits, SplatUndef;
4778   unsigned SplatBitSize;
4779   bool HasAnyUndefs;
4780   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4781     if (SplatBitSize <= 64) {
4782       // Check if an immediate VMOV works.
4783       EVT VmovVT;
4784       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4785                                       SplatUndef.getZExtValue(), SplatBitSize,
4786                                       DAG, VmovVT, VT.is128BitVector(),
4787                                       VMOVModImm);
4788       if (Val.getNode()) {
4789         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4790         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4791       }
4792
4793       // Try an immediate VMVN.
4794       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4795       Val = isNEONModifiedImm(NegatedImm,
4796                                       SplatUndef.getZExtValue(), SplatBitSize,
4797                                       DAG, VmovVT, VT.is128BitVector(),
4798                                       VMVNModImm);
4799       if (Val.getNode()) {
4800         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4801         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4802       }
4803
4804       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4805       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4806         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4807         if (ImmVal != -1) {
4808           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4809           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4810         }
4811       }
4812     }
4813   }
4814
4815   // Scan through the operands to see if only one value is used.
4816   //
4817   // As an optimisation, even if more than one value is used it may be more
4818   // profitable to splat with one value then change some lanes.
4819   //
4820   // Heuristically we decide to do this if the vector has a "dominant" value,
4821   // defined as splatted to more than half of the lanes.
4822   unsigned NumElts = VT.getVectorNumElements();
4823   bool isOnlyLowElement = true;
4824   bool usesOnlyOneValue = true;
4825   bool hasDominantValue = false;
4826   bool isConstant = true;
4827
4828   // Map of the number of times a particular SDValue appears in the
4829   // element list.
4830   DenseMap<SDValue, unsigned> ValueCounts;
4831   SDValue Value;
4832   for (unsigned i = 0; i < NumElts; ++i) {
4833     SDValue V = Op.getOperand(i);
4834     if (V.getOpcode() == ISD::UNDEF)
4835       continue;
4836     if (i > 0)
4837       isOnlyLowElement = false;
4838     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4839       isConstant = false;
4840
4841     ValueCounts.insert(std::make_pair(V, 0));
4842     unsigned &Count = ValueCounts[V];
4843
4844     // Is this value dominant? (takes up more than half of the lanes)
4845     if (++Count > (NumElts / 2)) {
4846       hasDominantValue = true;
4847       Value = V;
4848     }
4849   }
4850   if (ValueCounts.size() != 1)
4851     usesOnlyOneValue = false;
4852   if (!Value.getNode() && ValueCounts.size() > 0)
4853     Value = ValueCounts.begin()->first;
4854
4855   if (ValueCounts.size() == 0)
4856     return DAG.getUNDEF(VT);
4857
4858   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
4859   // Keep going if we are hitting this case.
4860   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
4861     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4862
4863   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4864
4865   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4866   // i32 and try again.
4867   if (hasDominantValue && EltSize <= 32) {
4868     if (!isConstant) {
4869       SDValue N;
4870
4871       // If we are VDUPing a value that comes directly from a vector, that will
4872       // cause an unnecessary move to and from a GPR, where instead we could
4873       // just use VDUPLANE. We can only do this if the lane being extracted
4874       // is at a constant index, as the VDUP from lane instructions only have
4875       // constant-index forms.
4876       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4877           isa<ConstantSDNode>(Value->getOperand(1))) {
4878         // We need to create a new undef vector to use for the VDUPLANE if the
4879         // size of the vector from which we get the value is different than the
4880         // size of the vector that we need to create. We will insert the element
4881         // such that the register coalescer will remove unnecessary copies.
4882         if (VT != Value->getOperand(0).getValueType()) {
4883           ConstantSDNode *constIndex;
4884           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4885           assert(constIndex && "The index is not a constant!");
4886           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4887                              VT.getVectorNumElements();
4888           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4889                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4890                         Value, DAG.getConstant(index, MVT::i32)),
4891                            DAG.getConstant(index, MVT::i32));
4892         } else
4893           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4894                         Value->getOperand(0), Value->getOperand(1));
4895       } else
4896         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4897
4898       if (!usesOnlyOneValue) {
4899         // The dominant value was splatted as 'N', but we now have to insert
4900         // all differing elements.
4901         for (unsigned I = 0; I < NumElts; ++I) {
4902           if (Op.getOperand(I) == Value)
4903             continue;
4904           SmallVector<SDValue, 3> Ops;
4905           Ops.push_back(N);
4906           Ops.push_back(Op.getOperand(I));
4907           Ops.push_back(DAG.getConstant(I, MVT::i32));
4908           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4909         }
4910       }
4911       return N;
4912     }
4913     if (VT.getVectorElementType().isFloatingPoint()) {
4914       SmallVector<SDValue, 8> Ops;
4915       for (unsigned i = 0; i < NumElts; ++i)
4916         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4917                                   Op.getOperand(i)));
4918       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4919       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4920       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4921       if (Val.getNode())
4922         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4923     }
4924     if (usesOnlyOneValue) {
4925       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4926       if (isConstant && Val.getNode())
4927         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4928     }
4929   }
4930
4931   // If all elements are constants and the case above didn't get hit, fall back
4932   // to the default expansion, which will generate a load from the constant
4933   // pool.
4934   if (isConstant)
4935     return SDValue();
4936
4937   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4938   if (NumElts >= 4) {
4939     SDValue shuffle = ReconstructShuffle(Op, DAG);
4940     if (shuffle != SDValue())
4941       return shuffle;
4942   }
4943
4944   // Vectors with 32- or 64-bit elements can be built by directly assigning
4945   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4946   // will be legalized.
4947   if (EltSize >= 32) {
4948     // Do the expansion with floating-point types, since that is what the VFP
4949     // registers are defined to use, and since i64 is not legal.
4950     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4951     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4952     SmallVector<SDValue, 8> Ops;
4953     for (unsigned i = 0; i < NumElts; ++i)
4954       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4955     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4956     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4957   }
4958
4959   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
4960   // know the default expansion would otherwise fall back on something even
4961   // worse. For a vector with one or two non-undef values, that's
4962   // scalar_to_vector for the elements followed by a shuffle (provided the
4963   // shuffle is valid for the target) and materialization element by element
4964   // on the stack followed by a load for everything else.
4965   if (!isConstant && !usesOnlyOneValue) {
4966     SDValue Vec = DAG.getUNDEF(VT);
4967     for (unsigned i = 0 ; i < NumElts; ++i) {
4968       SDValue V = Op.getOperand(i);
4969       if (V.getOpcode() == ISD::UNDEF)
4970         continue;
4971       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
4972       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
4973     }
4974     return Vec;
4975   }
4976
4977   return SDValue();
4978 }
4979
4980 // Gather data to see if the operation can be modelled as a
4981 // shuffle in combination with VEXTs.
4982 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4983                                               SelectionDAG &DAG) const {
4984   SDLoc dl(Op);
4985   EVT VT = Op.getValueType();
4986   unsigned NumElts = VT.getVectorNumElements();
4987
4988   SmallVector<SDValue, 2> SourceVecs;
4989   SmallVector<unsigned, 2> MinElts;
4990   SmallVector<unsigned, 2> MaxElts;
4991
4992   for (unsigned i = 0; i < NumElts; ++i) {
4993     SDValue V = Op.getOperand(i);
4994     if (V.getOpcode() == ISD::UNDEF)
4995       continue;
4996     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4997       // A shuffle can only come from building a vector from various
4998       // elements of other vectors.
4999       return SDValue();
5000     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5001                VT.getVectorElementType()) {
5002       // This code doesn't know how to handle shuffles where the vector
5003       // element types do not match (this happens because type legalization
5004       // promotes the return type of EXTRACT_VECTOR_ELT).
5005       // FIXME: It might be appropriate to extend this code to handle
5006       // mismatched types.
5007       return SDValue();
5008     }
5009
5010     // Record this extraction against the appropriate vector if possible...
5011     SDValue SourceVec = V.getOperand(0);
5012     // If the element number isn't a constant, we can't effectively
5013     // analyze what's going on.
5014     if (!isa<ConstantSDNode>(V.getOperand(1)))
5015       return SDValue();
5016     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5017     bool FoundSource = false;
5018     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5019       if (SourceVecs[j] == SourceVec) {
5020         if (MinElts[j] > EltNo)
5021           MinElts[j] = EltNo;
5022         if (MaxElts[j] < EltNo)
5023           MaxElts[j] = EltNo;
5024         FoundSource = true;
5025         break;
5026       }
5027     }
5028
5029     // Or record a new source if not...
5030     if (!FoundSource) {
5031       SourceVecs.push_back(SourceVec);
5032       MinElts.push_back(EltNo);
5033       MaxElts.push_back(EltNo);
5034     }
5035   }
5036
5037   // Currently only do something sane when at most two source vectors
5038   // involved.
5039   if (SourceVecs.size() > 2)
5040     return SDValue();
5041
5042   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5043   int VEXTOffsets[2] = {0, 0};
5044
5045   // This loop extracts the usage patterns of the source vectors
5046   // and prepares appropriate SDValues for a shuffle if possible.
5047   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5048     if (SourceVecs[i].getValueType() == VT) {
5049       // No VEXT necessary
5050       ShuffleSrcs[i] = SourceVecs[i];
5051       VEXTOffsets[i] = 0;
5052       continue;
5053     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5054       // It probably isn't worth padding out a smaller vector just to
5055       // break it down again in a shuffle.
5056       return SDValue();
5057     }
5058
5059     // Since only 64-bit and 128-bit vectors are legal on ARM and
5060     // we've eliminated the other cases...
5061     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5062            "unexpected vector sizes in ReconstructShuffle");
5063
5064     if (MaxElts[i] - MinElts[i] >= NumElts) {
5065       // Span too large for a VEXT to cope
5066       return SDValue();
5067     }
5068
5069     if (MinElts[i] >= NumElts) {
5070       // The extraction can just take the second half
5071       VEXTOffsets[i] = NumElts;
5072       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5073                                    SourceVecs[i],
5074                                    DAG.getIntPtrConstant(NumElts));
5075     } else if (MaxElts[i] < NumElts) {
5076       // The extraction can just take the first half
5077       VEXTOffsets[i] = 0;
5078       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5079                                    SourceVecs[i],
5080                                    DAG.getIntPtrConstant(0));
5081     } else {
5082       // An actual VEXT is needed
5083       VEXTOffsets[i] = MinElts[i];
5084       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5085                                      SourceVecs[i],
5086                                      DAG.getIntPtrConstant(0));
5087       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5088                                      SourceVecs[i],
5089                                      DAG.getIntPtrConstant(NumElts));
5090       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5091                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5092     }
5093   }
5094
5095   SmallVector<int, 8> Mask;
5096
5097   for (unsigned i = 0; i < NumElts; ++i) {
5098     SDValue Entry = Op.getOperand(i);
5099     if (Entry.getOpcode() == ISD::UNDEF) {
5100       Mask.push_back(-1);
5101       continue;
5102     }
5103
5104     SDValue ExtractVec = Entry.getOperand(0);
5105     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5106                                           .getOperand(1))->getSExtValue();
5107     if (ExtractVec == SourceVecs[0]) {
5108       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5109     } else {
5110       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5111     }
5112   }
5113
5114   // Final check before we try to produce nonsense...
5115   if (isShuffleMaskLegal(Mask, VT))
5116     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5117                                 &Mask[0]);
5118
5119   return SDValue();
5120 }
5121
5122 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5123 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5124 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5125 /// are assumed to be legal.
5126 bool
5127 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5128                                       EVT VT) const {
5129   if (VT.getVectorNumElements() == 4 &&
5130       (VT.is128BitVector() || VT.is64BitVector())) {
5131     unsigned PFIndexes[4];
5132     for (unsigned i = 0; i != 4; ++i) {
5133       if (M[i] < 0)
5134         PFIndexes[i] = 8;
5135       else
5136         PFIndexes[i] = M[i];
5137     }
5138
5139     // Compute the index in the perfect shuffle table.
5140     unsigned PFTableIndex =
5141       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5142     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5143     unsigned Cost = (PFEntry >> 30);
5144
5145     if (Cost <= 4)
5146       return true;
5147   }
5148
5149   bool ReverseVEXT;
5150   unsigned Imm, WhichResult;
5151
5152   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5153   return (EltSize >= 32 ||
5154           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5155           isVREVMask(M, VT, 64) ||
5156           isVREVMask(M, VT, 32) ||
5157           isVREVMask(M, VT, 16) ||
5158           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5159           isVTBLMask(M, VT) ||
5160           isVTRNMask(M, VT, WhichResult) ||
5161           isVUZPMask(M, VT, WhichResult) ||
5162           isVZIPMask(M, VT, WhichResult) ||
5163           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5164           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5165           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5166           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5167 }
5168
5169 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5170 /// the specified operations to build the shuffle.
5171 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5172                                       SDValue RHS, SelectionDAG &DAG,
5173                                       SDLoc dl) {
5174   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5175   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5176   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5177
5178   enum {
5179     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5180     OP_VREV,
5181     OP_VDUP0,
5182     OP_VDUP1,
5183     OP_VDUP2,
5184     OP_VDUP3,
5185     OP_VEXT1,
5186     OP_VEXT2,
5187     OP_VEXT3,
5188     OP_VUZPL, // VUZP, left result
5189     OP_VUZPR, // VUZP, right result
5190     OP_VZIPL, // VZIP, left result
5191     OP_VZIPR, // VZIP, right result
5192     OP_VTRNL, // VTRN, left result
5193     OP_VTRNR  // VTRN, right result
5194   };
5195
5196   if (OpNum == OP_COPY) {
5197     if (LHSID == (1*9+2)*9+3) return LHS;
5198     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5199     return RHS;
5200   }
5201
5202   SDValue OpLHS, OpRHS;
5203   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5204   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5205   EVT VT = OpLHS.getValueType();
5206
5207   switch (OpNum) {
5208   default: llvm_unreachable("Unknown shuffle opcode!");
5209   case OP_VREV:
5210     // VREV divides the vector in half and swaps within the half.
5211     if (VT.getVectorElementType() == MVT::i32 ||
5212         VT.getVectorElementType() == MVT::f32)
5213       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5214     // vrev <4 x i16> -> VREV32
5215     if (VT.getVectorElementType() == MVT::i16)
5216       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5217     // vrev <4 x i8> -> VREV16
5218     assert(VT.getVectorElementType() == MVT::i8);
5219     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5220   case OP_VDUP0:
5221   case OP_VDUP1:
5222   case OP_VDUP2:
5223   case OP_VDUP3:
5224     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5225                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5226   case OP_VEXT1:
5227   case OP_VEXT2:
5228   case OP_VEXT3:
5229     return DAG.getNode(ARMISD::VEXT, dl, VT,
5230                        OpLHS, OpRHS,
5231                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5232   case OP_VUZPL:
5233   case OP_VUZPR:
5234     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5235                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5236   case OP_VZIPL:
5237   case OP_VZIPR:
5238     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5239                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5240   case OP_VTRNL:
5241   case OP_VTRNR:
5242     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5243                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5244   }
5245 }
5246
5247 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5248                                        ArrayRef<int> ShuffleMask,
5249                                        SelectionDAG &DAG) {
5250   // Check to see if we can use the VTBL instruction.
5251   SDValue V1 = Op.getOperand(0);
5252   SDValue V2 = Op.getOperand(1);
5253   SDLoc DL(Op);
5254
5255   SmallVector<SDValue, 8> VTBLMask;
5256   for (ArrayRef<int>::iterator
5257          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5258     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5259
5260   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5261     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5262                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5263                                    &VTBLMask[0], 8));
5264
5265   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5266                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5267                                  &VTBLMask[0], 8));
5268 }
5269
5270 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5271                                                       SelectionDAG &DAG) {
5272   SDLoc DL(Op);
5273   SDValue OpLHS = Op.getOperand(0);
5274   EVT VT = OpLHS.getValueType();
5275
5276   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5277          "Expect an v8i16/v16i8 type");
5278   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5279   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5280   // extract the first 8 bytes into the top double word and the last 8 bytes
5281   // into the bottom double word. The v8i16 case is similar.
5282   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5283   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5284                      DAG.getConstant(ExtractNum, MVT::i32));
5285 }
5286
5287 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5288   SDValue V1 = Op.getOperand(0);
5289   SDValue V2 = Op.getOperand(1);
5290   SDLoc dl(Op);
5291   EVT VT = Op.getValueType();
5292   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5293
5294   // Convert shuffles that are directly supported on NEON to target-specific
5295   // DAG nodes, instead of keeping them as shuffles and matching them again
5296   // during code selection.  This is more efficient and avoids the possibility
5297   // of inconsistencies between legalization and selection.
5298   // FIXME: floating-point vectors should be canonicalized to integer vectors
5299   // of the same time so that they get CSEd properly.
5300   ArrayRef<int> ShuffleMask = SVN->getMask();
5301
5302   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5303   if (EltSize <= 32) {
5304     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5305       int Lane = SVN->getSplatIndex();
5306       // If this is undef splat, generate it via "just" vdup, if possible.
5307       if (Lane == -1) Lane = 0;
5308
5309       // Test if V1 is a SCALAR_TO_VECTOR.
5310       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5311         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5312       }
5313       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5314       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5315       // reaches it).
5316       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5317           !isa<ConstantSDNode>(V1.getOperand(0))) {
5318         bool IsScalarToVector = true;
5319         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5320           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5321             IsScalarToVector = false;
5322             break;
5323           }
5324         if (IsScalarToVector)
5325           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5326       }
5327       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5328                          DAG.getConstant(Lane, MVT::i32));
5329     }
5330
5331     bool ReverseVEXT;
5332     unsigned Imm;
5333     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5334       if (ReverseVEXT)
5335         std::swap(V1, V2);
5336       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5337                          DAG.getConstant(Imm, MVT::i32));
5338     }
5339
5340     if (isVREVMask(ShuffleMask, VT, 64))
5341       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5342     if (isVREVMask(ShuffleMask, VT, 32))
5343       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5344     if (isVREVMask(ShuffleMask, VT, 16))
5345       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5346
5347     if (V2->getOpcode() == ISD::UNDEF &&
5348         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5349       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5350                          DAG.getConstant(Imm, MVT::i32));
5351     }
5352
5353     // Check for Neon shuffles that modify both input vectors in place.
5354     // If both results are used, i.e., if there are two shuffles with the same
5355     // source operands and with masks corresponding to both results of one of
5356     // these operations, DAG memoization will ensure that a single node is
5357     // used for both shuffles.
5358     unsigned WhichResult;
5359     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5360       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5361                          V1, V2).getValue(WhichResult);
5362     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5363       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5364                          V1, V2).getValue(WhichResult);
5365     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5366       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5367                          V1, V2).getValue(WhichResult);
5368
5369     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5370       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5371                          V1, V1).getValue(WhichResult);
5372     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5373       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5374                          V1, V1).getValue(WhichResult);
5375     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5376       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5377                          V1, V1).getValue(WhichResult);
5378   }
5379
5380   // If the shuffle is not directly supported and it has 4 elements, use
5381   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5382   unsigned NumElts = VT.getVectorNumElements();
5383   if (NumElts == 4) {
5384     unsigned PFIndexes[4];
5385     for (unsigned i = 0; i != 4; ++i) {
5386       if (ShuffleMask[i] < 0)
5387         PFIndexes[i] = 8;
5388       else
5389         PFIndexes[i] = ShuffleMask[i];
5390     }
5391
5392     // Compute the index in the perfect shuffle table.
5393     unsigned PFTableIndex =
5394       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5395     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5396     unsigned Cost = (PFEntry >> 30);
5397
5398     if (Cost <= 4)
5399       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5400   }
5401
5402   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5403   if (EltSize >= 32) {
5404     // Do the expansion with floating-point types, since that is what the VFP
5405     // registers are defined to use, and since i64 is not legal.
5406     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5407     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5408     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5409     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5410     SmallVector<SDValue, 8> Ops;
5411     for (unsigned i = 0; i < NumElts; ++i) {
5412       if (ShuffleMask[i] < 0)
5413         Ops.push_back(DAG.getUNDEF(EltVT));
5414       else
5415         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5416                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5417                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5418                                                   MVT::i32)));
5419     }
5420     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5421     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5422   }
5423
5424   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5425     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5426
5427   if (VT == MVT::v8i8) {
5428     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5429     if (NewOp.getNode())
5430       return NewOp;
5431   }
5432
5433   return SDValue();
5434 }
5435
5436 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5437   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5438   SDValue Lane = Op.getOperand(2);
5439   if (!isa<ConstantSDNode>(Lane))
5440     return SDValue();
5441
5442   return Op;
5443 }
5444
5445 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5446   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5447   SDValue Lane = Op.getOperand(1);
5448   if (!isa<ConstantSDNode>(Lane))
5449     return SDValue();
5450
5451   SDValue Vec = Op.getOperand(0);
5452   if (Op.getValueType() == MVT::i32 &&
5453       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5454     SDLoc dl(Op);
5455     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5456   }
5457
5458   return Op;
5459 }
5460
5461 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5462   // The only time a CONCAT_VECTORS operation can have legal types is when
5463   // two 64-bit vectors are concatenated to a 128-bit vector.
5464   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5465          "unexpected CONCAT_VECTORS");
5466   SDLoc dl(Op);
5467   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5468   SDValue Op0 = Op.getOperand(0);
5469   SDValue Op1 = Op.getOperand(1);
5470   if (Op0.getOpcode() != ISD::UNDEF)
5471     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5472                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5473                       DAG.getIntPtrConstant(0));
5474   if (Op1.getOpcode() != ISD::UNDEF)
5475     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5476                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5477                       DAG.getIntPtrConstant(1));
5478   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5479 }
5480
5481 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5482 /// element has been zero/sign-extended, depending on the isSigned parameter,
5483 /// from an integer type half its size.
5484 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5485                                    bool isSigned) {
5486   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5487   EVT VT = N->getValueType(0);
5488   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5489     SDNode *BVN = N->getOperand(0).getNode();
5490     if (BVN->getValueType(0) != MVT::v4i32 ||
5491         BVN->getOpcode() != ISD::BUILD_VECTOR)
5492       return false;
5493     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5494     unsigned HiElt = 1 - LoElt;
5495     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5496     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5497     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5498     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5499     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5500       return false;
5501     if (isSigned) {
5502       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5503           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5504         return true;
5505     } else {
5506       if (Hi0->isNullValue() && Hi1->isNullValue())
5507         return true;
5508     }
5509     return false;
5510   }
5511
5512   if (N->getOpcode() != ISD::BUILD_VECTOR)
5513     return false;
5514
5515   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5516     SDNode *Elt = N->getOperand(i).getNode();
5517     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5518       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5519       unsigned HalfSize = EltSize / 2;
5520       if (isSigned) {
5521         if (!isIntN(HalfSize, C->getSExtValue()))
5522           return false;
5523       } else {
5524         if (!isUIntN(HalfSize, C->getZExtValue()))
5525           return false;
5526       }
5527       continue;
5528     }
5529     return false;
5530   }
5531
5532   return true;
5533 }
5534
5535 /// isSignExtended - Check if a node is a vector value that is sign-extended
5536 /// or a constant BUILD_VECTOR with sign-extended elements.
5537 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5538   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5539     return true;
5540   if (isExtendedBUILD_VECTOR(N, DAG, true))
5541     return true;
5542   return false;
5543 }
5544
5545 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5546 /// or a constant BUILD_VECTOR with zero-extended elements.
5547 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5548   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5549     return true;
5550   if (isExtendedBUILD_VECTOR(N, DAG, false))
5551     return true;
5552   return false;
5553 }
5554
5555 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5556   if (OrigVT.getSizeInBits() >= 64)
5557     return OrigVT;
5558
5559   assert(OrigVT.isSimple() && "Expecting a simple value type");
5560
5561   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5562   switch (OrigSimpleTy) {
5563   default: llvm_unreachable("Unexpected Vector Type");
5564   case MVT::v2i8:
5565   case MVT::v2i16:
5566      return MVT::v2i32;
5567   case MVT::v4i8:
5568     return  MVT::v4i16;
5569   }
5570 }
5571
5572 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5573 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5574 /// We insert the required extension here to get the vector to fill a D register.
5575 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5576                                             const EVT &OrigTy,
5577                                             const EVT &ExtTy,
5578                                             unsigned ExtOpcode) {
5579   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5580   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5581   // 64-bits we need to insert a new extension so that it will be 64-bits.
5582   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5583   if (OrigTy.getSizeInBits() >= 64)
5584     return N;
5585
5586   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5587   EVT NewVT = getExtensionTo64Bits(OrigTy);
5588
5589   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5590 }
5591
5592 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5593 /// does not do any sign/zero extension. If the original vector is less
5594 /// than 64 bits, an appropriate extension will be added after the load to
5595 /// reach a total size of 64 bits. We have to add the extension separately
5596 /// because ARM does not have a sign/zero extending load for vectors.
5597 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5598   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5599
5600   // The load already has the right type.
5601   if (ExtendedTy == LD->getMemoryVT())
5602     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5603                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5604                 LD->isNonTemporal(), LD->isInvariant(),
5605                 LD->getAlignment());
5606
5607   // We need to create a zextload/sextload. We cannot just create a load
5608   // followed by a zext/zext node because LowerMUL is also run during normal
5609   // operation legalization where we can't create illegal types.
5610   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5611                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5612                         LD->getMemoryVT(), LD->isVolatile(),
5613                         LD->isNonTemporal(), LD->getAlignment());
5614 }
5615
5616 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5617 /// extending load, or BUILD_VECTOR with extended elements, return the
5618 /// unextended value. The unextended vector should be 64 bits so that it can
5619 /// be used as an operand to a VMULL instruction. If the original vector size
5620 /// before extension is less than 64 bits we add a an extension to resize
5621 /// the vector to 64 bits.
5622 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5623   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5624     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5625                                         N->getOperand(0)->getValueType(0),
5626                                         N->getValueType(0),
5627                                         N->getOpcode());
5628
5629   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5630     return SkipLoadExtensionForVMULL(LD, DAG);
5631
5632   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5633   // have been legalized as a BITCAST from v4i32.
5634   if (N->getOpcode() == ISD::BITCAST) {
5635     SDNode *BVN = N->getOperand(0).getNode();
5636     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5637            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5638     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5639     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5640                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5641   }
5642   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5643   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5644   EVT VT = N->getValueType(0);
5645   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5646   unsigned NumElts = VT.getVectorNumElements();
5647   MVT TruncVT = MVT::getIntegerVT(EltSize);
5648   SmallVector<SDValue, 8> Ops;
5649   for (unsigned i = 0; i != NumElts; ++i) {
5650     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5651     const APInt &CInt = C->getAPIntValue();
5652     // Element types smaller than 32 bits are not legal, so use i32 elements.
5653     // The values are implicitly truncated so sext vs. zext doesn't matter.
5654     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5655   }
5656   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5657                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5658 }
5659
5660 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5661   unsigned Opcode = N->getOpcode();
5662   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5663     SDNode *N0 = N->getOperand(0).getNode();
5664     SDNode *N1 = N->getOperand(1).getNode();
5665     return N0->hasOneUse() && N1->hasOneUse() &&
5666       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5667   }
5668   return false;
5669 }
5670
5671 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5672   unsigned Opcode = N->getOpcode();
5673   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5674     SDNode *N0 = N->getOperand(0).getNode();
5675     SDNode *N1 = N->getOperand(1).getNode();
5676     return N0->hasOneUse() && N1->hasOneUse() &&
5677       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5678   }
5679   return false;
5680 }
5681
5682 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5683   // Multiplications are only custom-lowered for 128-bit vectors so that
5684   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5685   EVT VT = Op.getValueType();
5686   assert(VT.is128BitVector() && VT.isInteger() &&
5687          "unexpected type for custom-lowering ISD::MUL");
5688   SDNode *N0 = Op.getOperand(0).getNode();
5689   SDNode *N1 = Op.getOperand(1).getNode();
5690   unsigned NewOpc = 0;
5691   bool isMLA = false;
5692   bool isN0SExt = isSignExtended(N0, DAG);
5693   bool isN1SExt = isSignExtended(N1, DAG);
5694   if (isN0SExt && isN1SExt)
5695     NewOpc = ARMISD::VMULLs;
5696   else {
5697     bool isN0ZExt = isZeroExtended(N0, DAG);
5698     bool isN1ZExt = isZeroExtended(N1, DAG);
5699     if (isN0ZExt && isN1ZExt)
5700       NewOpc = ARMISD::VMULLu;
5701     else if (isN1SExt || isN1ZExt) {
5702       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5703       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5704       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5705         NewOpc = ARMISD::VMULLs;
5706         isMLA = true;
5707       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5708         NewOpc = ARMISD::VMULLu;
5709         isMLA = true;
5710       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5711         std::swap(N0, N1);
5712         NewOpc = ARMISD::VMULLu;
5713         isMLA = true;
5714       }
5715     }
5716
5717     if (!NewOpc) {
5718       if (VT == MVT::v2i64)
5719         // Fall through to expand this.  It is not legal.
5720         return SDValue();
5721       else
5722         // Other vector multiplications are legal.
5723         return Op;
5724     }
5725   }
5726
5727   // Legalize to a VMULL instruction.
5728   SDLoc DL(Op);
5729   SDValue Op0;
5730   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5731   if (!isMLA) {
5732     Op0 = SkipExtensionForVMULL(N0, DAG);
5733     assert(Op0.getValueType().is64BitVector() &&
5734            Op1.getValueType().is64BitVector() &&
5735            "unexpected types for extended operands to VMULL");
5736     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5737   }
5738
5739   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5740   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5741   //   vmull q0, d4, d6
5742   //   vmlal q0, d5, d6
5743   // is faster than
5744   //   vaddl q0, d4, d5
5745   //   vmovl q1, d6
5746   //   vmul  q0, q0, q1
5747   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5748   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5749   EVT Op1VT = Op1.getValueType();
5750   return DAG.getNode(N0->getOpcode(), DL, VT,
5751                      DAG.getNode(NewOpc, DL, VT,
5752                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5753                      DAG.getNode(NewOpc, DL, VT,
5754                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5755 }
5756
5757 static SDValue
5758 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5759   // Convert to float
5760   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5761   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5762   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5763   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5764   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5765   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5766   // Get reciprocal estimate.
5767   // float4 recip = vrecpeq_f32(yf);
5768   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5769                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5770   // Because char has a smaller range than uchar, we can actually get away
5771   // without any newton steps.  This requires that we use a weird bias
5772   // of 0xb000, however (again, this has been exhaustively tested).
5773   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5774   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5775   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5776   Y = DAG.getConstant(0xb000, MVT::i32);
5777   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5778   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5779   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5780   // Convert back to short.
5781   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5782   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5783   return X;
5784 }
5785
5786 static SDValue
5787 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5788   SDValue N2;
5789   // Convert to float.
5790   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5791   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5792   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5793   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5794   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5795   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5796
5797   // Use reciprocal estimate and one refinement step.
5798   // float4 recip = vrecpeq_f32(yf);
5799   // recip *= vrecpsq_f32(yf, recip);
5800   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5801                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5802   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5803                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5804                    N1, N2);
5805   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5806   // Because short has a smaller range than ushort, we can actually get away
5807   // with only a single newton step.  This requires that we use a weird bias
5808   // of 89, however (again, this has been exhaustively tested).
5809   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5810   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5811   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5812   N1 = DAG.getConstant(0x89, MVT::i32);
5813   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5814   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5815   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5816   // Convert back to integer and return.
5817   // return vmovn_s32(vcvt_s32_f32(result));
5818   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5819   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5820   return N0;
5821 }
5822
5823 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5824   EVT VT = Op.getValueType();
5825   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5826          "unexpected type for custom-lowering ISD::SDIV");
5827
5828   SDLoc dl(Op);
5829   SDValue N0 = Op.getOperand(0);
5830   SDValue N1 = Op.getOperand(1);
5831   SDValue N2, N3;
5832
5833   if (VT == MVT::v8i8) {
5834     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5835     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5836
5837     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5838                      DAG.getIntPtrConstant(4));
5839     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5840                      DAG.getIntPtrConstant(4));
5841     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5842                      DAG.getIntPtrConstant(0));
5843     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5844                      DAG.getIntPtrConstant(0));
5845
5846     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5847     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5848
5849     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5850     N0 = LowerCONCAT_VECTORS(N0, DAG);
5851
5852     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5853     return N0;
5854   }
5855   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5856 }
5857
5858 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5859   EVT VT = Op.getValueType();
5860   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5861          "unexpected type for custom-lowering ISD::UDIV");
5862
5863   SDLoc dl(Op);
5864   SDValue N0 = Op.getOperand(0);
5865   SDValue N1 = Op.getOperand(1);
5866   SDValue N2, N3;
5867
5868   if (VT == MVT::v8i8) {
5869     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5870     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5871
5872     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5873                      DAG.getIntPtrConstant(4));
5874     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5875                      DAG.getIntPtrConstant(4));
5876     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5877                      DAG.getIntPtrConstant(0));
5878     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5879                      DAG.getIntPtrConstant(0));
5880
5881     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5882     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5883
5884     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5885     N0 = LowerCONCAT_VECTORS(N0, DAG);
5886
5887     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5888                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5889                      N0);
5890     return N0;
5891   }
5892
5893   // v4i16 sdiv ... Convert to float.
5894   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5895   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5896   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5897   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5898   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5899   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5900
5901   // Use reciprocal estimate and two refinement steps.
5902   // float4 recip = vrecpeq_f32(yf);
5903   // recip *= vrecpsq_f32(yf, recip);
5904   // recip *= vrecpsq_f32(yf, recip);
5905   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5906                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5907   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5908                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5909                    BN1, N2);
5910   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5911   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5912                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5913                    BN1, N2);
5914   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5915   // Simply multiplying by the reciprocal estimate can leave us a few ulps
5916   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5917   // and that it will never cause us to return an answer too large).
5918   // float4 result = as_float4(as_int4(xf*recip) + 2);
5919   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5920   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5921   N1 = DAG.getConstant(2, MVT::i32);
5922   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5923   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5924   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5925   // Convert back to integer and return.
5926   // return vmovn_u32(vcvt_s32_f32(result));
5927   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5928   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5929   return N0;
5930 }
5931
5932 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5933   EVT VT = Op.getNode()->getValueType(0);
5934   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5935
5936   unsigned Opc;
5937   bool ExtraOp = false;
5938   switch (Op.getOpcode()) {
5939   default: llvm_unreachable("Invalid code");
5940   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5941   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5942   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5943   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5944   }
5945
5946   if (!ExtraOp)
5947     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5948                        Op.getOperand(1));
5949   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5950                      Op.getOperand(1), Op.getOperand(2));
5951 }
5952
5953 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5954   // Monotonic load/store is legal for all targets
5955   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5956     return Op;
5957
5958   // Aquire/Release load/store is not legal for targets without a
5959   // dmb or equivalent available.
5960   return SDValue();
5961 }
5962
5963 static void
5964 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5965                     SelectionDAG &DAG) {
5966   SDLoc dl(Node);
5967   assert (Node->getValueType(0) == MVT::i64 &&
5968           "Only know how to expand i64 atomics");
5969   AtomicSDNode *AN = cast<AtomicSDNode>(Node);
5970
5971   SmallVector<SDValue, 6> Ops;
5972   Ops.push_back(Node->getOperand(0)); // Chain
5973   Ops.push_back(Node->getOperand(1)); // Ptr
5974   for(unsigned i=2; i<Node->getNumOperands(); i++) {
5975     // Low part
5976     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5977                               Node->getOperand(i), DAG.getIntPtrConstant(0)));
5978     // High part
5979     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5980                               Node->getOperand(i), DAG.getIntPtrConstant(1)));
5981   }
5982   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5983   SDValue Result =
5984     DAG.getAtomic(Node->getOpcode(), dl, MVT::i64, Tys, Ops.data(), Ops.size(),
5985                   cast<MemSDNode>(Node)->getMemOperand(), AN->getOrdering(),
5986                   AN->getSynchScope());
5987   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5988   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5989   Results.push_back(Result.getValue(2));
5990 }
5991
5992 static void ReplaceREADCYCLECOUNTER(SDNode *N,
5993                                     SmallVectorImpl<SDValue> &Results,
5994                                     SelectionDAG &DAG,
5995                                     const ARMSubtarget *Subtarget) {
5996   SDLoc DL(N);
5997   SDValue Cycles32, OutChain;
5998
5999   if (Subtarget->hasPerfMon()) {
6000     // Under Power Management extensions, the cycle-count is:
6001     //    mrc p15, #0, <Rt>, c9, c13, #0
6002     SDValue Ops[] = { N->getOperand(0), // Chain
6003                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6004                       DAG.getConstant(15, MVT::i32),
6005                       DAG.getConstant(0, MVT::i32),
6006                       DAG.getConstant(9, MVT::i32),
6007                       DAG.getConstant(13, MVT::i32),
6008                       DAG.getConstant(0, MVT::i32)
6009     };
6010
6011     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6012                            DAG.getVTList(MVT::i32, MVT::Other), &Ops[0],
6013                            array_lengthof(Ops));
6014     OutChain = Cycles32.getValue(1);
6015   } else {
6016     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6017     // there are older ARM CPUs that have implementation-specific ways of
6018     // obtaining this information (FIXME!).
6019     Cycles32 = DAG.getConstant(0, MVT::i32);
6020     OutChain = DAG.getEntryNode();
6021   }
6022
6023
6024   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6025                                  Cycles32, DAG.getConstant(0, MVT::i32));
6026   Results.push_back(Cycles64);
6027   Results.push_back(OutChain);
6028 }
6029
6030 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6031   switch (Op.getOpcode()) {
6032   default: llvm_unreachable("Don't know how to custom lower this!");
6033   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6034   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6035   case ISD::GlobalAddress:
6036     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
6037       LowerGlobalAddressELF(Op, DAG);
6038   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6039   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6040   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6041   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6042   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6043   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6044   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6045   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6046   case ISD::SINT_TO_FP:
6047   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6048   case ISD::FP_TO_SINT:
6049   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6050   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6051   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6052   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6053   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6054   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6055   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6056   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6057                                                                Subtarget);
6058   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6059   case ISD::SHL:
6060   case ISD::SRL:
6061   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6062   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6063   case ISD::SRL_PARTS:
6064   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6065   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6066   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6067   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6068   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6069   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6070   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6071   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6072   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6073   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6074   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6075   case ISD::MUL:           return LowerMUL(Op, DAG);
6076   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6077   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6078   case ISD::ADDC:
6079   case ISD::ADDE:
6080   case ISD::SUBC:
6081   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6082   case ISD::ATOMIC_LOAD:
6083   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6084   case ISD::SDIVREM:
6085   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6086   }
6087 }
6088
6089 /// ReplaceNodeResults - Replace the results of node with an illegal result
6090 /// type with new values built out of custom code.
6091 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6092                                            SmallVectorImpl<SDValue>&Results,
6093                                            SelectionDAG &DAG) const {
6094   SDValue Res;
6095   switch (N->getOpcode()) {
6096   default:
6097     llvm_unreachable("Don't know how to custom expand this!");
6098   case ISD::BITCAST:
6099     Res = ExpandBITCAST(N, DAG);
6100     break;
6101   case ISD::SRL:
6102   case ISD::SRA:
6103     Res = Expand64BitShift(N, DAG, Subtarget);
6104     break;
6105   case ISD::READCYCLECOUNTER:
6106     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6107     return;
6108   case ISD::ATOMIC_STORE:
6109   case ISD::ATOMIC_LOAD:
6110   case ISD::ATOMIC_LOAD_ADD:
6111   case ISD::ATOMIC_LOAD_AND:
6112   case ISD::ATOMIC_LOAD_NAND:
6113   case ISD::ATOMIC_LOAD_OR:
6114   case ISD::ATOMIC_LOAD_SUB:
6115   case ISD::ATOMIC_LOAD_XOR:
6116   case ISD::ATOMIC_SWAP:
6117   case ISD::ATOMIC_CMP_SWAP:
6118   case ISD::ATOMIC_LOAD_MIN:
6119   case ISD::ATOMIC_LOAD_UMIN:
6120   case ISD::ATOMIC_LOAD_MAX:
6121   case ISD::ATOMIC_LOAD_UMAX:
6122     ReplaceATOMIC_OP_64(N, Results, DAG);
6123     return;
6124   }
6125   if (Res.getNode())
6126     Results.push_back(Res);
6127 }
6128
6129 //===----------------------------------------------------------------------===//
6130 //                           ARM Scheduler Hooks
6131 //===----------------------------------------------------------------------===//
6132
6133 MachineBasicBlock *
6134 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
6135                                      MachineBasicBlock *BB,
6136                                      unsigned Size) const {
6137   unsigned dest    = MI->getOperand(0).getReg();
6138   unsigned ptr     = MI->getOperand(1).getReg();
6139   unsigned oldval  = MI->getOperand(2).getReg();
6140   unsigned newval  = MI->getOperand(3).getReg();
6141   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6142   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(4).getImm());
6143   DebugLoc dl = MI->getDebugLoc();
6144   bool isThumb2 = Subtarget->isThumb2();
6145
6146   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6147   unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
6148     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6149     (const TargetRegisterClass*)&ARM::GPRRegClass);
6150
6151   if (isThumb2) {
6152     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6153     MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
6154     MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
6155   }
6156
6157   unsigned ldrOpc, strOpc;
6158   getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6159
6160   MachineFunction *MF = BB->getParent();
6161   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6162   MachineFunction::iterator It = BB;
6163   ++It; // insert the new blocks after the current block
6164
6165   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6166   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6167   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6168   MF->insert(It, loop1MBB);
6169   MF->insert(It, loop2MBB);
6170   MF->insert(It, exitMBB);
6171
6172   // Transfer the remainder of BB and its successor edges to exitMBB.
6173   exitMBB->splice(exitMBB->begin(), BB,
6174                   llvm::next(MachineBasicBlock::iterator(MI)),
6175                   BB->end());
6176   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6177
6178   //  thisMBB:
6179   //   ...
6180   //   fallthrough --> loop1MBB
6181   BB->addSuccessor(loop1MBB);
6182
6183   // loop1MBB:
6184   //   ldrex dest, [ptr]
6185   //   cmp dest, oldval
6186   //   bne exitMBB
6187   BB = loop1MBB;
6188   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6189   if (ldrOpc == ARM::t2LDREX)
6190     MIB.addImm(0);
6191   AddDefaultPred(MIB);
6192   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6193                  .addReg(dest).addReg(oldval));
6194   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6195     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6196   BB->addSuccessor(loop2MBB);
6197   BB->addSuccessor(exitMBB);
6198
6199   // loop2MBB:
6200   //   strex scratch, newval, [ptr]
6201   //   cmp scratch, #0
6202   //   bne loop1MBB
6203   BB = loop2MBB;
6204   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
6205   if (strOpc == ARM::t2STREX)
6206     MIB.addImm(0);
6207   AddDefaultPred(MIB);
6208   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6209                  .addReg(scratch).addImm(0));
6210   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6211     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6212   BB->addSuccessor(loop1MBB);
6213   BB->addSuccessor(exitMBB);
6214
6215   //  exitMBB:
6216   //   ...
6217   BB = exitMBB;
6218
6219   MI->eraseFromParent();   // The instruction is gone now.
6220
6221   return BB;
6222 }
6223
6224 MachineBasicBlock *
6225 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6226                                     unsigned Size, unsigned BinOpcode) const {
6227   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6228   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6229
6230   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6231   MachineFunction *MF = BB->getParent();
6232   MachineFunction::iterator It = BB;
6233   ++It;
6234
6235   unsigned dest = MI->getOperand(0).getReg();
6236   unsigned ptr = MI->getOperand(1).getReg();
6237   unsigned incr = MI->getOperand(2).getReg();
6238   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6239   DebugLoc dl = MI->getDebugLoc();
6240   bool isThumb2 = Subtarget->isThumb2();
6241
6242   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6243   if (isThumb2) {
6244     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6245     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6246     MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6247   }
6248
6249   unsigned ldrOpc, strOpc;
6250   getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6251
6252   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6253   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6254   MF->insert(It, loopMBB);
6255   MF->insert(It, exitMBB);
6256
6257   // Transfer the remainder of BB and its successor edges to exitMBB.
6258   exitMBB->splice(exitMBB->begin(), BB,
6259                   llvm::next(MachineBasicBlock::iterator(MI)),
6260                   BB->end());
6261   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6262
6263   const TargetRegisterClass *TRC = isThumb2 ?
6264     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6265     (const TargetRegisterClass*)&ARM::GPRRegClass;
6266   unsigned scratch = MRI.createVirtualRegister(TRC);
6267   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
6268
6269   //  thisMBB:
6270   //   ...
6271   //   fallthrough --> loopMBB
6272   BB->addSuccessor(loopMBB);
6273
6274   //  loopMBB:
6275   //   ldrex dest, ptr
6276   //   <binop> scratch2, dest, incr
6277   //   strex scratch, scratch2, ptr
6278   //   cmp scratch, #0
6279   //   bne- loopMBB
6280   //   fallthrough --> exitMBB
6281   BB = loopMBB;
6282   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6283   if (ldrOpc == ARM::t2LDREX)
6284     MIB.addImm(0);
6285   AddDefaultPred(MIB);
6286   if (BinOpcode) {
6287     // operand order needs to go the other way for NAND
6288     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
6289       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6290                      addReg(incr).addReg(dest)).addReg(0);
6291     else
6292       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6293                      addReg(dest).addReg(incr)).addReg(0);
6294   }
6295
6296   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6297   if (strOpc == ARM::t2STREX)
6298     MIB.addImm(0);
6299   AddDefaultPred(MIB);
6300   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6301                  .addReg(scratch).addImm(0));
6302   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6303     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6304
6305   BB->addSuccessor(loopMBB);
6306   BB->addSuccessor(exitMBB);
6307
6308   //  exitMBB:
6309   //   ...
6310   BB = exitMBB;
6311
6312   MI->eraseFromParent();   // The instruction is gone now.
6313
6314   return BB;
6315 }
6316
6317 MachineBasicBlock *
6318 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
6319                                           MachineBasicBlock *BB,
6320                                           unsigned Size,
6321                                           bool signExtend,
6322                                           ARMCC::CondCodes Cond) const {
6323   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6324
6325   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6326   MachineFunction *MF = BB->getParent();
6327   MachineFunction::iterator It = BB;
6328   ++It;
6329
6330   unsigned dest = MI->getOperand(0).getReg();
6331   unsigned ptr = MI->getOperand(1).getReg();
6332   unsigned incr = MI->getOperand(2).getReg();
6333   unsigned oldval = dest;
6334   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6335   DebugLoc dl = MI->getDebugLoc();
6336   bool isThumb2 = Subtarget->isThumb2();
6337
6338   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6339   if (isThumb2) {
6340     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6341     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6342     MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6343   }
6344
6345   unsigned ldrOpc, strOpc, extendOpc;
6346   getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6347   switch (Size) {
6348   default: llvm_unreachable("unsupported size for AtomicBinaryMinMax!");
6349   case 1:
6350     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
6351     break;
6352   case 2:
6353     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
6354     break;
6355   case 4:
6356     extendOpc = 0;
6357     break;
6358   }
6359
6360   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6361   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6362   MF->insert(It, loopMBB);
6363   MF->insert(It, exitMBB);
6364
6365   // Transfer the remainder of BB and its successor edges to exitMBB.
6366   exitMBB->splice(exitMBB->begin(), BB,
6367                   llvm::next(MachineBasicBlock::iterator(MI)),
6368                   BB->end());
6369   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6370
6371   const TargetRegisterClass *TRC = isThumb2 ?
6372     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6373     (const TargetRegisterClass*)&ARM::GPRRegClass;
6374   unsigned scratch = MRI.createVirtualRegister(TRC);
6375   unsigned scratch2 = MRI.createVirtualRegister(TRC);
6376
6377   //  thisMBB:
6378   //   ...
6379   //   fallthrough --> loopMBB
6380   BB->addSuccessor(loopMBB);
6381
6382   //  loopMBB:
6383   //   ldrex dest, ptr
6384   //   (sign extend dest, if required)
6385   //   cmp dest, incr
6386   //   cmov.cond scratch2, incr, dest
6387   //   strex scratch, scratch2, ptr
6388   //   cmp scratch, #0
6389   //   bne- loopMBB
6390   //   fallthrough --> exitMBB
6391   BB = loopMBB;
6392   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6393   if (ldrOpc == ARM::t2LDREX)
6394     MIB.addImm(0);
6395   AddDefaultPred(MIB);
6396
6397   // Sign extend the value, if necessary.
6398   if (signExtend && extendOpc) {
6399     oldval = MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass
6400                                                 : &ARM::GPRnopcRegClass);
6401     if (!isThumb2)
6402       MRI.constrainRegClass(dest, &ARM::GPRnopcRegClass);
6403     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
6404                      .addReg(dest)
6405                      .addImm(0));
6406   }
6407
6408   // Build compare and cmov instructions.
6409   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6410                  .addReg(oldval).addReg(incr));
6411   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
6412          .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
6413
6414   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6415   if (strOpc == ARM::t2STREX)
6416     MIB.addImm(0);
6417   AddDefaultPred(MIB);
6418   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6419                  .addReg(scratch).addImm(0));
6420   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6421     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6422
6423   BB->addSuccessor(loopMBB);
6424   BB->addSuccessor(exitMBB);
6425
6426   //  exitMBB:
6427   //   ...
6428   BB = exitMBB;
6429
6430   MI->eraseFromParent();   // The instruction is gone now.
6431
6432   return BB;
6433 }
6434
6435 MachineBasicBlock *
6436 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
6437                                       unsigned Op1, unsigned Op2,
6438                                       bool NeedsCarry, bool IsCmpxchg,
6439                                       bool IsMinMax, ARMCC::CondCodes CC) const {
6440   // This also handles ATOMIC_SWAP and ATOMIC_STORE, indicated by Op1==0.
6441   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6442
6443   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6444   MachineFunction *MF = BB->getParent();
6445   MachineFunction::iterator It = BB;
6446   ++It;
6447
6448   bool isStore = (MI->getOpcode() == ARM::ATOMIC_STORE_I64);
6449   unsigned offset = (isStore ? -2 : 0);
6450   unsigned destlo = MI->getOperand(0).getReg();
6451   unsigned desthi = MI->getOperand(1).getReg();
6452   unsigned ptr = MI->getOperand(offset+2).getReg();
6453   unsigned vallo = MI->getOperand(offset+3).getReg();
6454   unsigned valhi = MI->getOperand(offset+4).getReg();
6455   unsigned OrdIdx = offset + (IsCmpxchg ? 7 : 5);
6456   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(OrdIdx).getImm());
6457   DebugLoc dl = MI->getDebugLoc();
6458   bool isThumb2 = Subtarget->isThumb2();
6459
6460   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6461   if (isThumb2) {
6462     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6463     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6464     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6465     MRI.constrainRegClass(vallo, &ARM::rGPRRegClass);
6466     MRI.constrainRegClass(valhi, &ARM::rGPRRegClass);
6467   }
6468
6469   unsigned ldrOpc, strOpc;
6470   getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6471
6472   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6473   MachineBasicBlock *contBB = 0, *cont2BB = 0;
6474   if (IsCmpxchg || IsMinMax)
6475     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
6476   if (IsCmpxchg)
6477     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
6478   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6479
6480   MF->insert(It, loopMBB);
6481   if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6482   if (IsCmpxchg) MF->insert(It, cont2BB);
6483   MF->insert(It, exitMBB);
6484
6485   // Transfer the remainder of BB and its successor edges to exitMBB.
6486   exitMBB->splice(exitMBB->begin(), BB,
6487                   llvm::next(MachineBasicBlock::iterator(MI)),
6488                   BB->end());
6489   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6490
6491   const TargetRegisterClass *TRC = isThumb2 ?
6492     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6493     (const TargetRegisterClass*)&ARM::GPRRegClass;
6494   unsigned storesuccess = MRI.createVirtualRegister(TRC);
6495
6496   //  thisMBB:
6497   //   ...
6498   //   fallthrough --> loopMBB
6499   BB->addSuccessor(loopMBB);
6500
6501   //  loopMBB:
6502   //   ldrexd r2, r3, ptr
6503   //   <binopa> r0, r2, incr
6504   //   <binopb> r1, r3, incr
6505   //   strexd storesuccess, r0, r1, ptr
6506   //   cmp storesuccess, #0
6507   //   bne- loopMBB
6508   //   fallthrough --> exitMBB
6509   BB = loopMBB;
6510
6511   if (!isStore) {
6512     // Load
6513     if (isThumb2) {
6514       AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6515                      .addReg(destlo, RegState::Define)
6516                      .addReg(desthi, RegState::Define)
6517                      .addReg(ptr));
6518     } else {
6519       unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6520       AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6521                      .addReg(GPRPair0, RegState::Define).addReg(ptr));
6522       // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
6523       BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6524         .addReg(GPRPair0, 0, ARM::gsub_0);
6525       BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6526         .addReg(GPRPair0, 0, ARM::gsub_1);
6527     }
6528   }
6529
6530   unsigned StoreLo, StoreHi;
6531   if (IsCmpxchg) {
6532     // Add early exit
6533     for (unsigned i = 0; i < 2; i++) {
6534       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6535                                                          ARM::CMPrr))
6536                      .addReg(i == 0 ? destlo : desthi)
6537                      .addReg(i == 0 ? vallo : valhi));
6538       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6539         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6540       BB->addSuccessor(exitMBB);
6541       BB->addSuccessor(i == 0 ? contBB : cont2BB);
6542       BB = (i == 0 ? contBB : cont2BB);
6543     }
6544
6545     // Copy to physregs for strexd
6546     StoreLo = MI->getOperand(5).getReg();
6547     StoreHi = MI->getOperand(6).getReg();
6548   } else if (Op1) {
6549     // Perform binary operation
6550     unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6551     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6552                    .addReg(destlo).addReg(vallo))
6553         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6554     unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6555     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6556                    .addReg(desthi).addReg(valhi))
6557         .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6558
6559     StoreLo = tmpRegLo;
6560     StoreHi = tmpRegHi;
6561   } else {
6562     // Copy to physregs for strexd
6563     StoreLo = vallo;
6564     StoreHi = valhi;
6565   }
6566   if (IsMinMax) {
6567     // Compare and branch to exit block.
6568     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6569       .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6570     BB->addSuccessor(exitMBB);
6571     BB->addSuccessor(contBB);
6572     BB = contBB;
6573     StoreLo = vallo;
6574     StoreHi = valhi;
6575   }
6576
6577   // Store
6578   if (isThumb2) {
6579     MRI.constrainRegClass(StoreLo, &ARM::rGPRRegClass);
6580     MRI.constrainRegClass(StoreHi, &ARM::rGPRRegClass);
6581     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6582                    .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6583   } else {
6584     // Marshal a pair...
6585     unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6586     unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6587     unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6588     BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6589     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6590       .addReg(UndefPair)
6591       .addReg(StoreLo)
6592       .addImm(ARM::gsub_0);
6593     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6594       .addReg(r1)
6595       .addReg(StoreHi)
6596       .addImm(ARM::gsub_1);
6597
6598     // ...and store it
6599     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6600                    .addReg(StorePair).addReg(ptr));
6601   }
6602   // Cmp+jump
6603   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6604                  .addReg(storesuccess).addImm(0));
6605   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6606     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6607
6608   BB->addSuccessor(loopMBB);
6609   BB->addSuccessor(exitMBB);
6610
6611   //  exitMBB:
6612   //   ...
6613   BB = exitMBB;
6614
6615   MI->eraseFromParent();   // The instruction is gone now.
6616
6617   return BB;
6618 }
6619
6620 MachineBasicBlock *
6621 ARMTargetLowering::EmitAtomicLoad64(MachineInstr *MI, MachineBasicBlock *BB) const {
6622
6623   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6624
6625   unsigned destlo = MI->getOperand(0).getReg();
6626   unsigned desthi = MI->getOperand(1).getReg();
6627   unsigned ptr = MI->getOperand(2).getReg();
6628   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6629   DebugLoc dl = MI->getDebugLoc();
6630   bool isThumb2 = Subtarget->isThumb2();
6631
6632   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6633   if (isThumb2) {
6634     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6635     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6636     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6637   }
6638   unsigned ldrOpc, strOpc;
6639   getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6640
6641   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(ldrOpc));
6642
6643   if (isThumb2) {
6644     MIB.addReg(destlo, RegState::Define)
6645        .addReg(desthi, RegState::Define)
6646        .addReg(ptr);
6647
6648   } else {
6649     unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6650     MIB.addReg(GPRPair0, RegState::Define).addReg(ptr);
6651
6652     // Copy GPRPair0 into dest.  (This copy will normally be coalesced.)
6653     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), destlo)
6654       .addReg(GPRPair0, 0, ARM::gsub_0);
6655     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), desthi)
6656       .addReg(GPRPair0, 0, ARM::gsub_1);
6657   }
6658   AddDefaultPred(MIB);
6659
6660   MI->eraseFromParent();   // The instruction is gone now.
6661
6662   return BB;
6663 }
6664
6665 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6666 /// registers the function context.
6667 void ARMTargetLowering::
6668 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6669                        MachineBasicBlock *DispatchBB, int FI) const {
6670   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6671   DebugLoc dl = MI->getDebugLoc();
6672   MachineFunction *MF = MBB->getParent();
6673   MachineRegisterInfo *MRI = &MF->getRegInfo();
6674   MachineConstantPool *MCP = MF->getConstantPool();
6675   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6676   const Function *F = MF->getFunction();
6677
6678   bool isThumb = Subtarget->isThumb();
6679   bool isThumb2 = Subtarget->isThumb2();
6680
6681   unsigned PCLabelId = AFI->createPICLabelUId();
6682   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6683   ARMConstantPoolValue *CPV =
6684     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6685   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6686
6687   const TargetRegisterClass *TRC = isThumb ?
6688     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6689     (const TargetRegisterClass*)&ARM::GPRRegClass;
6690
6691   // Grab constant pool and fixed stack memory operands.
6692   MachineMemOperand *CPMMO =
6693     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6694                              MachineMemOperand::MOLoad, 4, 4);
6695
6696   MachineMemOperand *FIMMOSt =
6697     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6698                              MachineMemOperand::MOStore, 4, 4);
6699
6700   // Load the address of the dispatch MBB into the jump buffer.
6701   if (isThumb2) {
6702     // Incoming value: jbuf
6703     //   ldr.n  r5, LCPI1_1
6704     //   orr    r5, r5, #1
6705     //   add    r5, pc
6706     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6707     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6708     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6709                    .addConstantPoolIndex(CPI)
6710                    .addMemOperand(CPMMO));
6711     // Set the low bit because of thumb mode.
6712     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6713     AddDefaultCC(
6714       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6715                      .addReg(NewVReg1, RegState::Kill)
6716                      .addImm(0x01)));
6717     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6718     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6719       .addReg(NewVReg2, RegState::Kill)
6720       .addImm(PCLabelId);
6721     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6722                    .addReg(NewVReg3, RegState::Kill)
6723                    .addFrameIndex(FI)
6724                    .addImm(36)  // &jbuf[1] :: pc
6725                    .addMemOperand(FIMMOSt));
6726   } else if (isThumb) {
6727     // Incoming value: jbuf
6728     //   ldr.n  r1, LCPI1_4
6729     //   add    r1, pc
6730     //   mov    r2, #1
6731     //   orrs   r1, r2
6732     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6733     //   str    r1, [r2]
6734     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6735     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6736                    .addConstantPoolIndex(CPI)
6737                    .addMemOperand(CPMMO));
6738     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6739     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6740       .addReg(NewVReg1, RegState::Kill)
6741       .addImm(PCLabelId);
6742     // Set the low bit because of thumb mode.
6743     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6744     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6745                    .addReg(ARM::CPSR, RegState::Define)
6746                    .addImm(1));
6747     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6748     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6749                    .addReg(ARM::CPSR, RegState::Define)
6750                    .addReg(NewVReg2, RegState::Kill)
6751                    .addReg(NewVReg3, RegState::Kill));
6752     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6753     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6754                    .addFrameIndex(FI)
6755                    .addImm(36)); // &jbuf[1] :: pc
6756     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6757                    .addReg(NewVReg4, RegState::Kill)
6758                    .addReg(NewVReg5, RegState::Kill)
6759                    .addImm(0)
6760                    .addMemOperand(FIMMOSt));
6761   } else {
6762     // Incoming value: jbuf
6763     //   ldr  r1, LCPI1_1
6764     //   add  r1, pc, r1
6765     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6766     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6767     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6768                    .addConstantPoolIndex(CPI)
6769                    .addImm(0)
6770                    .addMemOperand(CPMMO));
6771     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6772     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6773                    .addReg(NewVReg1, RegState::Kill)
6774                    .addImm(PCLabelId));
6775     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6776                    .addReg(NewVReg2, RegState::Kill)
6777                    .addFrameIndex(FI)
6778                    .addImm(36)  // &jbuf[1] :: pc
6779                    .addMemOperand(FIMMOSt));
6780   }
6781 }
6782
6783 MachineBasicBlock *ARMTargetLowering::
6784 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6785   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6786   DebugLoc dl = MI->getDebugLoc();
6787   MachineFunction *MF = MBB->getParent();
6788   MachineRegisterInfo *MRI = &MF->getRegInfo();
6789   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6790   MachineFrameInfo *MFI = MF->getFrameInfo();
6791   int FI = MFI->getFunctionContextIndex();
6792
6793   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6794     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6795     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6796
6797   // Get a mapping of the call site numbers to all of the landing pads they're
6798   // associated with.
6799   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6800   unsigned MaxCSNum = 0;
6801   MachineModuleInfo &MMI = MF->getMMI();
6802   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6803        ++BB) {
6804     if (!BB->isLandingPad()) continue;
6805
6806     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6807     // pad.
6808     for (MachineBasicBlock::iterator
6809            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6810       if (!II->isEHLabel()) continue;
6811
6812       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6813       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6814
6815       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6816       for (SmallVectorImpl<unsigned>::iterator
6817              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6818            CSI != CSE; ++CSI) {
6819         CallSiteNumToLPad[*CSI].push_back(BB);
6820         MaxCSNum = std::max(MaxCSNum, *CSI);
6821       }
6822       break;
6823     }
6824   }
6825
6826   // Get an ordered list of the machine basic blocks for the jump table.
6827   std::vector<MachineBasicBlock*> LPadList;
6828   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6829   LPadList.reserve(CallSiteNumToLPad.size());
6830   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6831     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6832     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6833            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6834       LPadList.push_back(*II);
6835       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6836     }
6837   }
6838
6839   assert(!LPadList.empty() &&
6840          "No landing pad destinations for the dispatch jump table!");
6841
6842   // Create the jump table and associated information.
6843   MachineJumpTableInfo *JTI =
6844     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6845   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6846   unsigned UId = AFI->createJumpTableUId();
6847   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6848
6849   // Create the MBBs for the dispatch code.
6850
6851   // Shove the dispatch's address into the return slot in the function context.
6852   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6853   DispatchBB->setIsLandingPad();
6854
6855   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6856   unsigned trap_opcode;
6857   if (Subtarget->isThumb())
6858     trap_opcode = ARM::tTRAP;
6859   else
6860     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6861
6862   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6863   DispatchBB->addSuccessor(TrapBB);
6864
6865   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6866   DispatchBB->addSuccessor(DispContBB);
6867
6868   // Insert and MBBs.
6869   MF->insert(MF->end(), DispatchBB);
6870   MF->insert(MF->end(), DispContBB);
6871   MF->insert(MF->end(), TrapBB);
6872
6873   // Insert code into the entry block that creates and registers the function
6874   // context.
6875   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6876
6877   MachineMemOperand *FIMMOLd =
6878     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6879                              MachineMemOperand::MOLoad |
6880                              MachineMemOperand::MOVolatile, 4, 4);
6881
6882   MachineInstrBuilder MIB;
6883   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6884
6885   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6886   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6887
6888   // Add a register mask with no preserved registers.  This results in all
6889   // registers being marked as clobbered.
6890   MIB.addRegMask(RI.getNoPreservedMask());
6891
6892   unsigned NumLPads = LPadList.size();
6893   if (Subtarget->isThumb2()) {
6894     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6895     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6896                    .addFrameIndex(FI)
6897                    .addImm(4)
6898                    .addMemOperand(FIMMOLd));
6899
6900     if (NumLPads < 256) {
6901       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6902                      .addReg(NewVReg1)
6903                      .addImm(LPadList.size()));
6904     } else {
6905       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6906       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6907                      .addImm(NumLPads & 0xFFFF));
6908
6909       unsigned VReg2 = VReg1;
6910       if ((NumLPads & 0xFFFF0000) != 0) {
6911         VReg2 = MRI->createVirtualRegister(TRC);
6912         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6913                        .addReg(VReg1)
6914                        .addImm(NumLPads >> 16));
6915       }
6916
6917       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6918                      .addReg(NewVReg1)
6919                      .addReg(VReg2));
6920     }
6921
6922     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6923       .addMBB(TrapBB)
6924       .addImm(ARMCC::HI)
6925       .addReg(ARM::CPSR);
6926
6927     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6928     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6929                    .addJumpTableIndex(MJTI)
6930                    .addImm(UId));
6931
6932     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6933     AddDefaultCC(
6934       AddDefaultPred(
6935         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6936         .addReg(NewVReg3, RegState::Kill)
6937         .addReg(NewVReg1)
6938         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6939
6940     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6941       .addReg(NewVReg4, RegState::Kill)
6942       .addReg(NewVReg1)
6943       .addJumpTableIndex(MJTI)
6944       .addImm(UId);
6945   } else if (Subtarget->isThumb()) {
6946     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6947     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6948                    .addFrameIndex(FI)
6949                    .addImm(1)
6950                    .addMemOperand(FIMMOLd));
6951
6952     if (NumLPads < 256) {
6953       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6954                      .addReg(NewVReg1)
6955                      .addImm(NumLPads));
6956     } else {
6957       MachineConstantPool *ConstantPool = MF->getConstantPool();
6958       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6959       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6960
6961       // MachineConstantPool wants an explicit alignment.
6962       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6963       if (Align == 0)
6964         Align = getDataLayout()->getTypeAllocSize(C->getType());
6965       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6966
6967       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6968       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6969                      .addReg(VReg1, RegState::Define)
6970                      .addConstantPoolIndex(Idx));
6971       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6972                      .addReg(NewVReg1)
6973                      .addReg(VReg1));
6974     }
6975
6976     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6977       .addMBB(TrapBB)
6978       .addImm(ARMCC::HI)
6979       .addReg(ARM::CPSR);
6980
6981     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6982     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6983                    .addReg(ARM::CPSR, RegState::Define)
6984                    .addReg(NewVReg1)
6985                    .addImm(2));
6986
6987     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6988     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6989                    .addJumpTableIndex(MJTI)
6990                    .addImm(UId));
6991
6992     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6993     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6994                    .addReg(ARM::CPSR, RegState::Define)
6995                    .addReg(NewVReg2, RegState::Kill)
6996                    .addReg(NewVReg3));
6997
6998     MachineMemOperand *JTMMOLd =
6999       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7000                                MachineMemOperand::MOLoad, 4, 4);
7001
7002     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7003     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7004                    .addReg(NewVReg4, RegState::Kill)
7005                    .addImm(0)
7006                    .addMemOperand(JTMMOLd));
7007
7008     unsigned NewVReg6 = NewVReg5;
7009     if (RelocM == Reloc::PIC_) {
7010       NewVReg6 = MRI->createVirtualRegister(TRC);
7011       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7012                      .addReg(ARM::CPSR, RegState::Define)
7013                      .addReg(NewVReg5, RegState::Kill)
7014                      .addReg(NewVReg3));
7015     }
7016
7017     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7018       .addReg(NewVReg6, RegState::Kill)
7019       .addJumpTableIndex(MJTI)
7020       .addImm(UId);
7021   } else {
7022     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7023     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7024                    .addFrameIndex(FI)
7025                    .addImm(4)
7026                    .addMemOperand(FIMMOLd));
7027
7028     if (NumLPads < 256) {
7029       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7030                      .addReg(NewVReg1)
7031                      .addImm(NumLPads));
7032     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7033       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7034       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7035                      .addImm(NumLPads & 0xFFFF));
7036
7037       unsigned VReg2 = VReg1;
7038       if ((NumLPads & 0xFFFF0000) != 0) {
7039         VReg2 = MRI->createVirtualRegister(TRC);
7040         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7041                        .addReg(VReg1)
7042                        .addImm(NumLPads >> 16));
7043       }
7044
7045       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7046                      .addReg(NewVReg1)
7047                      .addReg(VReg2));
7048     } else {
7049       MachineConstantPool *ConstantPool = MF->getConstantPool();
7050       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7051       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7052
7053       // MachineConstantPool wants an explicit alignment.
7054       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7055       if (Align == 0)
7056         Align = getDataLayout()->getTypeAllocSize(C->getType());
7057       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7058
7059       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7060       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7061                      .addReg(VReg1, RegState::Define)
7062                      .addConstantPoolIndex(Idx)
7063                      .addImm(0));
7064       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7065                      .addReg(NewVReg1)
7066                      .addReg(VReg1, RegState::Kill));
7067     }
7068
7069     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7070       .addMBB(TrapBB)
7071       .addImm(ARMCC::HI)
7072       .addReg(ARM::CPSR);
7073
7074     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7075     AddDefaultCC(
7076       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7077                      .addReg(NewVReg1)
7078                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7079     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7080     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7081                    .addJumpTableIndex(MJTI)
7082                    .addImm(UId));
7083
7084     MachineMemOperand *JTMMOLd =
7085       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7086                                MachineMemOperand::MOLoad, 4, 4);
7087     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7088     AddDefaultPred(
7089       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7090       .addReg(NewVReg3, RegState::Kill)
7091       .addReg(NewVReg4)
7092       .addImm(0)
7093       .addMemOperand(JTMMOLd));
7094
7095     if (RelocM == Reloc::PIC_) {
7096       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7097         .addReg(NewVReg5, RegState::Kill)
7098         .addReg(NewVReg4)
7099         .addJumpTableIndex(MJTI)
7100         .addImm(UId);
7101     } else {
7102       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7103         .addReg(NewVReg5, RegState::Kill)
7104         .addJumpTableIndex(MJTI)
7105         .addImm(UId);
7106     }
7107   }
7108
7109   // Add the jump table entries as successors to the MBB.
7110   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7111   for (std::vector<MachineBasicBlock*>::iterator
7112          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7113     MachineBasicBlock *CurMBB = *I;
7114     if (SeenMBBs.insert(CurMBB))
7115       DispContBB->addSuccessor(CurMBB);
7116   }
7117
7118   // N.B. the order the invoke BBs are processed in doesn't matter here.
7119   const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
7120   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7121   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
7122          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
7123     MachineBasicBlock *BB = *I;
7124
7125     // Remove the landing pad successor from the invoke block and replace it
7126     // with the new dispatch block.
7127     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7128                                                   BB->succ_end());
7129     while (!Successors.empty()) {
7130       MachineBasicBlock *SMBB = Successors.pop_back_val();
7131       if (SMBB->isLandingPad()) {
7132         BB->removeSuccessor(SMBB);
7133         MBBLPads.push_back(SMBB);
7134       }
7135     }
7136
7137     BB->addSuccessor(DispatchBB);
7138
7139     // Find the invoke call and mark all of the callee-saved registers as
7140     // 'implicit defined' so that they're spilled. This prevents code from
7141     // moving instructions to before the EH block, where they will never be
7142     // executed.
7143     for (MachineBasicBlock::reverse_iterator
7144            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7145       if (!II->isCall()) continue;
7146
7147       DenseMap<unsigned, bool> DefRegs;
7148       for (MachineInstr::mop_iterator
7149              OI = II->operands_begin(), OE = II->operands_end();
7150            OI != OE; ++OI) {
7151         if (!OI->isReg()) continue;
7152         DefRegs[OI->getReg()] = true;
7153       }
7154
7155       MachineInstrBuilder MIB(*MF, &*II);
7156
7157       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7158         unsigned Reg = SavedRegs[i];
7159         if (Subtarget->isThumb2() &&
7160             !ARM::tGPRRegClass.contains(Reg) &&
7161             !ARM::hGPRRegClass.contains(Reg))
7162           continue;
7163         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7164           continue;
7165         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7166           continue;
7167         if (!DefRegs[Reg])
7168           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7169       }
7170
7171       break;
7172     }
7173   }
7174
7175   // Mark all former landing pads as non-landing pads. The dispatch is the only
7176   // landing pad now.
7177   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7178          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7179     (*I)->setIsLandingPad(false);
7180
7181   // The instruction is gone now.
7182   MI->eraseFromParent();
7183
7184   return MBB;
7185 }
7186
7187 static
7188 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7189   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7190        E = MBB->succ_end(); I != E; ++I)
7191     if (*I != Succ)
7192       return *I;
7193   llvm_unreachable("Expecting a BB with two successors!");
7194 }
7195
7196 /// Return the load opcode for a given load size. If load size >= 8,
7197 /// neon opcode will be returned.
7198 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7199   if (LdSize >= 8)
7200     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7201                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7202   if (IsThumb1)
7203     return LdSize == 4 ? ARM::tLDRi
7204                        : LdSize == 2 ? ARM::tLDRHi
7205                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7206   if (IsThumb2)
7207     return LdSize == 4 ? ARM::t2LDR_POST
7208                        : LdSize == 2 ? ARM::t2LDRH_POST
7209                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7210   return LdSize == 4 ? ARM::LDR_POST_IMM
7211                      : LdSize == 2 ? ARM::LDRH_POST
7212                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7213 }
7214
7215 /// Return the store opcode for a given store size. If store size >= 8,
7216 /// neon opcode will be returned.
7217 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7218   if (StSize >= 8)
7219     return StSize == 16 ? ARM::VST1q32wb_fixed
7220                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7221   if (IsThumb1)
7222     return StSize == 4 ? ARM::tSTRi
7223                        : StSize == 2 ? ARM::tSTRHi
7224                                      : StSize == 1 ? ARM::tSTRBi : 0;
7225   if (IsThumb2)
7226     return StSize == 4 ? ARM::t2STR_POST
7227                        : StSize == 2 ? ARM::t2STRH_POST
7228                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7229   return StSize == 4 ? ARM::STR_POST_IMM
7230                      : StSize == 2 ? ARM::STRH_POST
7231                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7232 }
7233
7234 /// Emit a post-increment load operation with given size. The instructions
7235 /// will be added to BB at Pos.
7236 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7237                        const TargetInstrInfo *TII, DebugLoc dl,
7238                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7239                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7240   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7241   assert(LdOpc != 0 && "Should have a load opcode");
7242   if (LdSize >= 8) {
7243     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7244                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7245                        .addImm(0));
7246   } else if (IsThumb1) {
7247     // load + update AddrIn
7248     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7249                        .addReg(AddrIn).addImm(0));
7250     MachineInstrBuilder MIB =
7251         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7252     MIB = AddDefaultT1CC(MIB);
7253     MIB.addReg(AddrIn).addImm(LdSize);
7254     AddDefaultPred(MIB);
7255   } else if (IsThumb2) {
7256     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7257                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7258                        .addImm(LdSize));
7259   } else { // arm
7260     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7261                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7262                        .addReg(0).addImm(LdSize));
7263   }
7264 }
7265
7266 /// Emit a post-increment store operation with given size. The instructions
7267 /// will be added to BB at Pos.
7268 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7269                        const TargetInstrInfo *TII, DebugLoc dl,
7270                        unsigned StSize, unsigned Data, unsigned AddrIn,
7271                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7272   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7273   assert(StOpc != 0 && "Should have a store opcode");
7274   if (StSize >= 8) {
7275     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7276                        .addReg(AddrIn).addImm(0).addReg(Data));
7277   } else if (IsThumb1) {
7278     // store + update AddrIn
7279     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7280                        .addReg(AddrIn).addImm(0));
7281     MachineInstrBuilder MIB =
7282         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7283     MIB = AddDefaultT1CC(MIB);
7284     MIB.addReg(AddrIn).addImm(StSize);
7285     AddDefaultPred(MIB);
7286   } else if (IsThumb2) {
7287     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7288                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7289   } else { // arm
7290     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7291                        .addReg(Data).addReg(AddrIn).addReg(0)
7292                        .addImm(StSize));
7293   }
7294 }
7295
7296 MachineBasicBlock *
7297 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7298                                    MachineBasicBlock *BB) const {
7299   // This pseudo instruction has 3 operands: dst, src, size
7300   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7301   // Otherwise, we will generate unrolled scalar copies.
7302   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7303   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7304   MachineFunction::iterator It = BB;
7305   ++It;
7306
7307   unsigned dest = MI->getOperand(0).getReg();
7308   unsigned src = MI->getOperand(1).getReg();
7309   unsigned SizeVal = MI->getOperand(2).getImm();
7310   unsigned Align = MI->getOperand(3).getImm();
7311   DebugLoc dl = MI->getDebugLoc();
7312
7313   MachineFunction *MF = BB->getParent();
7314   MachineRegisterInfo &MRI = MF->getRegInfo();
7315   unsigned UnitSize = 0;
7316   const TargetRegisterClass *TRC = 0;
7317   const TargetRegisterClass *VecTRC = 0;
7318
7319   bool IsThumb1 = Subtarget->isThumb1Only();
7320   bool IsThumb2 = Subtarget->isThumb2();
7321
7322   if (Align & 1) {
7323     UnitSize = 1;
7324   } else if (Align & 2) {
7325     UnitSize = 2;
7326   } else {
7327     // Check whether we can use NEON instructions.
7328     if (!MF->getFunction()->getAttributes().
7329           hasAttribute(AttributeSet::FunctionIndex,
7330                        Attribute::NoImplicitFloat) &&
7331         Subtarget->hasNEON()) {
7332       if ((Align % 16 == 0) && SizeVal >= 16)
7333         UnitSize = 16;
7334       else if ((Align % 8 == 0) && SizeVal >= 8)
7335         UnitSize = 8;
7336     }
7337     // Can't use NEON instructions.
7338     if (UnitSize == 0)
7339       UnitSize = 4;
7340   }
7341
7342   // Select the correct opcode and register class for unit size load/store
7343   bool IsNeon = UnitSize >= 8;
7344   TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
7345                                : (const TargetRegisterClass *)&ARM::GPRRegClass;
7346   if (IsNeon)
7347     VecTRC = UnitSize == 16
7348                  ? (const TargetRegisterClass *)&ARM::DPairRegClass
7349                  : UnitSize == 8
7350                        ? (const TargetRegisterClass *)&ARM::DPRRegClass
7351                        : 0;
7352
7353   unsigned BytesLeft = SizeVal % UnitSize;
7354   unsigned LoopSize = SizeVal - BytesLeft;
7355
7356   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7357     // Use LDR and STR to copy.
7358     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7359     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7360     unsigned srcIn = src;
7361     unsigned destIn = dest;
7362     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7363       unsigned srcOut = MRI.createVirtualRegister(TRC);
7364       unsigned destOut = MRI.createVirtualRegister(TRC);
7365       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7366       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7367                  IsThumb1, IsThumb2);
7368       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7369                  IsThumb1, IsThumb2);
7370       srcIn = srcOut;
7371       destIn = destOut;
7372     }
7373
7374     // Handle the leftover bytes with LDRB and STRB.
7375     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7376     // [destOut] = STRB_POST(scratch, destIn, 1)
7377     for (unsigned i = 0; i < BytesLeft; i++) {
7378       unsigned srcOut = MRI.createVirtualRegister(TRC);
7379       unsigned destOut = MRI.createVirtualRegister(TRC);
7380       unsigned scratch = MRI.createVirtualRegister(TRC);
7381       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7382                  IsThumb1, IsThumb2);
7383       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7384                  IsThumb1, IsThumb2);
7385       srcIn = srcOut;
7386       destIn = destOut;
7387     }
7388     MI->eraseFromParent();   // The instruction is gone now.
7389     return BB;
7390   }
7391
7392   // Expand the pseudo op to a loop.
7393   // thisMBB:
7394   //   ...
7395   //   movw varEnd, # --> with thumb2
7396   //   movt varEnd, #
7397   //   ldrcp varEnd, idx --> without thumb2
7398   //   fallthrough --> loopMBB
7399   // loopMBB:
7400   //   PHI varPhi, varEnd, varLoop
7401   //   PHI srcPhi, src, srcLoop
7402   //   PHI destPhi, dst, destLoop
7403   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7404   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7405   //   subs varLoop, varPhi, #UnitSize
7406   //   bne loopMBB
7407   //   fallthrough --> exitMBB
7408   // exitMBB:
7409   //   epilogue to handle left-over bytes
7410   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7411   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7412   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7413   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7414   MF->insert(It, loopMBB);
7415   MF->insert(It, exitMBB);
7416
7417   // Transfer the remainder of BB and its successor edges to exitMBB.
7418   exitMBB->splice(exitMBB->begin(), BB,
7419                   llvm::next(MachineBasicBlock::iterator(MI)),
7420                   BB->end());
7421   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7422
7423   // Load an immediate to varEnd.
7424   unsigned varEnd = MRI.createVirtualRegister(TRC);
7425   if (IsThumb2) {
7426     unsigned Vtmp = varEnd;
7427     if ((LoopSize & 0xFFFF0000) != 0)
7428       Vtmp = MRI.createVirtualRegister(TRC);
7429     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7430                        .addImm(LoopSize & 0xFFFF));
7431
7432     if ((LoopSize & 0xFFFF0000) != 0)
7433       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7434                          .addReg(Vtmp).addImm(LoopSize >> 16));
7435   } else {
7436     MachineConstantPool *ConstantPool = MF->getConstantPool();
7437     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7438     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7439
7440     // MachineConstantPool wants an explicit alignment.
7441     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7442     if (Align == 0)
7443       Align = getDataLayout()->getTypeAllocSize(C->getType());
7444     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7445
7446     if (IsThumb1)
7447       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7448           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7449     else
7450       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7451           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7452   }
7453   BB->addSuccessor(loopMBB);
7454
7455   // Generate the loop body:
7456   //   varPhi = PHI(varLoop, varEnd)
7457   //   srcPhi = PHI(srcLoop, src)
7458   //   destPhi = PHI(destLoop, dst)
7459   MachineBasicBlock *entryBB = BB;
7460   BB = loopMBB;
7461   unsigned varLoop = MRI.createVirtualRegister(TRC);
7462   unsigned varPhi = MRI.createVirtualRegister(TRC);
7463   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7464   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7465   unsigned destLoop = MRI.createVirtualRegister(TRC);
7466   unsigned destPhi = MRI.createVirtualRegister(TRC);
7467
7468   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7469     .addReg(varLoop).addMBB(loopMBB)
7470     .addReg(varEnd).addMBB(entryBB);
7471   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7472     .addReg(srcLoop).addMBB(loopMBB)
7473     .addReg(src).addMBB(entryBB);
7474   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7475     .addReg(destLoop).addMBB(loopMBB)
7476     .addReg(dest).addMBB(entryBB);
7477
7478   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7479   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7480   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7481   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7482              IsThumb1, IsThumb2);
7483   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7484              IsThumb1, IsThumb2);
7485
7486   // Decrement loop variable by UnitSize.
7487   if (IsThumb1) {
7488     MachineInstrBuilder MIB =
7489         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7490     MIB = AddDefaultT1CC(MIB);
7491     MIB.addReg(varPhi).addImm(UnitSize);
7492     AddDefaultPred(MIB);
7493   } else {
7494     MachineInstrBuilder MIB =
7495         BuildMI(*BB, BB->end(), dl,
7496                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7497     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7498     MIB->getOperand(5).setReg(ARM::CPSR);
7499     MIB->getOperand(5).setIsDef(true);
7500   }
7501   BuildMI(*BB, BB->end(), dl,
7502           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7503       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7504
7505   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7506   BB->addSuccessor(loopMBB);
7507   BB->addSuccessor(exitMBB);
7508
7509   // Add epilogue to handle BytesLeft.
7510   BB = exitMBB;
7511   MachineInstr *StartOfExit = exitMBB->begin();
7512
7513   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7514   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7515   unsigned srcIn = srcLoop;
7516   unsigned destIn = destLoop;
7517   for (unsigned i = 0; i < BytesLeft; i++) {
7518     unsigned srcOut = MRI.createVirtualRegister(TRC);
7519     unsigned destOut = MRI.createVirtualRegister(TRC);
7520     unsigned scratch = MRI.createVirtualRegister(TRC);
7521     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7522                IsThumb1, IsThumb2);
7523     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7524                IsThumb1, IsThumb2);
7525     srcIn = srcOut;
7526     destIn = destOut;
7527   }
7528
7529   MI->eraseFromParent();   // The instruction is gone now.
7530   return BB;
7531 }
7532
7533 MachineBasicBlock *
7534 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7535                                                MachineBasicBlock *BB) const {
7536   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7537   DebugLoc dl = MI->getDebugLoc();
7538   bool isThumb2 = Subtarget->isThumb2();
7539   switch (MI->getOpcode()) {
7540   default: {
7541     MI->dump();
7542     llvm_unreachable("Unexpected instr type to insert");
7543   }
7544   // The Thumb2 pre-indexed stores have the same MI operands, they just
7545   // define them differently in the .td files from the isel patterns, so
7546   // they need pseudos.
7547   case ARM::t2STR_preidx:
7548     MI->setDesc(TII->get(ARM::t2STR_PRE));
7549     return BB;
7550   case ARM::t2STRB_preidx:
7551     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7552     return BB;
7553   case ARM::t2STRH_preidx:
7554     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7555     return BB;
7556
7557   case ARM::STRi_preidx:
7558   case ARM::STRBi_preidx: {
7559     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7560       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7561     // Decode the offset.
7562     unsigned Offset = MI->getOperand(4).getImm();
7563     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7564     Offset = ARM_AM::getAM2Offset(Offset);
7565     if (isSub)
7566       Offset = -Offset;
7567
7568     MachineMemOperand *MMO = *MI->memoperands_begin();
7569     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7570       .addOperand(MI->getOperand(0))  // Rn_wb
7571       .addOperand(MI->getOperand(1))  // Rt
7572       .addOperand(MI->getOperand(2))  // Rn
7573       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7574       .addOperand(MI->getOperand(5))  // pred
7575       .addOperand(MI->getOperand(6))
7576       .addMemOperand(MMO);
7577     MI->eraseFromParent();
7578     return BB;
7579   }
7580   case ARM::STRr_preidx:
7581   case ARM::STRBr_preidx:
7582   case ARM::STRH_preidx: {
7583     unsigned NewOpc;
7584     switch (MI->getOpcode()) {
7585     default: llvm_unreachable("unexpected opcode!");
7586     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7587     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7588     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7589     }
7590     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7591     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7592       MIB.addOperand(MI->getOperand(i));
7593     MI->eraseFromParent();
7594     return BB;
7595   }
7596   case ARM::ATOMIC_LOAD_ADD_I8:
7597      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7598   case ARM::ATOMIC_LOAD_ADD_I16:
7599      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7600   case ARM::ATOMIC_LOAD_ADD_I32:
7601      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7602
7603   case ARM::ATOMIC_LOAD_AND_I8:
7604      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7605   case ARM::ATOMIC_LOAD_AND_I16:
7606      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7607   case ARM::ATOMIC_LOAD_AND_I32:
7608      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7609
7610   case ARM::ATOMIC_LOAD_OR_I8:
7611      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7612   case ARM::ATOMIC_LOAD_OR_I16:
7613      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7614   case ARM::ATOMIC_LOAD_OR_I32:
7615      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7616
7617   case ARM::ATOMIC_LOAD_XOR_I8:
7618      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7619   case ARM::ATOMIC_LOAD_XOR_I16:
7620      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7621   case ARM::ATOMIC_LOAD_XOR_I32:
7622      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7623
7624   case ARM::ATOMIC_LOAD_NAND_I8:
7625      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7626   case ARM::ATOMIC_LOAD_NAND_I16:
7627      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7628   case ARM::ATOMIC_LOAD_NAND_I32:
7629      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7630
7631   case ARM::ATOMIC_LOAD_SUB_I8:
7632      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7633   case ARM::ATOMIC_LOAD_SUB_I16:
7634      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7635   case ARM::ATOMIC_LOAD_SUB_I32:
7636      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7637
7638   case ARM::ATOMIC_LOAD_MIN_I8:
7639      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7640   case ARM::ATOMIC_LOAD_MIN_I16:
7641      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7642   case ARM::ATOMIC_LOAD_MIN_I32:
7643      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7644
7645   case ARM::ATOMIC_LOAD_MAX_I8:
7646      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7647   case ARM::ATOMIC_LOAD_MAX_I16:
7648      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7649   case ARM::ATOMIC_LOAD_MAX_I32:
7650      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7651
7652   case ARM::ATOMIC_LOAD_UMIN_I8:
7653      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7654   case ARM::ATOMIC_LOAD_UMIN_I16:
7655      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7656   case ARM::ATOMIC_LOAD_UMIN_I32:
7657      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7658
7659   case ARM::ATOMIC_LOAD_UMAX_I8:
7660      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7661   case ARM::ATOMIC_LOAD_UMAX_I16:
7662      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7663   case ARM::ATOMIC_LOAD_UMAX_I32:
7664      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7665
7666   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
7667   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7668   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7669
7670   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
7671   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7672   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7673
7674   case ARM::ATOMIC_LOAD_I64:
7675     return EmitAtomicLoad64(MI, BB);
7676
7677   case ARM::ATOMIC_LOAD_ADD_I64:
7678     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7679                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7680                               /*NeedsCarry*/ true);
7681   case ARM::ATOMIC_LOAD_SUB_I64:
7682     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7683                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7684                               /*NeedsCarry*/ true);
7685   case ARM::ATOMIC_LOAD_OR_I64:
7686     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7687                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7688   case ARM::ATOMIC_LOAD_XOR_I64:
7689     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7690                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7691   case ARM::ATOMIC_LOAD_AND_I64:
7692     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7693                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7694   case ARM::ATOMIC_STORE_I64:
7695   case ARM::ATOMIC_SWAP_I64:
7696     return EmitAtomicBinary64(MI, BB, 0, 0, false);
7697   case ARM::ATOMIC_CMP_SWAP_I64:
7698     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7699                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7700                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7701   case ARM::ATOMIC_LOAD_MIN_I64:
7702     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7703                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7704                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7705                               /*IsMinMax*/ true, ARMCC::LT);
7706   case ARM::ATOMIC_LOAD_MAX_I64:
7707     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7708                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7709                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7710                               /*IsMinMax*/ true, ARMCC::GE);
7711   case ARM::ATOMIC_LOAD_UMIN_I64:
7712     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7713                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7714                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7715                               /*IsMinMax*/ true, ARMCC::LO);
7716   case ARM::ATOMIC_LOAD_UMAX_I64:
7717     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7718                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7719                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7720                               /*IsMinMax*/ true, ARMCC::HS);
7721
7722   case ARM::tMOVCCr_pseudo: {
7723     // To "insert" a SELECT_CC instruction, we actually have to insert the
7724     // diamond control-flow pattern.  The incoming instruction knows the
7725     // destination vreg to set, the condition code register to branch on, the
7726     // true/false values to select between, and a branch opcode to use.
7727     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7728     MachineFunction::iterator It = BB;
7729     ++It;
7730
7731     //  thisMBB:
7732     //  ...
7733     //   TrueVal = ...
7734     //   cmpTY ccX, r1, r2
7735     //   bCC copy1MBB
7736     //   fallthrough --> copy0MBB
7737     MachineBasicBlock *thisMBB  = BB;
7738     MachineFunction *F = BB->getParent();
7739     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7740     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7741     F->insert(It, copy0MBB);
7742     F->insert(It, sinkMBB);
7743
7744     // Transfer the remainder of BB and its successor edges to sinkMBB.
7745     sinkMBB->splice(sinkMBB->begin(), BB,
7746                     llvm::next(MachineBasicBlock::iterator(MI)),
7747                     BB->end());
7748     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7749
7750     BB->addSuccessor(copy0MBB);
7751     BB->addSuccessor(sinkMBB);
7752
7753     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7754       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7755
7756     //  copy0MBB:
7757     //   %FalseValue = ...
7758     //   # fallthrough to sinkMBB
7759     BB = copy0MBB;
7760
7761     // Update machine-CFG edges
7762     BB->addSuccessor(sinkMBB);
7763
7764     //  sinkMBB:
7765     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7766     //  ...
7767     BB = sinkMBB;
7768     BuildMI(*BB, BB->begin(), dl,
7769             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7770       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7771       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7772
7773     MI->eraseFromParent();   // The pseudo instruction is gone now.
7774     return BB;
7775   }
7776
7777   case ARM::BCCi64:
7778   case ARM::BCCZi64: {
7779     // If there is an unconditional branch to the other successor, remove it.
7780     BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
7781
7782     // Compare both parts that make up the double comparison separately for
7783     // equality.
7784     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7785
7786     unsigned LHS1 = MI->getOperand(1).getReg();
7787     unsigned LHS2 = MI->getOperand(2).getReg();
7788     if (RHSisZero) {
7789       AddDefaultPred(BuildMI(BB, dl,
7790                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7791                      .addReg(LHS1).addImm(0));
7792       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7793         .addReg(LHS2).addImm(0)
7794         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7795     } else {
7796       unsigned RHS1 = MI->getOperand(3).getReg();
7797       unsigned RHS2 = MI->getOperand(4).getReg();
7798       AddDefaultPred(BuildMI(BB, dl,
7799                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7800                      .addReg(LHS1).addReg(RHS1));
7801       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7802         .addReg(LHS2).addReg(RHS2)
7803         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7804     }
7805
7806     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7807     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7808     if (MI->getOperand(0).getImm() == ARMCC::NE)
7809       std::swap(destMBB, exitMBB);
7810
7811     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7812       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7813     if (isThumb2)
7814       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7815     else
7816       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7817
7818     MI->eraseFromParent();   // The pseudo instruction is gone now.
7819     return BB;
7820   }
7821
7822   case ARM::Int_eh_sjlj_setjmp:
7823   case ARM::Int_eh_sjlj_setjmp_nofp:
7824   case ARM::tInt_eh_sjlj_setjmp:
7825   case ARM::t2Int_eh_sjlj_setjmp:
7826   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7827     EmitSjLjDispatchBlock(MI, BB);
7828     return BB;
7829
7830   case ARM::ABS:
7831   case ARM::t2ABS: {
7832     // To insert an ABS instruction, we have to insert the
7833     // diamond control-flow pattern.  The incoming instruction knows the
7834     // source vreg to test against 0, the destination vreg to set,
7835     // the condition code register to branch on, the
7836     // true/false values to select between, and a branch opcode to use.
7837     // It transforms
7838     //     V1 = ABS V0
7839     // into
7840     //     V2 = MOVS V0
7841     //     BCC                      (branch to SinkBB if V0 >= 0)
7842     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7843     //     SinkBB: V1 = PHI(V2, V3)
7844     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7845     MachineFunction::iterator BBI = BB;
7846     ++BBI;
7847     MachineFunction *Fn = BB->getParent();
7848     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7849     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7850     Fn->insert(BBI, RSBBB);
7851     Fn->insert(BBI, SinkBB);
7852
7853     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7854     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7855     bool isThumb2 = Subtarget->isThumb2();
7856     MachineRegisterInfo &MRI = Fn->getRegInfo();
7857     // In Thumb mode S must not be specified if source register is the SP or
7858     // PC and if destination register is the SP, so restrict register class
7859     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7860       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7861       (const TargetRegisterClass*)&ARM::GPRRegClass);
7862
7863     // Transfer the remainder of BB and its successor edges to sinkMBB.
7864     SinkBB->splice(SinkBB->begin(), BB,
7865       llvm::next(MachineBasicBlock::iterator(MI)),
7866       BB->end());
7867     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7868
7869     BB->addSuccessor(RSBBB);
7870     BB->addSuccessor(SinkBB);
7871
7872     // fall through to SinkMBB
7873     RSBBB->addSuccessor(SinkBB);
7874
7875     // insert a cmp at the end of BB
7876     AddDefaultPred(BuildMI(BB, dl,
7877                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7878                    .addReg(ABSSrcReg).addImm(0));
7879
7880     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7881     BuildMI(BB, dl,
7882       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7883       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7884
7885     // insert rsbri in RSBBB
7886     // Note: BCC and rsbri will be converted into predicated rsbmi
7887     // by if-conversion pass
7888     BuildMI(*RSBBB, RSBBB->begin(), dl,
7889       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7890       .addReg(ABSSrcReg, RegState::Kill)
7891       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7892
7893     // insert PHI in SinkBB,
7894     // reuse ABSDstReg to not change uses of ABS instruction
7895     BuildMI(*SinkBB, SinkBB->begin(), dl,
7896       TII->get(ARM::PHI), ABSDstReg)
7897       .addReg(NewRsbDstReg).addMBB(RSBBB)
7898       .addReg(ABSSrcReg).addMBB(BB);
7899
7900     // remove ABS instruction
7901     MI->eraseFromParent();
7902
7903     // return last added BB
7904     return SinkBB;
7905   }
7906   case ARM::COPY_STRUCT_BYVAL_I32:
7907     ++NumLoopByVals;
7908     return EmitStructByval(MI, BB);
7909   }
7910 }
7911
7912 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7913                                                       SDNode *Node) const {
7914   if (!MI->hasPostISelHook()) {
7915     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7916            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7917     return;
7918   }
7919
7920   const MCInstrDesc *MCID = &MI->getDesc();
7921   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7922   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7923   // operand is still set to noreg. If needed, set the optional operand's
7924   // register to CPSR, and remove the redundant implicit def.
7925   //
7926   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7927
7928   // Rename pseudo opcodes.
7929   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7930   if (NewOpc) {
7931     const ARMBaseInstrInfo *TII =
7932       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7933     MCID = &TII->get(NewOpc);
7934
7935     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7936            "converted opcode should be the same except for cc_out");
7937
7938     MI->setDesc(*MCID);
7939
7940     // Add the optional cc_out operand
7941     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7942   }
7943   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7944
7945   // Any ARM instruction that sets the 's' bit should specify an optional
7946   // "cc_out" operand in the last operand position.
7947   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7948     assert(!NewOpc && "Optional cc_out operand required");
7949     return;
7950   }
7951   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7952   // since we already have an optional CPSR def.
7953   bool definesCPSR = false;
7954   bool deadCPSR = false;
7955   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7956        i != e; ++i) {
7957     const MachineOperand &MO = MI->getOperand(i);
7958     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7959       definesCPSR = true;
7960       if (MO.isDead())
7961         deadCPSR = true;
7962       MI->RemoveOperand(i);
7963       break;
7964     }
7965   }
7966   if (!definesCPSR) {
7967     assert(!NewOpc && "Optional cc_out operand required");
7968     return;
7969   }
7970   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7971   if (deadCPSR) {
7972     assert(!MI->getOperand(ccOutIdx).getReg() &&
7973            "expect uninitialized optional cc_out operand");
7974     return;
7975   }
7976
7977   // If this instruction was defined with an optional CPSR def and its dag node
7978   // had a live implicit CPSR def, then activate the optional CPSR def.
7979   MachineOperand &MO = MI->getOperand(ccOutIdx);
7980   MO.setReg(ARM::CPSR);
7981   MO.setIsDef(true);
7982 }
7983
7984 //===----------------------------------------------------------------------===//
7985 //                           ARM Optimization Hooks
7986 //===----------------------------------------------------------------------===//
7987
7988 // Helper function that checks if N is a null or all ones constant.
7989 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7990   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7991   if (!C)
7992     return false;
7993   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7994 }
7995
7996 // Return true if N is conditionally 0 or all ones.
7997 // Detects these expressions where cc is an i1 value:
7998 //
7999 //   (select cc 0, y)   [AllOnes=0]
8000 //   (select cc y, 0)   [AllOnes=0]
8001 //   (zext cc)          [AllOnes=0]
8002 //   (sext cc)          [AllOnes=0/1]
8003 //   (select cc -1, y)  [AllOnes=1]
8004 //   (select cc y, -1)  [AllOnes=1]
8005 //
8006 // Invert is set when N is the null/all ones constant when CC is false.
8007 // OtherOp is set to the alternative value of N.
8008 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8009                                        SDValue &CC, bool &Invert,
8010                                        SDValue &OtherOp,
8011                                        SelectionDAG &DAG) {
8012   switch (N->getOpcode()) {
8013   default: return false;
8014   case ISD::SELECT: {
8015     CC = N->getOperand(0);
8016     SDValue N1 = N->getOperand(1);
8017     SDValue N2 = N->getOperand(2);
8018     if (isZeroOrAllOnes(N1, AllOnes)) {
8019       Invert = false;
8020       OtherOp = N2;
8021       return true;
8022     }
8023     if (isZeroOrAllOnes(N2, AllOnes)) {
8024       Invert = true;
8025       OtherOp = N1;
8026       return true;
8027     }
8028     return false;
8029   }
8030   case ISD::ZERO_EXTEND:
8031     // (zext cc) can never be the all ones value.
8032     if (AllOnes)
8033       return false;
8034     // Fall through.
8035   case ISD::SIGN_EXTEND: {
8036     EVT VT = N->getValueType(0);
8037     CC = N->getOperand(0);
8038     if (CC.getValueType() != MVT::i1)
8039       return false;
8040     Invert = !AllOnes;
8041     if (AllOnes)
8042       // When looking for an AllOnes constant, N is an sext, and the 'other'
8043       // value is 0.
8044       OtherOp = DAG.getConstant(0, VT);
8045     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8046       // When looking for a 0 constant, N can be zext or sext.
8047       OtherOp = DAG.getConstant(1, VT);
8048     else
8049       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
8050     return true;
8051   }
8052   }
8053 }
8054
8055 // Combine a constant select operand into its use:
8056 //
8057 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
8058 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
8059 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
8060 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
8061 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
8062 //
8063 // The transform is rejected if the select doesn't have a constant operand that
8064 // is null, or all ones when AllOnes is set.
8065 //
8066 // Also recognize sext/zext from i1:
8067 //
8068 //   (add (zext cc), x) -> (select cc (add x, 1), x)
8069 //   (add (sext cc), x) -> (select cc (add x, -1), x)
8070 //
8071 // These transformations eventually create predicated instructions.
8072 //
8073 // @param N       The node to transform.
8074 // @param Slct    The N operand that is a select.
8075 // @param OtherOp The other N operand (x above).
8076 // @param DCI     Context.
8077 // @param AllOnes Require the select constant to be all ones instead of null.
8078 // @returns The new node, or SDValue() on failure.
8079 static
8080 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8081                             TargetLowering::DAGCombinerInfo &DCI,
8082                             bool AllOnes = false) {
8083   SelectionDAG &DAG = DCI.DAG;
8084   EVT VT = N->getValueType(0);
8085   SDValue NonConstantVal;
8086   SDValue CCOp;
8087   bool SwapSelectOps;
8088   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8089                                   NonConstantVal, DAG))
8090     return SDValue();
8091
8092   // Slct is now know to be the desired identity constant when CC is true.
8093   SDValue TrueVal = OtherOp;
8094   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8095                                  OtherOp, NonConstantVal);
8096   // Unless SwapSelectOps says CC should be false.
8097   if (SwapSelectOps)
8098     std::swap(TrueVal, FalseVal);
8099
8100   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8101                      CCOp, TrueVal, FalseVal);
8102 }
8103
8104 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8105 static
8106 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8107                                        TargetLowering::DAGCombinerInfo &DCI) {
8108   SDValue N0 = N->getOperand(0);
8109   SDValue N1 = N->getOperand(1);
8110   if (N0.getNode()->hasOneUse()) {
8111     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8112     if (Result.getNode())
8113       return Result;
8114   }
8115   if (N1.getNode()->hasOneUse()) {
8116     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8117     if (Result.getNode())
8118       return Result;
8119   }
8120   return SDValue();
8121 }
8122
8123 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8124 // (only after legalization).
8125 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8126                                  TargetLowering::DAGCombinerInfo &DCI,
8127                                  const ARMSubtarget *Subtarget) {
8128
8129   // Only perform optimization if after legalize, and if NEON is available. We
8130   // also expected both operands to be BUILD_VECTORs.
8131   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8132       || N0.getOpcode() != ISD::BUILD_VECTOR
8133       || N1.getOpcode() != ISD::BUILD_VECTOR)
8134     return SDValue();
8135
8136   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8137   EVT VT = N->getValueType(0);
8138   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8139     return SDValue();
8140
8141   // Check that the vector operands are of the right form.
8142   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8143   // operands, where N is the size of the formed vector.
8144   // Each EXTRACT_VECTOR should have the same input vector and odd or even
8145   // index such that we have a pair wise add pattern.
8146
8147   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8148   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8149     return SDValue();
8150   SDValue Vec = N0->getOperand(0)->getOperand(0);
8151   SDNode *V = Vec.getNode();
8152   unsigned nextIndex = 0;
8153
8154   // For each operands to the ADD which are BUILD_VECTORs,
8155   // check to see if each of their operands are an EXTRACT_VECTOR with
8156   // the same vector and appropriate index.
8157   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8158     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8159         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8160
8161       SDValue ExtVec0 = N0->getOperand(i);
8162       SDValue ExtVec1 = N1->getOperand(i);
8163
8164       // First operand is the vector, verify its the same.
8165       if (V != ExtVec0->getOperand(0).getNode() ||
8166           V != ExtVec1->getOperand(0).getNode())
8167         return SDValue();
8168
8169       // Second is the constant, verify its correct.
8170       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8171       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8172
8173       // For the constant, we want to see all the even or all the odd.
8174       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8175           || C1->getZExtValue() != nextIndex+1)
8176         return SDValue();
8177
8178       // Increment index.
8179       nextIndex+=2;
8180     } else
8181       return SDValue();
8182   }
8183
8184   // Create VPADDL node.
8185   SelectionDAG &DAG = DCI.DAG;
8186   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8187
8188   // Build operand list.
8189   SmallVector<SDValue, 8> Ops;
8190   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
8191                                 TLI.getPointerTy()));
8192
8193   // Input is the vector.
8194   Ops.push_back(Vec);
8195
8196   // Get widened type and narrowed type.
8197   MVT widenType;
8198   unsigned numElem = VT.getVectorNumElements();
8199   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8200     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8201     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8202     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8203     default:
8204       llvm_unreachable("Invalid vector element type for padd optimization.");
8205   }
8206
8207   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
8208                             widenType, &Ops[0], Ops.size());
8209   return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, tmp);
8210 }
8211
8212 static SDValue findMUL_LOHI(SDValue V) {
8213   if (V->getOpcode() == ISD::UMUL_LOHI ||
8214       V->getOpcode() == ISD::SMUL_LOHI)
8215     return V;
8216   return SDValue();
8217 }
8218
8219 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8220                                      TargetLowering::DAGCombinerInfo &DCI,
8221                                      const ARMSubtarget *Subtarget) {
8222
8223   if (Subtarget->isThumb1Only()) return SDValue();
8224
8225   // Only perform the checks after legalize when the pattern is available.
8226   if (DCI.isBeforeLegalize()) return SDValue();
8227
8228   // Look for multiply add opportunities.
8229   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8230   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8231   // a glue link from the first add to the second add.
8232   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8233   // a S/UMLAL instruction.
8234   //          loAdd   UMUL_LOHI
8235   //            \    / :lo    \ :hi
8236   //             \  /          \          [no multiline comment]
8237   //              ADDC         |  hiAdd
8238   //                 \ :glue  /  /
8239   //                  \      /  /
8240   //                    ADDE
8241   //
8242   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8243   SDValue AddcOp0 = AddcNode->getOperand(0);
8244   SDValue AddcOp1 = AddcNode->getOperand(1);
8245
8246   // Check if the two operands are from the same mul_lohi node.
8247   if (AddcOp0.getNode() == AddcOp1.getNode())
8248     return SDValue();
8249
8250   assert(AddcNode->getNumValues() == 2 &&
8251          AddcNode->getValueType(0) == MVT::i32 &&
8252          "Expect ADDC with two result values. First: i32");
8253
8254   // Check that we have a glued ADDC node.
8255   if (AddcNode->getValueType(1) != MVT::Glue)
8256     return SDValue();
8257
8258   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8259   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8260       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8261       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8262       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8263     return SDValue();
8264
8265   // Look for the glued ADDE.
8266   SDNode* AddeNode = AddcNode->getGluedUser();
8267   if (AddeNode == NULL)
8268     return SDValue();
8269
8270   // Make sure it is really an ADDE.
8271   if (AddeNode->getOpcode() != ISD::ADDE)
8272     return SDValue();
8273
8274   assert(AddeNode->getNumOperands() == 3 &&
8275          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8276          "ADDE node has the wrong inputs");
8277
8278   // Check for the triangle shape.
8279   SDValue AddeOp0 = AddeNode->getOperand(0);
8280   SDValue AddeOp1 = AddeNode->getOperand(1);
8281
8282   // Make sure that the ADDE operands are not coming from the same node.
8283   if (AddeOp0.getNode() == AddeOp1.getNode())
8284     return SDValue();
8285
8286   // Find the MUL_LOHI node walking up ADDE's operands.
8287   bool IsLeftOperandMUL = false;
8288   SDValue MULOp = findMUL_LOHI(AddeOp0);
8289   if (MULOp == SDValue())
8290    MULOp = findMUL_LOHI(AddeOp1);
8291   else
8292     IsLeftOperandMUL = true;
8293   if (MULOp == SDValue())
8294      return SDValue();
8295
8296   // Figure out the right opcode.
8297   unsigned Opc = MULOp->getOpcode();
8298   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8299
8300   // Figure out the high and low input values to the MLAL node.
8301   SDValue* HiMul = &MULOp;
8302   SDValue* HiAdd = NULL;
8303   SDValue* LoMul = NULL;
8304   SDValue* LowAdd = NULL;
8305
8306   if (IsLeftOperandMUL)
8307     HiAdd = &AddeOp1;
8308   else
8309     HiAdd = &AddeOp0;
8310
8311
8312   if (AddcOp0->getOpcode() == Opc) {
8313     LoMul = &AddcOp0;
8314     LowAdd = &AddcOp1;
8315   }
8316   if (AddcOp1->getOpcode() == Opc) {
8317     LoMul = &AddcOp1;
8318     LowAdd = &AddcOp0;
8319   }
8320
8321   if (LoMul == NULL)
8322     return SDValue();
8323
8324   if (LoMul->getNode() != HiMul->getNode())
8325     return SDValue();
8326
8327   // Create the merged node.
8328   SelectionDAG &DAG = DCI.DAG;
8329
8330   // Build operand list.
8331   SmallVector<SDValue, 8> Ops;
8332   Ops.push_back(LoMul->getOperand(0));
8333   Ops.push_back(LoMul->getOperand(1));
8334   Ops.push_back(*LowAdd);
8335   Ops.push_back(*HiAdd);
8336
8337   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8338                                  DAG.getVTList(MVT::i32, MVT::i32),
8339                                  &Ops[0], Ops.size());
8340
8341   // Replace the ADDs' nodes uses by the MLA node's values.
8342   SDValue HiMLALResult(MLALNode.getNode(), 1);
8343   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8344
8345   SDValue LoMLALResult(MLALNode.getNode(), 0);
8346   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8347
8348   // Return original node to notify the driver to stop replacing.
8349   SDValue resNode(AddcNode, 0);
8350   return resNode;
8351 }
8352
8353 /// PerformADDCCombine - Target-specific dag combine transform from
8354 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8355 static SDValue PerformADDCCombine(SDNode *N,
8356                                  TargetLowering::DAGCombinerInfo &DCI,
8357                                  const ARMSubtarget *Subtarget) {
8358
8359   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8360
8361 }
8362
8363 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8364 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8365 /// called with the default operands, and if that fails, with commuted
8366 /// operands.
8367 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8368                                           TargetLowering::DAGCombinerInfo &DCI,
8369                                           const ARMSubtarget *Subtarget){
8370
8371   // Attempt to create vpaddl for this add.
8372   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8373   if (Result.getNode())
8374     return Result;
8375
8376   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8377   if (N0.getNode()->hasOneUse()) {
8378     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8379     if (Result.getNode()) return Result;
8380   }
8381   return SDValue();
8382 }
8383
8384 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8385 ///
8386 static SDValue PerformADDCombine(SDNode *N,
8387                                  TargetLowering::DAGCombinerInfo &DCI,
8388                                  const ARMSubtarget *Subtarget) {
8389   SDValue N0 = N->getOperand(0);
8390   SDValue N1 = N->getOperand(1);
8391
8392   // First try with the default operand order.
8393   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8394   if (Result.getNode())
8395     return Result;
8396
8397   // If that didn't work, try again with the operands commuted.
8398   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8399 }
8400
8401 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8402 ///
8403 static SDValue PerformSUBCombine(SDNode *N,
8404                                  TargetLowering::DAGCombinerInfo &DCI) {
8405   SDValue N0 = N->getOperand(0);
8406   SDValue N1 = N->getOperand(1);
8407
8408   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8409   if (N1.getNode()->hasOneUse()) {
8410     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8411     if (Result.getNode()) return Result;
8412   }
8413
8414   return SDValue();
8415 }
8416
8417 /// PerformVMULCombine
8418 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8419 /// special multiplier accumulator forwarding.
8420 ///   vmul d3, d0, d2
8421 ///   vmla d3, d1, d2
8422 /// is faster than
8423 ///   vadd d3, d0, d1
8424 ///   vmul d3, d3, d2
8425 //  However, for (A + B) * (A + B),
8426 //    vadd d2, d0, d1
8427 //    vmul d3, d0, d2
8428 //    vmla d3, d1, d2
8429 //  is slower than
8430 //    vadd d2, d0, d1
8431 //    vmul d3, d2, d2
8432 static SDValue PerformVMULCombine(SDNode *N,
8433                                   TargetLowering::DAGCombinerInfo &DCI,
8434                                   const ARMSubtarget *Subtarget) {
8435   if (!Subtarget->hasVMLxForwarding())
8436     return SDValue();
8437
8438   SelectionDAG &DAG = DCI.DAG;
8439   SDValue N0 = N->getOperand(0);
8440   SDValue N1 = N->getOperand(1);
8441   unsigned Opcode = N0.getOpcode();
8442   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8443       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8444     Opcode = N1.getOpcode();
8445     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8446         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8447       return SDValue();
8448     std::swap(N0, N1);
8449   }
8450
8451   if (N0 == N1)
8452     return SDValue();
8453
8454   EVT VT = N->getValueType(0);
8455   SDLoc DL(N);
8456   SDValue N00 = N0->getOperand(0);
8457   SDValue N01 = N0->getOperand(1);
8458   return DAG.getNode(Opcode, DL, VT,
8459                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8460                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8461 }
8462
8463 static SDValue PerformMULCombine(SDNode *N,
8464                                  TargetLowering::DAGCombinerInfo &DCI,
8465                                  const ARMSubtarget *Subtarget) {
8466   SelectionDAG &DAG = DCI.DAG;
8467
8468   if (Subtarget->isThumb1Only())
8469     return SDValue();
8470
8471   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8472     return SDValue();
8473
8474   EVT VT = N->getValueType(0);
8475   if (VT.is64BitVector() || VT.is128BitVector())
8476     return PerformVMULCombine(N, DCI, Subtarget);
8477   if (VT != MVT::i32)
8478     return SDValue();
8479
8480   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8481   if (!C)
8482     return SDValue();
8483
8484   int64_t MulAmt = C->getSExtValue();
8485   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8486
8487   ShiftAmt = ShiftAmt & (32 - 1);
8488   SDValue V = N->getOperand(0);
8489   SDLoc DL(N);
8490
8491   SDValue Res;
8492   MulAmt >>= ShiftAmt;
8493
8494   if (MulAmt >= 0) {
8495     if (isPowerOf2_32(MulAmt - 1)) {
8496       // (mul x, 2^N + 1) => (add (shl x, N), x)
8497       Res = DAG.getNode(ISD::ADD, DL, VT,
8498                         V,
8499                         DAG.getNode(ISD::SHL, DL, VT,
8500                                     V,
8501                                     DAG.getConstant(Log2_32(MulAmt - 1),
8502                                                     MVT::i32)));
8503     } else if (isPowerOf2_32(MulAmt + 1)) {
8504       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8505       Res = DAG.getNode(ISD::SUB, DL, VT,
8506                         DAG.getNode(ISD::SHL, DL, VT,
8507                                     V,
8508                                     DAG.getConstant(Log2_32(MulAmt + 1),
8509                                                     MVT::i32)),
8510                         V);
8511     } else
8512       return SDValue();
8513   } else {
8514     uint64_t MulAmtAbs = -MulAmt;
8515     if (isPowerOf2_32(MulAmtAbs + 1)) {
8516       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8517       Res = DAG.getNode(ISD::SUB, DL, VT,
8518                         V,
8519                         DAG.getNode(ISD::SHL, DL, VT,
8520                                     V,
8521                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8522                                                     MVT::i32)));
8523     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8524       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8525       Res = DAG.getNode(ISD::ADD, DL, VT,
8526                         V,
8527                         DAG.getNode(ISD::SHL, DL, VT,
8528                                     V,
8529                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8530                                                     MVT::i32)));
8531       Res = DAG.getNode(ISD::SUB, DL, VT,
8532                         DAG.getConstant(0, MVT::i32),Res);
8533
8534     } else
8535       return SDValue();
8536   }
8537
8538   if (ShiftAmt != 0)
8539     Res = DAG.getNode(ISD::SHL, DL, VT,
8540                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8541
8542   // Do not add new nodes to DAG combiner worklist.
8543   DCI.CombineTo(N, Res, false);
8544   return SDValue();
8545 }
8546
8547 static SDValue PerformANDCombine(SDNode *N,
8548                                  TargetLowering::DAGCombinerInfo &DCI,
8549                                  const ARMSubtarget *Subtarget) {
8550
8551   // Attempt to use immediate-form VBIC
8552   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8553   SDLoc dl(N);
8554   EVT VT = N->getValueType(0);
8555   SelectionDAG &DAG = DCI.DAG;
8556
8557   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8558     return SDValue();
8559
8560   APInt SplatBits, SplatUndef;
8561   unsigned SplatBitSize;
8562   bool HasAnyUndefs;
8563   if (BVN &&
8564       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8565     if (SplatBitSize <= 64) {
8566       EVT VbicVT;
8567       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8568                                       SplatUndef.getZExtValue(), SplatBitSize,
8569                                       DAG, VbicVT, VT.is128BitVector(),
8570                                       OtherModImm);
8571       if (Val.getNode()) {
8572         SDValue Input =
8573           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8574         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8575         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8576       }
8577     }
8578   }
8579
8580   if (!Subtarget->isThumb1Only()) {
8581     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8582     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8583     if (Result.getNode())
8584       return Result;
8585   }
8586
8587   return SDValue();
8588 }
8589
8590 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8591 static SDValue PerformORCombine(SDNode *N,
8592                                 TargetLowering::DAGCombinerInfo &DCI,
8593                                 const ARMSubtarget *Subtarget) {
8594   // Attempt to use immediate-form VORR
8595   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8596   SDLoc dl(N);
8597   EVT VT = N->getValueType(0);
8598   SelectionDAG &DAG = DCI.DAG;
8599
8600   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8601     return SDValue();
8602
8603   APInt SplatBits, SplatUndef;
8604   unsigned SplatBitSize;
8605   bool HasAnyUndefs;
8606   if (BVN && Subtarget->hasNEON() &&
8607       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8608     if (SplatBitSize <= 64) {
8609       EVT VorrVT;
8610       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8611                                       SplatUndef.getZExtValue(), SplatBitSize,
8612                                       DAG, VorrVT, VT.is128BitVector(),
8613                                       OtherModImm);
8614       if (Val.getNode()) {
8615         SDValue Input =
8616           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8617         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8618         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8619       }
8620     }
8621   }
8622
8623   if (!Subtarget->isThumb1Only()) {
8624     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8625     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8626     if (Result.getNode())
8627       return Result;
8628   }
8629
8630   // The code below optimizes (or (and X, Y), Z).
8631   // The AND operand needs to have a single user to make these optimizations
8632   // profitable.
8633   SDValue N0 = N->getOperand(0);
8634   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8635     return SDValue();
8636   SDValue N1 = N->getOperand(1);
8637
8638   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8639   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8640       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8641     APInt SplatUndef;
8642     unsigned SplatBitSize;
8643     bool HasAnyUndefs;
8644
8645     APInt SplatBits0, SplatBits1;
8646     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8647     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8648     // Ensure that the second operand of both ands are constants
8649     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8650                                       HasAnyUndefs) && !HasAnyUndefs) {
8651         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8652                                           HasAnyUndefs) && !HasAnyUndefs) {
8653             // Ensure that the bit width of the constants are the same and that
8654             // the splat arguments are logical inverses as per the pattern we
8655             // are trying to simplify.
8656             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8657                 SplatBits0 == ~SplatBits1) {
8658                 // Canonicalize the vector type to make instruction selection
8659                 // simpler.
8660                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8661                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8662                                              N0->getOperand(1),
8663                                              N0->getOperand(0),
8664                                              N1->getOperand(0));
8665                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8666             }
8667         }
8668     }
8669   }
8670
8671   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8672   // reasonable.
8673
8674   // BFI is only available on V6T2+
8675   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8676     return SDValue();
8677
8678   SDLoc DL(N);
8679   // 1) or (and A, mask), val => ARMbfi A, val, mask
8680   //      iff (val & mask) == val
8681   //
8682   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8683   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8684   //          && mask == ~mask2
8685   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8686   //          && ~mask == mask2
8687   //  (i.e., copy a bitfield value into another bitfield of the same width)
8688
8689   if (VT != MVT::i32)
8690     return SDValue();
8691
8692   SDValue N00 = N0.getOperand(0);
8693
8694   // The value and the mask need to be constants so we can verify this is
8695   // actually a bitfield set. If the mask is 0xffff, we can do better
8696   // via a movt instruction, so don't use BFI in that case.
8697   SDValue MaskOp = N0.getOperand(1);
8698   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8699   if (!MaskC)
8700     return SDValue();
8701   unsigned Mask = MaskC->getZExtValue();
8702   if (Mask == 0xffff)
8703     return SDValue();
8704   SDValue Res;
8705   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8706   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8707   if (N1C) {
8708     unsigned Val = N1C->getZExtValue();
8709     if ((Val & ~Mask) != Val)
8710       return SDValue();
8711
8712     if (ARM::isBitFieldInvertedMask(Mask)) {
8713       Val >>= countTrailingZeros(~Mask);
8714
8715       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8716                         DAG.getConstant(Val, MVT::i32),
8717                         DAG.getConstant(Mask, MVT::i32));
8718
8719       // Do not add new nodes to DAG combiner worklist.
8720       DCI.CombineTo(N, Res, false);
8721       return SDValue();
8722     }
8723   } else if (N1.getOpcode() == ISD::AND) {
8724     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8725     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8726     if (!N11C)
8727       return SDValue();
8728     unsigned Mask2 = N11C->getZExtValue();
8729
8730     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8731     // as is to match.
8732     if (ARM::isBitFieldInvertedMask(Mask) &&
8733         (Mask == ~Mask2)) {
8734       // The pack halfword instruction works better for masks that fit it,
8735       // so use that when it's available.
8736       if (Subtarget->hasT2ExtractPack() &&
8737           (Mask == 0xffff || Mask == 0xffff0000))
8738         return SDValue();
8739       // 2a
8740       unsigned amt = countTrailingZeros(Mask2);
8741       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8742                         DAG.getConstant(amt, MVT::i32));
8743       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8744                         DAG.getConstant(Mask, MVT::i32));
8745       // Do not add new nodes to DAG combiner worklist.
8746       DCI.CombineTo(N, Res, false);
8747       return SDValue();
8748     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8749                (~Mask == Mask2)) {
8750       // The pack halfword instruction works better for masks that fit it,
8751       // so use that when it's available.
8752       if (Subtarget->hasT2ExtractPack() &&
8753           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8754         return SDValue();
8755       // 2b
8756       unsigned lsb = countTrailingZeros(Mask);
8757       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8758                         DAG.getConstant(lsb, MVT::i32));
8759       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8760                         DAG.getConstant(Mask2, MVT::i32));
8761       // Do not add new nodes to DAG combiner worklist.
8762       DCI.CombineTo(N, Res, false);
8763       return SDValue();
8764     }
8765   }
8766
8767   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8768       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8769       ARM::isBitFieldInvertedMask(~Mask)) {
8770     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8771     // where lsb(mask) == #shamt and masked bits of B are known zero.
8772     SDValue ShAmt = N00.getOperand(1);
8773     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8774     unsigned LSB = countTrailingZeros(Mask);
8775     if (ShAmtC != LSB)
8776       return SDValue();
8777
8778     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8779                       DAG.getConstant(~Mask, MVT::i32));
8780
8781     // Do not add new nodes to DAG combiner worklist.
8782     DCI.CombineTo(N, Res, false);
8783   }
8784
8785   return SDValue();
8786 }
8787
8788 static SDValue PerformXORCombine(SDNode *N,
8789                                  TargetLowering::DAGCombinerInfo &DCI,
8790                                  const ARMSubtarget *Subtarget) {
8791   EVT VT = N->getValueType(0);
8792   SelectionDAG &DAG = DCI.DAG;
8793
8794   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8795     return SDValue();
8796
8797   if (!Subtarget->isThumb1Only()) {
8798     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8799     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8800     if (Result.getNode())
8801       return Result;
8802   }
8803
8804   return SDValue();
8805 }
8806
8807 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8808 /// the bits being cleared by the AND are not demanded by the BFI.
8809 static SDValue PerformBFICombine(SDNode *N,
8810                                  TargetLowering::DAGCombinerInfo &DCI) {
8811   SDValue N1 = N->getOperand(1);
8812   if (N1.getOpcode() == ISD::AND) {
8813     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8814     if (!N11C)
8815       return SDValue();
8816     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8817     unsigned LSB = countTrailingZeros(~InvMask);
8818     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8819     unsigned Mask = (1 << Width)-1;
8820     unsigned Mask2 = N11C->getZExtValue();
8821     if ((Mask & (~Mask2)) == 0)
8822       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8823                              N->getOperand(0), N1.getOperand(0),
8824                              N->getOperand(2));
8825   }
8826   return SDValue();
8827 }
8828
8829 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8830 /// ARMISD::VMOVRRD.
8831 static SDValue PerformVMOVRRDCombine(SDNode *N,
8832                                      TargetLowering::DAGCombinerInfo &DCI) {
8833   // vmovrrd(vmovdrr x, y) -> x,y
8834   SDValue InDouble = N->getOperand(0);
8835   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8836     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8837
8838   // vmovrrd(load f64) -> (load i32), (load i32)
8839   SDNode *InNode = InDouble.getNode();
8840   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8841       InNode->getValueType(0) == MVT::f64 &&
8842       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8843       !cast<LoadSDNode>(InNode)->isVolatile()) {
8844     // TODO: Should this be done for non-FrameIndex operands?
8845     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8846
8847     SelectionDAG &DAG = DCI.DAG;
8848     SDLoc DL(LD);
8849     SDValue BasePtr = LD->getBasePtr();
8850     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8851                                  LD->getPointerInfo(), LD->isVolatile(),
8852                                  LD->isNonTemporal(), LD->isInvariant(),
8853                                  LD->getAlignment());
8854
8855     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8856                                     DAG.getConstant(4, MVT::i32));
8857     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8858                                  LD->getPointerInfo(), LD->isVolatile(),
8859                                  LD->isNonTemporal(), LD->isInvariant(),
8860                                  std::min(4U, LD->getAlignment() / 2));
8861
8862     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8863     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8864     DCI.RemoveFromWorklist(LD);
8865     DAG.DeleteNode(LD);
8866     return Result;
8867   }
8868
8869   return SDValue();
8870 }
8871
8872 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8873 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8874 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8875   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8876   SDValue Op0 = N->getOperand(0);
8877   SDValue Op1 = N->getOperand(1);
8878   if (Op0.getOpcode() == ISD::BITCAST)
8879     Op0 = Op0.getOperand(0);
8880   if (Op1.getOpcode() == ISD::BITCAST)
8881     Op1 = Op1.getOperand(0);
8882   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8883       Op0.getNode() == Op1.getNode() &&
8884       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8885     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8886                        N->getValueType(0), Op0.getOperand(0));
8887   return SDValue();
8888 }
8889
8890 /// PerformSTORECombine - Target-specific dag combine xforms for
8891 /// ISD::STORE.
8892 static SDValue PerformSTORECombine(SDNode *N,
8893                                    TargetLowering::DAGCombinerInfo &DCI) {
8894   StoreSDNode *St = cast<StoreSDNode>(N);
8895   if (St->isVolatile())
8896     return SDValue();
8897
8898   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8899   // pack all of the elements in one place.  Next, store to memory in fewer
8900   // chunks.
8901   SDValue StVal = St->getValue();
8902   EVT VT = StVal.getValueType();
8903   if (St->isTruncatingStore() && VT.isVector()) {
8904     SelectionDAG &DAG = DCI.DAG;
8905     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8906     EVT StVT = St->getMemoryVT();
8907     unsigned NumElems = VT.getVectorNumElements();
8908     assert(StVT != VT && "Cannot truncate to the same type");
8909     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8910     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8911
8912     // From, To sizes and ElemCount must be pow of two
8913     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8914
8915     // We are going to use the original vector elt for storing.
8916     // Accumulated smaller vector elements must be a multiple of the store size.
8917     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8918
8919     unsigned SizeRatio  = FromEltSz / ToEltSz;
8920     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8921
8922     // Create a type on which we perform the shuffle.
8923     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8924                                      NumElems*SizeRatio);
8925     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8926
8927     SDLoc DL(St);
8928     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8929     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8930     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8931
8932     // Can't shuffle using an illegal type.
8933     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8934
8935     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8936                                 DAG.getUNDEF(WideVec.getValueType()),
8937                                 ShuffleVec.data());
8938     // At this point all of the data is stored at the bottom of the
8939     // register. We now need to save it to mem.
8940
8941     // Find the largest store unit
8942     MVT StoreType = MVT::i8;
8943     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8944          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8945       MVT Tp = (MVT::SimpleValueType)tp;
8946       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8947         StoreType = Tp;
8948     }
8949     // Didn't find a legal store type.
8950     if (!TLI.isTypeLegal(StoreType))
8951       return SDValue();
8952
8953     // Bitcast the original vector into a vector of store-size units
8954     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8955             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8956     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8957     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8958     SmallVector<SDValue, 8> Chains;
8959     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8960                                         TLI.getPointerTy());
8961     SDValue BasePtr = St->getBasePtr();
8962
8963     // Perform one or more big stores into memory.
8964     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8965     for (unsigned I = 0; I < E; I++) {
8966       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8967                                    StoreType, ShuffWide,
8968                                    DAG.getIntPtrConstant(I));
8969       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8970                                 St->getPointerInfo(), St->isVolatile(),
8971                                 St->isNonTemporal(), St->getAlignment());
8972       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8973                             Increment);
8974       Chains.push_back(Ch);
8975     }
8976     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
8977                        Chains.size());
8978   }
8979
8980   if (!ISD::isNormalStore(St))
8981     return SDValue();
8982
8983   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8984   // ARM stores of arguments in the same cache line.
8985   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8986       StVal.getNode()->hasOneUse()) {
8987     SelectionDAG  &DAG = DCI.DAG;
8988     SDLoc DL(St);
8989     SDValue BasePtr = St->getBasePtr();
8990     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8991                                   StVal.getNode()->getOperand(0), BasePtr,
8992                                   St->getPointerInfo(), St->isVolatile(),
8993                                   St->isNonTemporal(), St->getAlignment());
8994
8995     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8996                                     DAG.getConstant(4, MVT::i32));
8997     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
8998                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8999                         St->isNonTemporal(),
9000                         std::min(4U, St->getAlignment() / 2));
9001   }
9002
9003   if (StVal.getValueType() != MVT::i64 ||
9004       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9005     return SDValue();
9006
9007   // Bitcast an i64 store extracted from a vector to f64.
9008   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9009   SelectionDAG &DAG = DCI.DAG;
9010   SDLoc dl(StVal);
9011   SDValue IntVec = StVal.getOperand(0);
9012   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9013                                  IntVec.getValueType().getVectorNumElements());
9014   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9015   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9016                                Vec, StVal.getOperand(1));
9017   dl = SDLoc(N);
9018   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9019   // Make the DAGCombiner fold the bitcasts.
9020   DCI.AddToWorklist(Vec.getNode());
9021   DCI.AddToWorklist(ExtElt.getNode());
9022   DCI.AddToWorklist(V.getNode());
9023   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9024                       St->getPointerInfo(), St->isVolatile(),
9025                       St->isNonTemporal(), St->getAlignment(),
9026                       St->getTBAAInfo());
9027 }
9028
9029 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9030 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
9031 /// i64 vector to have f64 elements, since the value can then be loaded
9032 /// directly into a VFP register.
9033 static bool hasNormalLoadOperand(SDNode *N) {
9034   unsigned NumElts = N->getValueType(0).getVectorNumElements();
9035   for (unsigned i = 0; i < NumElts; ++i) {
9036     SDNode *Elt = N->getOperand(i).getNode();
9037     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9038       return true;
9039   }
9040   return false;
9041 }
9042
9043 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9044 /// ISD::BUILD_VECTOR.
9045 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9046                                           TargetLowering::DAGCombinerInfo &DCI){
9047   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9048   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
9049   // into a pair of GPRs, which is fine when the value is used as a scalar,
9050   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9051   SelectionDAG &DAG = DCI.DAG;
9052   if (N->getNumOperands() == 2) {
9053     SDValue RV = PerformVMOVDRRCombine(N, DAG);
9054     if (RV.getNode())
9055       return RV;
9056   }
9057
9058   // Load i64 elements as f64 values so that type legalization does not split
9059   // them up into i32 values.
9060   EVT VT = N->getValueType(0);
9061   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9062     return SDValue();
9063   SDLoc dl(N);
9064   SmallVector<SDValue, 8> Ops;
9065   unsigned NumElts = VT.getVectorNumElements();
9066   for (unsigned i = 0; i < NumElts; ++i) {
9067     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9068     Ops.push_back(V);
9069     // Make the DAGCombiner fold the bitcast.
9070     DCI.AddToWorklist(V.getNode());
9071   }
9072   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9073   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
9074   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9075 }
9076
9077 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9078 static SDValue
9079 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9080   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9081   // At that time, we may have inserted bitcasts from integer to float.
9082   // If these bitcasts have survived DAGCombine, change the lowering of this
9083   // BUILD_VECTOR in something more vector friendly, i.e., that does not
9084   // force to use floating point types.
9085
9086   // Make sure we can change the type of the vector.
9087   // This is possible iff:
9088   // 1. The vector is only used in a bitcast to a integer type. I.e.,
9089   //    1.1. Vector is used only once.
9090   //    1.2. Use is a bit convert to an integer type.
9091   // 2. The size of its operands are 32-bits (64-bits are not legal).
9092   EVT VT = N->getValueType(0);
9093   EVT EltVT = VT.getVectorElementType();
9094
9095   // Check 1.1. and 2.
9096   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9097     return SDValue();
9098
9099   // By construction, the input type must be float.
9100   assert(EltVT == MVT::f32 && "Unexpected type!");
9101
9102   // Check 1.2.
9103   SDNode *Use = *N->use_begin();
9104   if (Use->getOpcode() != ISD::BITCAST ||
9105       Use->getValueType(0).isFloatingPoint())
9106     return SDValue();
9107
9108   // Check profitability.
9109   // Model is, if more than half of the relevant operands are bitcast from
9110   // i32, turn the build_vector into a sequence of insert_vector_elt.
9111   // Relevant operands are everything that is not statically
9112   // (i.e., at compile time) bitcasted.
9113   unsigned NumOfBitCastedElts = 0;
9114   unsigned NumElts = VT.getVectorNumElements();
9115   unsigned NumOfRelevantElts = NumElts;
9116   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9117     SDValue Elt = N->getOperand(Idx);
9118     if (Elt->getOpcode() == ISD::BITCAST) {
9119       // Assume only bit cast to i32 will go away.
9120       if (Elt->getOperand(0).getValueType() == MVT::i32)
9121         ++NumOfBitCastedElts;
9122     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9123       // Constants are statically casted, thus do not count them as
9124       // relevant operands.
9125       --NumOfRelevantElts;
9126   }
9127
9128   // Check if more than half of the elements require a non-free bitcast.
9129   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9130     return SDValue();
9131
9132   SelectionDAG &DAG = DCI.DAG;
9133   // Create the new vector type.
9134   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9135   // Check if the type is legal.
9136   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9137   if (!TLI.isTypeLegal(VecVT))
9138     return SDValue();
9139
9140   // Combine:
9141   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9142   // => BITCAST INSERT_VECTOR_ELT
9143   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9144   //                      (BITCAST EN), N.
9145   SDValue Vec = DAG.getUNDEF(VecVT);
9146   SDLoc dl(N);
9147   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9148     SDValue V = N->getOperand(Idx);
9149     if (V.getOpcode() == ISD::UNDEF)
9150       continue;
9151     if (V.getOpcode() == ISD::BITCAST &&
9152         V->getOperand(0).getValueType() == MVT::i32)
9153       // Fold obvious case.
9154       V = V.getOperand(0);
9155     else {
9156       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 
9157       // Make the DAGCombiner fold the bitcasts.
9158       DCI.AddToWorklist(V.getNode());
9159     }
9160     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
9161     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9162   }
9163   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9164   // Make the DAGCombiner fold the bitcasts.
9165   DCI.AddToWorklist(Vec.getNode());
9166   return Vec;
9167 }
9168
9169 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9170 /// ISD::INSERT_VECTOR_ELT.
9171 static SDValue PerformInsertEltCombine(SDNode *N,
9172                                        TargetLowering::DAGCombinerInfo &DCI) {
9173   // Bitcast an i64 load inserted into a vector to f64.
9174   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9175   EVT VT = N->getValueType(0);
9176   SDNode *Elt = N->getOperand(1).getNode();
9177   if (VT.getVectorElementType() != MVT::i64 ||
9178       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9179     return SDValue();
9180
9181   SelectionDAG &DAG = DCI.DAG;
9182   SDLoc dl(N);
9183   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9184                                  VT.getVectorNumElements());
9185   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9186   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9187   // Make the DAGCombiner fold the bitcasts.
9188   DCI.AddToWorklist(Vec.getNode());
9189   DCI.AddToWorklist(V.getNode());
9190   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9191                                Vec, V, N->getOperand(2));
9192   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9193 }
9194
9195 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9196 /// ISD::VECTOR_SHUFFLE.
9197 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9198   // The LLVM shufflevector instruction does not require the shuffle mask
9199   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9200   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
9201   // operands do not match the mask length, they are extended by concatenating
9202   // them with undef vectors.  That is probably the right thing for other
9203   // targets, but for NEON it is better to concatenate two double-register
9204   // size vector operands into a single quad-register size vector.  Do that
9205   // transformation here:
9206   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
9207   //   shuffle(concat(v1, v2), undef)
9208   SDValue Op0 = N->getOperand(0);
9209   SDValue Op1 = N->getOperand(1);
9210   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9211       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9212       Op0.getNumOperands() != 2 ||
9213       Op1.getNumOperands() != 2)
9214     return SDValue();
9215   SDValue Concat0Op1 = Op0.getOperand(1);
9216   SDValue Concat1Op1 = Op1.getOperand(1);
9217   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9218       Concat1Op1.getOpcode() != ISD::UNDEF)
9219     return SDValue();
9220   // Skip the transformation if any of the types are illegal.
9221   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9222   EVT VT = N->getValueType(0);
9223   if (!TLI.isTypeLegal(VT) ||
9224       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9225       !TLI.isTypeLegal(Concat1Op1.getValueType()))
9226     return SDValue();
9227
9228   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9229                                   Op0.getOperand(0), Op1.getOperand(0));
9230   // Translate the shuffle mask.
9231   SmallVector<int, 16> NewMask;
9232   unsigned NumElts = VT.getVectorNumElements();
9233   unsigned HalfElts = NumElts/2;
9234   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9235   for (unsigned n = 0; n < NumElts; ++n) {
9236     int MaskElt = SVN->getMaskElt(n);
9237     int NewElt = -1;
9238     if (MaskElt < (int)HalfElts)
9239       NewElt = MaskElt;
9240     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9241       NewElt = HalfElts + MaskElt - NumElts;
9242     NewMask.push_back(NewElt);
9243   }
9244   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9245                               DAG.getUNDEF(VT), NewMask.data());
9246 }
9247
9248 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
9249 /// NEON load/store intrinsics to merge base address updates.
9250 static SDValue CombineBaseUpdate(SDNode *N,
9251                                  TargetLowering::DAGCombinerInfo &DCI) {
9252   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9253     return SDValue();
9254
9255   SelectionDAG &DAG = DCI.DAG;
9256   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9257                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9258   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
9259   SDValue Addr = N->getOperand(AddrOpIdx);
9260
9261   // Search for a use of the address operand that is an increment.
9262   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9263          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9264     SDNode *User = *UI;
9265     if (User->getOpcode() != ISD::ADD ||
9266         UI.getUse().getResNo() != Addr.getResNo())
9267       continue;
9268
9269     // Check that the add is independent of the load/store.  Otherwise, folding
9270     // it would create a cycle.
9271     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9272       continue;
9273
9274     // Find the new opcode for the updating load/store.
9275     bool isLoad = true;
9276     bool isLaneOp = false;
9277     unsigned NewOpc = 0;
9278     unsigned NumVecs = 0;
9279     if (isIntrinsic) {
9280       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9281       switch (IntNo) {
9282       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9283       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9284         NumVecs = 1; break;
9285       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9286         NumVecs = 2; break;
9287       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9288         NumVecs = 3; break;
9289       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9290         NumVecs = 4; break;
9291       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9292         NumVecs = 2; isLaneOp = true; break;
9293       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9294         NumVecs = 3; isLaneOp = true; break;
9295       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9296         NumVecs = 4; isLaneOp = true; break;
9297       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9298         NumVecs = 1; isLoad = false; break;
9299       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9300         NumVecs = 2; isLoad = false; break;
9301       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9302         NumVecs = 3; isLoad = false; break;
9303       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9304         NumVecs = 4; isLoad = false; break;
9305       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9306         NumVecs = 2; isLoad = false; isLaneOp = true; break;
9307       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9308         NumVecs = 3; isLoad = false; isLaneOp = true; break;
9309       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9310         NumVecs = 4; isLoad = false; isLaneOp = true; break;
9311       }
9312     } else {
9313       isLaneOp = true;
9314       switch (N->getOpcode()) {
9315       default: llvm_unreachable("unexpected opcode for Neon base update");
9316       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9317       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9318       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9319       }
9320     }
9321
9322     // Find the size of memory referenced by the load/store.
9323     EVT VecTy;
9324     if (isLoad)
9325       VecTy = N->getValueType(0);
9326     else
9327       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9328     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9329     if (isLaneOp)
9330       NumBytes /= VecTy.getVectorNumElements();
9331
9332     // If the increment is a constant, it must match the memory ref size.
9333     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9334     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9335       uint64_t IncVal = CInc->getZExtValue();
9336       if (IncVal != NumBytes)
9337         continue;
9338     } else if (NumBytes >= 3 * 16) {
9339       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9340       // separate instructions that make it harder to use a non-constant update.
9341       continue;
9342     }
9343
9344     // Create the new updating load/store node.
9345     EVT Tys[6];
9346     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
9347     unsigned n;
9348     for (n = 0; n < NumResultVecs; ++n)
9349       Tys[n] = VecTy;
9350     Tys[n++] = MVT::i32;
9351     Tys[n] = MVT::Other;
9352     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
9353     SmallVector<SDValue, 8> Ops;
9354     Ops.push_back(N->getOperand(0)); // incoming chain
9355     Ops.push_back(N->getOperand(AddrOpIdx));
9356     Ops.push_back(Inc);
9357     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
9358       Ops.push_back(N->getOperand(i));
9359     }
9360     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9361     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9362                                            Ops.data(), Ops.size(),
9363                                            MemInt->getMemoryVT(),
9364                                            MemInt->getMemOperand());
9365
9366     // Update the uses.
9367     std::vector<SDValue> NewResults;
9368     for (unsigned i = 0; i < NumResultVecs; ++i) {
9369       NewResults.push_back(SDValue(UpdN.getNode(), i));
9370     }
9371     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9372     DCI.CombineTo(N, NewResults);
9373     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9374
9375     break;
9376   }
9377   return SDValue();
9378 }
9379
9380 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9381 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9382 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9383 /// return true.
9384 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9385   SelectionDAG &DAG = DCI.DAG;
9386   EVT VT = N->getValueType(0);
9387   // vldN-dup instructions only support 64-bit vectors for N > 1.
9388   if (!VT.is64BitVector())
9389     return false;
9390
9391   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9392   SDNode *VLD = N->getOperand(0).getNode();
9393   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9394     return false;
9395   unsigned NumVecs = 0;
9396   unsigned NewOpc = 0;
9397   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9398   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9399     NumVecs = 2;
9400     NewOpc = ARMISD::VLD2DUP;
9401   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9402     NumVecs = 3;
9403     NewOpc = ARMISD::VLD3DUP;
9404   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9405     NumVecs = 4;
9406     NewOpc = ARMISD::VLD4DUP;
9407   } else {
9408     return false;
9409   }
9410
9411   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9412   // numbers match the load.
9413   unsigned VLDLaneNo =
9414     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9415   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9416        UI != UE; ++UI) {
9417     // Ignore uses of the chain result.
9418     if (UI.getUse().getResNo() == NumVecs)
9419       continue;
9420     SDNode *User = *UI;
9421     if (User->getOpcode() != ARMISD::VDUPLANE ||
9422         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9423       return false;
9424   }
9425
9426   // Create the vldN-dup node.
9427   EVT Tys[5];
9428   unsigned n;
9429   for (n = 0; n < NumVecs; ++n)
9430     Tys[n] = VT;
9431   Tys[n] = MVT::Other;
9432   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
9433   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9434   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9435   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9436                                            Ops, 2, VLDMemInt->getMemoryVT(),
9437                                            VLDMemInt->getMemOperand());
9438
9439   // Update the uses.
9440   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9441        UI != UE; ++UI) {
9442     unsigned ResNo = UI.getUse().getResNo();
9443     // Ignore uses of the chain result.
9444     if (ResNo == NumVecs)
9445       continue;
9446     SDNode *User = *UI;
9447     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9448   }
9449
9450   // Now the vldN-lane intrinsic is dead except for its chain result.
9451   // Update uses of the chain.
9452   std::vector<SDValue> VLDDupResults;
9453   for (unsigned n = 0; n < NumVecs; ++n)
9454     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9455   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9456   DCI.CombineTo(VLD, VLDDupResults);
9457
9458   return true;
9459 }
9460
9461 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9462 /// ARMISD::VDUPLANE.
9463 static SDValue PerformVDUPLANECombine(SDNode *N,
9464                                       TargetLowering::DAGCombinerInfo &DCI) {
9465   SDValue Op = N->getOperand(0);
9466
9467   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9468   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9469   if (CombineVLDDUP(N, DCI))
9470     return SDValue(N, 0);
9471
9472   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9473   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9474   while (Op.getOpcode() == ISD::BITCAST)
9475     Op = Op.getOperand(0);
9476   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9477     return SDValue();
9478
9479   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9480   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9481   // The canonical VMOV for a zero vector uses a 32-bit element size.
9482   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9483   unsigned EltBits;
9484   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9485     EltSize = 8;
9486   EVT VT = N->getValueType(0);
9487   if (EltSize > VT.getVectorElementType().getSizeInBits())
9488     return SDValue();
9489
9490   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9491 }
9492
9493 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9494 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9495 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9496 {
9497   integerPart cN;
9498   integerPart c0 = 0;
9499   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9500        I != E; I++) {
9501     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9502     if (!C)
9503       return false;
9504
9505     bool isExact;
9506     APFloat APF = C->getValueAPF();
9507     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9508         != APFloat::opOK || !isExact)
9509       return false;
9510
9511     c0 = (I == 0) ? cN : c0;
9512     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9513       return false;
9514   }
9515   C = c0;
9516   return true;
9517 }
9518
9519 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9520 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9521 /// when the VMUL has a constant operand that is a power of 2.
9522 ///
9523 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9524 ///  vmul.f32        d16, d17, d16
9525 ///  vcvt.s32.f32    d16, d16
9526 /// becomes:
9527 ///  vcvt.s32.f32    d16, d16, #3
9528 static SDValue PerformVCVTCombine(SDNode *N,
9529                                   TargetLowering::DAGCombinerInfo &DCI,
9530                                   const ARMSubtarget *Subtarget) {
9531   SelectionDAG &DAG = DCI.DAG;
9532   SDValue Op = N->getOperand(0);
9533
9534   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9535       Op.getOpcode() != ISD::FMUL)
9536     return SDValue();
9537
9538   uint64_t C;
9539   SDValue N0 = Op->getOperand(0);
9540   SDValue ConstVec = Op->getOperand(1);
9541   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9542
9543   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9544       !isConstVecPow2(ConstVec, isSigned, C))
9545     return SDValue();
9546
9547   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9548   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9549   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9550     // These instructions only exist converting from f32 to i32. We can handle
9551     // smaller integers by generating an extra truncate, but larger ones would
9552     // be lossy.
9553     return SDValue();
9554   }
9555
9556   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9557     Intrinsic::arm_neon_vcvtfp2fxu;
9558   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9559   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9560                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9561                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9562                                  DAG.getConstant(Log2_64(C), MVT::i32));
9563
9564   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9565     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9566
9567   return FixConv;
9568 }
9569
9570 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9571 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9572 /// when the VDIV has a constant operand that is a power of 2.
9573 ///
9574 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9575 ///  vcvt.f32.s32    d16, d16
9576 ///  vdiv.f32        d16, d17, d16
9577 /// becomes:
9578 ///  vcvt.f32.s32    d16, d16, #3
9579 static SDValue PerformVDIVCombine(SDNode *N,
9580                                   TargetLowering::DAGCombinerInfo &DCI,
9581                                   const ARMSubtarget *Subtarget) {
9582   SelectionDAG &DAG = DCI.DAG;
9583   SDValue Op = N->getOperand(0);
9584   unsigned OpOpcode = Op.getNode()->getOpcode();
9585
9586   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9587       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9588     return SDValue();
9589
9590   uint64_t C;
9591   SDValue ConstVec = N->getOperand(1);
9592   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9593
9594   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9595       !isConstVecPow2(ConstVec, isSigned, C))
9596     return SDValue();
9597
9598   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9599   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9600   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9601     // These instructions only exist converting from i32 to f32. We can handle
9602     // smaller integers by generating an extra extend, but larger ones would
9603     // be lossy.
9604     return SDValue();
9605   }
9606
9607   SDValue ConvInput = Op.getOperand(0);
9608   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9609   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9610     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9611                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9612                             ConvInput);
9613
9614   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9615     Intrinsic::arm_neon_vcvtfxu2fp;
9616   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9617                      Op.getValueType(),
9618                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9619                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9620 }
9621
9622 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9623 /// operand of a vector shift operation, where all the elements of the
9624 /// build_vector must have the same constant integer value.
9625 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9626   // Ignore bit_converts.
9627   while (Op.getOpcode() == ISD::BITCAST)
9628     Op = Op.getOperand(0);
9629   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9630   APInt SplatBits, SplatUndef;
9631   unsigned SplatBitSize;
9632   bool HasAnyUndefs;
9633   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9634                                       HasAnyUndefs, ElementBits) ||
9635       SplatBitSize > ElementBits)
9636     return false;
9637   Cnt = SplatBits.getSExtValue();
9638   return true;
9639 }
9640
9641 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9642 /// operand of a vector shift left operation.  That value must be in the range:
9643 ///   0 <= Value < ElementBits for a left shift; or
9644 ///   0 <= Value <= ElementBits for a long left shift.
9645 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9646   assert(VT.isVector() && "vector shift count is not a vector type");
9647   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9648   if (! getVShiftImm(Op, ElementBits, Cnt))
9649     return false;
9650   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9651 }
9652
9653 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9654 /// operand of a vector shift right operation.  For a shift opcode, the value
9655 /// is positive, but for an intrinsic the value count must be negative. The
9656 /// absolute value must be in the range:
9657 ///   1 <= |Value| <= ElementBits for a right shift; or
9658 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9659 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9660                          int64_t &Cnt) {
9661   assert(VT.isVector() && "vector shift count is not a vector type");
9662   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9663   if (! getVShiftImm(Op, ElementBits, Cnt))
9664     return false;
9665   if (isIntrinsic)
9666     Cnt = -Cnt;
9667   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9668 }
9669
9670 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9671 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9672   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9673   switch (IntNo) {
9674   default:
9675     // Don't do anything for most intrinsics.
9676     break;
9677
9678   // Vector shifts: check for immediate versions and lower them.
9679   // Note: This is done during DAG combining instead of DAG legalizing because
9680   // the build_vectors for 64-bit vector element shift counts are generally
9681   // not legal, and it is hard to see their values after they get legalized to
9682   // loads from a constant pool.
9683   case Intrinsic::arm_neon_vshifts:
9684   case Intrinsic::arm_neon_vshiftu:
9685   case Intrinsic::arm_neon_vshiftls:
9686   case Intrinsic::arm_neon_vshiftlu:
9687   case Intrinsic::arm_neon_vshiftn:
9688   case Intrinsic::arm_neon_vrshifts:
9689   case Intrinsic::arm_neon_vrshiftu:
9690   case Intrinsic::arm_neon_vrshiftn:
9691   case Intrinsic::arm_neon_vqshifts:
9692   case Intrinsic::arm_neon_vqshiftu:
9693   case Intrinsic::arm_neon_vqshiftsu:
9694   case Intrinsic::arm_neon_vqshiftns:
9695   case Intrinsic::arm_neon_vqshiftnu:
9696   case Intrinsic::arm_neon_vqshiftnsu:
9697   case Intrinsic::arm_neon_vqrshiftns:
9698   case Intrinsic::arm_neon_vqrshiftnu:
9699   case Intrinsic::arm_neon_vqrshiftnsu: {
9700     EVT VT = N->getOperand(1).getValueType();
9701     int64_t Cnt;
9702     unsigned VShiftOpc = 0;
9703
9704     switch (IntNo) {
9705     case Intrinsic::arm_neon_vshifts:
9706     case Intrinsic::arm_neon_vshiftu:
9707       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9708         VShiftOpc = ARMISD::VSHL;
9709         break;
9710       }
9711       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9712         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9713                      ARMISD::VSHRs : ARMISD::VSHRu);
9714         break;
9715       }
9716       return SDValue();
9717
9718     case Intrinsic::arm_neon_vshiftls:
9719     case Intrinsic::arm_neon_vshiftlu:
9720       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
9721         break;
9722       llvm_unreachable("invalid shift count for vshll intrinsic");
9723
9724     case Intrinsic::arm_neon_vrshifts:
9725     case Intrinsic::arm_neon_vrshiftu:
9726       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9727         break;
9728       return SDValue();
9729
9730     case Intrinsic::arm_neon_vqshifts:
9731     case Intrinsic::arm_neon_vqshiftu:
9732       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9733         break;
9734       return SDValue();
9735
9736     case Intrinsic::arm_neon_vqshiftsu:
9737       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9738         break;
9739       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9740
9741     case Intrinsic::arm_neon_vshiftn:
9742     case Intrinsic::arm_neon_vrshiftn:
9743     case Intrinsic::arm_neon_vqshiftns:
9744     case Intrinsic::arm_neon_vqshiftnu:
9745     case Intrinsic::arm_neon_vqshiftnsu:
9746     case Intrinsic::arm_neon_vqrshiftns:
9747     case Intrinsic::arm_neon_vqrshiftnu:
9748     case Intrinsic::arm_neon_vqrshiftnsu:
9749       // Narrowing shifts require an immediate right shift.
9750       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9751         break;
9752       llvm_unreachable("invalid shift count for narrowing vector shift "
9753                        "intrinsic");
9754
9755     default:
9756       llvm_unreachable("unhandled vector shift");
9757     }
9758
9759     switch (IntNo) {
9760     case Intrinsic::arm_neon_vshifts:
9761     case Intrinsic::arm_neon_vshiftu:
9762       // Opcode already set above.
9763       break;
9764     case Intrinsic::arm_neon_vshiftls:
9765     case Intrinsic::arm_neon_vshiftlu:
9766       if (Cnt == VT.getVectorElementType().getSizeInBits())
9767         VShiftOpc = ARMISD::VSHLLi;
9768       else
9769         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
9770                      ARMISD::VSHLLs : ARMISD::VSHLLu);
9771       break;
9772     case Intrinsic::arm_neon_vshiftn:
9773       VShiftOpc = ARMISD::VSHRN; break;
9774     case Intrinsic::arm_neon_vrshifts:
9775       VShiftOpc = ARMISD::VRSHRs; break;
9776     case Intrinsic::arm_neon_vrshiftu:
9777       VShiftOpc = ARMISD::VRSHRu; break;
9778     case Intrinsic::arm_neon_vrshiftn:
9779       VShiftOpc = ARMISD::VRSHRN; break;
9780     case Intrinsic::arm_neon_vqshifts:
9781       VShiftOpc = ARMISD::VQSHLs; break;
9782     case Intrinsic::arm_neon_vqshiftu:
9783       VShiftOpc = ARMISD::VQSHLu; break;
9784     case Intrinsic::arm_neon_vqshiftsu:
9785       VShiftOpc = ARMISD::VQSHLsu; break;
9786     case Intrinsic::arm_neon_vqshiftns:
9787       VShiftOpc = ARMISD::VQSHRNs; break;
9788     case Intrinsic::arm_neon_vqshiftnu:
9789       VShiftOpc = ARMISD::VQSHRNu; break;
9790     case Intrinsic::arm_neon_vqshiftnsu:
9791       VShiftOpc = ARMISD::VQSHRNsu; break;
9792     case Intrinsic::arm_neon_vqrshiftns:
9793       VShiftOpc = ARMISD::VQRSHRNs; break;
9794     case Intrinsic::arm_neon_vqrshiftnu:
9795       VShiftOpc = ARMISD::VQRSHRNu; break;
9796     case Intrinsic::arm_neon_vqrshiftnsu:
9797       VShiftOpc = ARMISD::VQRSHRNsu; break;
9798     }
9799
9800     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9801                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9802   }
9803
9804   case Intrinsic::arm_neon_vshiftins: {
9805     EVT VT = N->getOperand(1).getValueType();
9806     int64_t Cnt;
9807     unsigned VShiftOpc = 0;
9808
9809     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9810       VShiftOpc = ARMISD::VSLI;
9811     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9812       VShiftOpc = ARMISD::VSRI;
9813     else {
9814       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9815     }
9816
9817     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9818                        N->getOperand(1), N->getOperand(2),
9819                        DAG.getConstant(Cnt, MVT::i32));
9820   }
9821
9822   case Intrinsic::arm_neon_vqrshifts:
9823   case Intrinsic::arm_neon_vqrshiftu:
9824     // No immediate versions of these to check for.
9825     break;
9826   }
9827
9828   return SDValue();
9829 }
9830
9831 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9832 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9833 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9834 /// vector element shift counts are generally not legal, and it is hard to see
9835 /// their values after they get legalized to loads from a constant pool.
9836 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9837                                    const ARMSubtarget *ST) {
9838   EVT VT = N->getValueType(0);
9839   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9840     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9841     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9842     SDValue N1 = N->getOperand(1);
9843     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9844       SDValue N0 = N->getOperand(0);
9845       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9846           DAG.MaskedValueIsZero(N0.getOperand(0),
9847                                 APInt::getHighBitsSet(32, 16)))
9848         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9849     }
9850   }
9851
9852   // Nothing to be done for scalar shifts.
9853   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9854   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9855     return SDValue();
9856
9857   assert(ST->hasNEON() && "unexpected vector shift");
9858   int64_t Cnt;
9859
9860   switch (N->getOpcode()) {
9861   default: llvm_unreachable("unexpected shift opcode");
9862
9863   case ISD::SHL:
9864     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9865       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9866                          DAG.getConstant(Cnt, MVT::i32));
9867     break;
9868
9869   case ISD::SRA:
9870   case ISD::SRL:
9871     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9872       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9873                             ARMISD::VSHRs : ARMISD::VSHRu);
9874       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9875                          DAG.getConstant(Cnt, MVT::i32));
9876     }
9877   }
9878   return SDValue();
9879 }
9880
9881 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9882 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9883 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9884                                     const ARMSubtarget *ST) {
9885   SDValue N0 = N->getOperand(0);
9886
9887   // Check for sign- and zero-extensions of vector extract operations of 8-
9888   // and 16-bit vector elements.  NEON supports these directly.  They are
9889   // handled during DAG combining because type legalization will promote them
9890   // to 32-bit types and it is messy to recognize the operations after that.
9891   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9892     SDValue Vec = N0.getOperand(0);
9893     SDValue Lane = N0.getOperand(1);
9894     EVT VT = N->getValueType(0);
9895     EVT EltVT = N0.getValueType();
9896     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9897
9898     if (VT == MVT::i32 &&
9899         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9900         TLI.isTypeLegal(Vec.getValueType()) &&
9901         isa<ConstantSDNode>(Lane)) {
9902
9903       unsigned Opc = 0;
9904       switch (N->getOpcode()) {
9905       default: llvm_unreachable("unexpected opcode");
9906       case ISD::SIGN_EXTEND:
9907         Opc = ARMISD::VGETLANEs;
9908         break;
9909       case ISD::ZERO_EXTEND:
9910       case ISD::ANY_EXTEND:
9911         Opc = ARMISD::VGETLANEu;
9912         break;
9913       }
9914       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9915     }
9916   }
9917
9918   return SDValue();
9919 }
9920
9921 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9922 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9923 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9924                                        const ARMSubtarget *ST) {
9925   // If the target supports NEON, try to use vmax/vmin instructions for f32
9926   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9927   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9928   // a NaN; only do the transformation when it matches that behavior.
9929
9930   // For now only do this when using NEON for FP operations; if using VFP, it
9931   // is not obvious that the benefit outweighs the cost of switching to the
9932   // NEON pipeline.
9933   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9934       N->getValueType(0) != MVT::f32)
9935     return SDValue();
9936
9937   SDValue CondLHS = N->getOperand(0);
9938   SDValue CondRHS = N->getOperand(1);
9939   SDValue LHS = N->getOperand(2);
9940   SDValue RHS = N->getOperand(3);
9941   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9942
9943   unsigned Opcode = 0;
9944   bool IsReversed;
9945   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9946     IsReversed = false; // x CC y ? x : y
9947   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9948     IsReversed = true ; // x CC y ? y : x
9949   } else {
9950     return SDValue();
9951   }
9952
9953   bool IsUnordered;
9954   switch (CC) {
9955   default: break;
9956   case ISD::SETOLT:
9957   case ISD::SETOLE:
9958   case ISD::SETLT:
9959   case ISD::SETLE:
9960   case ISD::SETULT:
9961   case ISD::SETULE:
9962     // If LHS is NaN, an ordered comparison will be false and the result will
9963     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9964     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9965     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9966     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9967       break;
9968     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9969     // will return -0, so vmin can only be used for unsafe math or if one of
9970     // the operands is known to be nonzero.
9971     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9972         !DAG.getTarget().Options.UnsafeFPMath &&
9973         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9974       break;
9975     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9976     break;
9977
9978   case ISD::SETOGT:
9979   case ISD::SETOGE:
9980   case ISD::SETGT:
9981   case ISD::SETGE:
9982   case ISD::SETUGT:
9983   case ISD::SETUGE:
9984     // If LHS is NaN, an ordered comparison will be false and the result will
9985     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9986     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9987     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9988     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9989       break;
9990     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9991     // will return +0, so vmax can only be used for unsafe math or if one of
9992     // the operands is known to be nonzero.
9993     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9994         !DAG.getTarget().Options.UnsafeFPMath &&
9995         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9996       break;
9997     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9998     break;
9999   }
10000
10001   if (!Opcode)
10002     return SDValue();
10003   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
10004 }
10005
10006 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10007 SDValue
10008 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10009   SDValue Cmp = N->getOperand(4);
10010   if (Cmp.getOpcode() != ARMISD::CMPZ)
10011     // Only looking at EQ and NE cases.
10012     return SDValue();
10013
10014   EVT VT = N->getValueType(0);
10015   SDLoc dl(N);
10016   SDValue LHS = Cmp.getOperand(0);
10017   SDValue RHS = Cmp.getOperand(1);
10018   SDValue FalseVal = N->getOperand(0);
10019   SDValue TrueVal = N->getOperand(1);
10020   SDValue ARMcc = N->getOperand(2);
10021   ARMCC::CondCodes CC =
10022     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10023
10024   // Simplify
10025   //   mov     r1, r0
10026   //   cmp     r1, x
10027   //   mov     r0, y
10028   //   moveq   r0, x
10029   // to
10030   //   cmp     r0, x
10031   //   movne   r0, y
10032   //
10033   //   mov     r1, r0
10034   //   cmp     r1, x
10035   //   mov     r0, x
10036   //   movne   r0, y
10037   // to
10038   //   cmp     r0, x
10039   //   movne   r0, y
10040   /// FIXME: Turn this into a target neutral optimization?
10041   SDValue Res;
10042   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10043     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10044                       N->getOperand(3), Cmp);
10045   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10046     SDValue ARMcc;
10047     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10048     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10049                       N->getOperand(3), NewCmp);
10050   }
10051
10052   if (Res.getNode()) {
10053     APInt KnownZero, KnownOne;
10054     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
10055     // Capture demanded bits information that would be otherwise lost.
10056     if (KnownZero == 0xfffffffe)
10057       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10058                         DAG.getValueType(MVT::i1));
10059     else if (KnownZero == 0xffffff00)
10060       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10061                         DAG.getValueType(MVT::i8));
10062     else if (KnownZero == 0xffff0000)
10063       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10064                         DAG.getValueType(MVT::i16));
10065   }
10066
10067   return Res;
10068 }
10069
10070 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10071                                              DAGCombinerInfo &DCI) const {
10072   switch (N->getOpcode()) {
10073   default: break;
10074   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
10075   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
10076   case ISD::SUB:        return PerformSUBCombine(N, DCI);
10077   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
10078   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
10079   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
10080   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
10081   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
10082   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
10083   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10084   case ISD::STORE:      return PerformSTORECombine(N, DCI);
10085   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
10086   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10087   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10088   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10089   case ISD::FP_TO_SINT:
10090   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10091   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
10092   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10093   case ISD::SHL:
10094   case ISD::SRA:
10095   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10096   case ISD::SIGN_EXTEND:
10097   case ISD::ZERO_EXTEND:
10098   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10099   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
10100   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10101   case ARMISD::VLD2DUP:
10102   case ARMISD::VLD3DUP:
10103   case ARMISD::VLD4DUP:
10104     return CombineBaseUpdate(N, DCI);
10105   case ARMISD::BUILD_VECTOR:
10106     return PerformARMBUILD_VECTORCombine(N, DCI);
10107   case ISD::INTRINSIC_VOID:
10108   case ISD::INTRINSIC_W_CHAIN:
10109     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10110     case Intrinsic::arm_neon_vld1:
10111     case Intrinsic::arm_neon_vld2:
10112     case Intrinsic::arm_neon_vld3:
10113     case Intrinsic::arm_neon_vld4:
10114     case Intrinsic::arm_neon_vld2lane:
10115     case Intrinsic::arm_neon_vld3lane:
10116     case Intrinsic::arm_neon_vld4lane:
10117     case Intrinsic::arm_neon_vst1:
10118     case Intrinsic::arm_neon_vst2:
10119     case Intrinsic::arm_neon_vst3:
10120     case Intrinsic::arm_neon_vst4:
10121     case Intrinsic::arm_neon_vst2lane:
10122     case Intrinsic::arm_neon_vst3lane:
10123     case Intrinsic::arm_neon_vst4lane:
10124       return CombineBaseUpdate(N, DCI);
10125     default: break;
10126     }
10127     break;
10128   }
10129   return SDValue();
10130 }
10131
10132 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10133                                                           EVT VT) const {
10134   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10135 }
10136
10137 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
10138   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10139   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10140
10141   switch (VT.getSimpleVT().SimpleTy) {
10142   default:
10143     return false;
10144   case MVT::i8:
10145   case MVT::i16:
10146   case MVT::i32: {
10147     // Unaligned access can use (for example) LRDB, LRDH, LDR
10148     if (AllowsUnaligned) {
10149       if (Fast)
10150         *Fast = Subtarget->hasV7Ops();
10151       return true;
10152     }
10153     return false;
10154   }
10155   case MVT::f64:
10156   case MVT::v2f64: {
10157     // For any little-endian targets with neon, we can support unaligned ld/st
10158     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10159     // A big-endian target may also explictly support unaligned accesses
10160     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
10161       if (Fast)
10162         *Fast = true;
10163       return true;
10164     }
10165     return false;
10166   }
10167   }
10168 }
10169
10170 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10171                        unsigned AlignCheck) {
10172   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10173           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10174 }
10175
10176 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10177                                            unsigned DstAlign, unsigned SrcAlign,
10178                                            bool IsMemset, bool ZeroMemset,
10179                                            bool MemcpyStrSrc,
10180                                            MachineFunction &MF) const {
10181   const Function *F = MF.getFunction();
10182
10183   // See if we can use NEON instructions for this...
10184   if ((!IsMemset || ZeroMemset) &&
10185       Subtarget->hasNEON() &&
10186       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
10187                                        Attribute::NoImplicitFloat)) {
10188     bool Fast;
10189     if (Size >= 16 &&
10190         (memOpAlign(SrcAlign, DstAlign, 16) ||
10191          (allowsUnalignedMemoryAccesses(MVT::v2f64, &Fast) && Fast))) {
10192       return MVT::v2f64;
10193     } else if (Size >= 8 &&
10194                (memOpAlign(SrcAlign, DstAlign, 8) ||
10195                 (allowsUnalignedMemoryAccesses(MVT::f64, &Fast) && Fast))) {
10196       return MVT::f64;
10197     }
10198   }
10199
10200   // Lowering to i32/i16 if the size permits.
10201   if (Size >= 4)
10202     return MVT::i32;
10203   else if (Size >= 2)
10204     return MVT::i16;
10205
10206   // Let the target-independent logic figure it out.
10207   return MVT::Other;
10208 }
10209
10210 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10211   if (Val.getOpcode() != ISD::LOAD)
10212     return false;
10213
10214   EVT VT1 = Val.getValueType();
10215   if (!VT1.isSimple() || !VT1.isInteger() ||
10216       !VT2.isSimple() || !VT2.isInteger())
10217     return false;
10218
10219   switch (VT1.getSimpleVT().SimpleTy) {
10220   default: break;
10221   case MVT::i1:
10222   case MVT::i8:
10223   case MVT::i16:
10224     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10225     return true;
10226   }
10227
10228   return false;
10229 }
10230
10231 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10232   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10233     return false;
10234
10235   if (!isTypeLegal(EVT::getEVT(Ty1)))
10236     return false;
10237
10238   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10239
10240   // Assuming the caller doesn't have a zeroext or signext return parameter,
10241   // truncation all the way down to i1 is valid.
10242   return true;
10243 }
10244
10245
10246 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10247   if (V < 0)
10248     return false;
10249
10250   unsigned Scale = 1;
10251   switch (VT.getSimpleVT().SimpleTy) {
10252   default: return false;
10253   case MVT::i1:
10254   case MVT::i8:
10255     // Scale == 1;
10256     break;
10257   case MVT::i16:
10258     // Scale == 2;
10259     Scale = 2;
10260     break;
10261   case MVT::i32:
10262     // Scale == 4;
10263     Scale = 4;
10264     break;
10265   }
10266
10267   if ((V & (Scale - 1)) != 0)
10268     return false;
10269   V /= Scale;
10270   return V == (V & ((1LL << 5) - 1));
10271 }
10272
10273 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10274                                       const ARMSubtarget *Subtarget) {
10275   bool isNeg = false;
10276   if (V < 0) {
10277     isNeg = true;
10278     V = - V;
10279   }
10280
10281   switch (VT.getSimpleVT().SimpleTy) {
10282   default: return false;
10283   case MVT::i1:
10284   case MVT::i8:
10285   case MVT::i16:
10286   case MVT::i32:
10287     // + imm12 or - imm8
10288     if (isNeg)
10289       return V == (V & ((1LL << 8) - 1));
10290     return V == (V & ((1LL << 12) - 1));
10291   case MVT::f32:
10292   case MVT::f64:
10293     // Same as ARM mode. FIXME: NEON?
10294     if (!Subtarget->hasVFP2())
10295       return false;
10296     if ((V & 3) != 0)
10297       return false;
10298     V >>= 2;
10299     return V == (V & ((1LL << 8) - 1));
10300   }
10301 }
10302
10303 /// isLegalAddressImmediate - Return true if the integer value can be used
10304 /// as the offset of the target addressing mode for load / store of the
10305 /// given type.
10306 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10307                                     const ARMSubtarget *Subtarget) {
10308   if (V == 0)
10309     return true;
10310
10311   if (!VT.isSimple())
10312     return false;
10313
10314   if (Subtarget->isThumb1Only())
10315     return isLegalT1AddressImmediate(V, VT);
10316   else if (Subtarget->isThumb2())
10317     return isLegalT2AddressImmediate(V, VT, Subtarget);
10318
10319   // ARM mode.
10320   if (V < 0)
10321     V = - V;
10322   switch (VT.getSimpleVT().SimpleTy) {
10323   default: return false;
10324   case MVT::i1:
10325   case MVT::i8:
10326   case MVT::i32:
10327     // +- imm12
10328     return V == (V & ((1LL << 12) - 1));
10329   case MVT::i16:
10330     // +- imm8
10331     return V == (V & ((1LL << 8) - 1));
10332   case MVT::f32:
10333   case MVT::f64:
10334     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10335       return false;
10336     if ((V & 3) != 0)
10337       return false;
10338     V >>= 2;
10339     return V == (V & ((1LL << 8) - 1));
10340   }
10341 }
10342
10343 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10344                                                       EVT VT) const {
10345   int Scale = AM.Scale;
10346   if (Scale < 0)
10347     return false;
10348
10349   switch (VT.getSimpleVT().SimpleTy) {
10350   default: return false;
10351   case MVT::i1:
10352   case MVT::i8:
10353   case MVT::i16:
10354   case MVT::i32:
10355     if (Scale == 1)
10356       return true;
10357     // r + r << imm
10358     Scale = Scale & ~1;
10359     return Scale == 2 || Scale == 4 || Scale == 8;
10360   case MVT::i64:
10361     // r + r
10362     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10363       return true;
10364     return false;
10365   case MVT::isVoid:
10366     // Note, we allow "void" uses (basically, uses that aren't loads or
10367     // stores), because arm allows folding a scale into many arithmetic
10368     // operations.  This should be made more precise and revisited later.
10369
10370     // Allow r << imm, but the imm has to be a multiple of two.
10371     if (Scale & 1) return false;
10372     return isPowerOf2_32(Scale);
10373   }
10374 }
10375
10376 /// isLegalAddressingMode - Return true if the addressing mode represented
10377 /// by AM is legal for this target, for a load/store of the specified type.
10378 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10379                                               Type *Ty) const {
10380   EVT VT = getValueType(Ty, true);
10381   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10382     return false;
10383
10384   // Can never fold addr of global into load/store.
10385   if (AM.BaseGV)
10386     return false;
10387
10388   switch (AM.Scale) {
10389   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10390     break;
10391   case 1:
10392     if (Subtarget->isThumb1Only())
10393       return false;
10394     // FALL THROUGH.
10395   default:
10396     // ARM doesn't support any R+R*scale+imm addr modes.
10397     if (AM.BaseOffs)
10398       return false;
10399
10400     if (!VT.isSimple())
10401       return false;
10402
10403     if (Subtarget->isThumb2())
10404       return isLegalT2ScaledAddressingMode(AM, VT);
10405
10406     int Scale = AM.Scale;
10407     switch (VT.getSimpleVT().SimpleTy) {
10408     default: return false;
10409     case MVT::i1:
10410     case MVT::i8:
10411     case MVT::i32:
10412       if (Scale < 0) Scale = -Scale;
10413       if (Scale == 1)
10414         return true;
10415       // r + r << imm
10416       return isPowerOf2_32(Scale & ~1);
10417     case MVT::i16:
10418     case MVT::i64:
10419       // r + r
10420       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10421         return true;
10422       return false;
10423
10424     case MVT::isVoid:
10425       // Note, we allow "void" uses (basically, uses that aren't loads or
10426       // stores), because arm allows folding a scale into many arithmetic
10427       // operations.  This should be made more precise and revisited later.
10428
10429       // Allow r << imm, but the imm has to be a multiple of two.
10430       if (Scale & 1) return false;
10431       return isPowerOf2_32(Scale);
10432     }
10433   }
10434   return true;
10435 }
10436
10437 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10438 /// icmp immediate, that is the target has icmp instructions which can compare
10439 /// a register against the immediate without having to materialize the
10440 /// immediate into a register.
10441 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10442   // Thumb2 and ARM modes can use cmn for negative immediates.
10443   if (!Subtarget->isThumb())
10444     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10445   if (Subtarget->isThumb2())
10446     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10447   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10448   return Imm >= 0 && Imm <= 255;
10449 }
10450
10451 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10452 /// *or sub* immediate, that is the target has add or sub instructions which can
10453 /// add a register with the immediate without having to materialize the
10454 /// immediate into a register.
10455 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10456   // Same encoding for add/sub, just flip the sign.
10457   int64_t AbsImm = llvm::abs64(Imm);
10458   if (!Subtarget->isThumb())
10459     return ARM_AM::getSOImmVal(AbsImm) != -1;
10460   if (Subtarget->isThumb2())
10461     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10462   // Thumb1 only has 8-bit unsigned immediate.
10463   return AbsImm >= 0 && AbsImm <= 255;
10464 }
10465
10466 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10467                                       bool isSEXTLoad, SDValue &Base,
10468                                       SDValue &Offset, bool &isInc,
10469                                       SelectionDAG &DAG) {
10470   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10471     return false;
10472
10473   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10474     // AddressingMode 3
10475     Base = Ptr->getOperand(0);
10476     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10477       int RHSC = (int)RHS->getZExtValue();
10478       if (RHSC < 0 && RHSC > -256) {
10479         assert(Ptr->getOpcode() == ISD::ADD);
10480         isInc = false;
10481         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10482         return true;
10483       }
10484     }
10485     isInc = (Ptr->getOpcode() == ISD::ADD);
10486     Offset = Ptr->getOperand(1);
10487     return true;
10488   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10489     // AddressingMode 2
10490     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10491       int RHSC = (int)RHS->getZExtValue();
10492       if (RHSC < 0 && RHSC > -0x1000) {
10493         assert(Ptr->getOpcode() == ISD::ADD);
10494         isInc = false;
10495         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10496         Base = Ptr->getOperand(0);
10497         return true;
10498       }
10499     }
10500
10501     if (Ptr->getOpcode() == ISD::ADD) {
10502       isInc = true;
10503       ARM_AM::ShiftOpc ShOpcVal=
10504         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10505       if (ShOpcVal != ARM_AM::no_shift) {
10506         Base = Ptr->getOperand(1);
10507         Offset = Ptr->getOperand(0);
10508       } else {
10509         Base = Ptr->getOperand(0);
10510         Offset = Ptr->getOperand(1);
10511       }
10512       return true;
10513     }
10514
10515     isInc = (Ptr->getOpcode() == ISD::ADD);
10516     Base = Ptr->getOperand(0);
10517     Offset = Ptr->getOperand(1);
10518     return true;
10519   }
10520
10521   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10522   return false;
10523 }
10524
10525 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10526                                      bool isSEXTLoad, SDValue &Base,
10527                                      SDValue &Offset, bool &isInc,
10528                                      SelectionDAG &DAG) {
10529   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10530     return false;
10531
10532   Base = Ptr->getOperand(0);
10533   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10534     int RHSC = (int)RHS->getZExtValue();
10535     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10536       assert(Ptr->getOpcode() == ISD::ADD);
10537       isInc = false;
10538       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10539       return true;
10540     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10541       isInc = Ptr->getOpcode() == ISD::ADD;
10542       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10543       return true;
10544     }
10545   }
10546
10547   return false;
10548 }
10549
10550 /// getPreIndexedAddressParts - returns true by value, base pointer and
10551 /// offset pointer and addressing mode by reference if the node's address
10552 /// can be legally represented as pre-indexed load / store address.
10553 bool
10554 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10555                                              SDValue &Offset,
10556                                              ISD::MemIndexedMode &AM,
10557                                              SelectionDAG &DAG) const {
10558   if (Subtarget->isThumb1Only())
10559     return false;
10560
10561   EVT VT;
10562   SDValue Ptr;
10563   bool isSEXTLoad = false;
10564   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10565     Ptr = LD->getBasePtr();
10566     VT  = LD->getMemoryVT();
10567     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10568   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10569     Ptr = ST->getBasePtr();
10570     VT  = ST->getMemoryVT();
10571   } else
10572     return false;
10573
10574   bool isInc;
10575   bool isLegal = false;
10576   if (Subtarget->isThumb2())
10577     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10578                                        Offset, isInc, DAG);
10579   else
10580     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10581                                         Offset, isInc, DAG);
10582   if (!isLegal)
10583     return false;
10584
10585   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10586   return true;
10587 }
10588
10589 /// getPostIndexedAddressParts - returns true by value, base pointer and
10590 /// offset pointer and addressing mode by reference if this node can be
10591 /// combined with a load / store to form a post-indexed load / store.
10592 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10593                                                    SDValue &Base,
10594                                                    SDValue &Offset,
10595                                                    ISD::MemIndexedMode &AM,
10596                                                    SelectionDAG &DAG) const {
10597   if (Subtarget->isThumb1Only())
10598     return false;
10599
10600   EVT VT;
10601   SDValue Ptr;
10602   bool isSEXTLoad = false;
10603   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10604     VT  = LD->getMemoryVT();
10605     Ptr = LD->getBasePtr();
10606     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10607   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10608     VT  = ST->getMemoryVT();
10609     Ptr = ST->getBasePtr();
10610   } else
10611     return false;
10612
10613   bool isInc;
10614   bool isLegal = false;
10615   if (Subtarget->isThumb2())
10616     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10617                                        isInc, DAG);
10618   else
10619     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10620                                         isInc, DAG);
10621   if (!isLegal)
10622     return false;
10623
10624   if (Ptr != Base) {
10625     // Swap base ptr and offset to catch more post-index load / store when
10626     // it's legal. In Thumb2 mode, offset must be an immediate.
10627     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10628         !Subtarget->isThumb2())
10629       std::swap(Base, Offset);
10630
10631     // Post-indexed load / store update the base pointer.
10632     if (Ptr != Base)
10633       return false;
10634   }
10635
10636   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10637   return true;
10638 }
10639
10640 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10641                                                        APInt &KnownZero,
10642                                                        APInt &KnownOne,
10643                                                        const SelectionDAG &DAG,
10644                                                        unsigned Depth) const {
10645   unsigned BitWidth = KnownOne.getBitWidth();
10646   KnownZero = KnownOne = APInt(BitWidth, 0);
10647   switch (Op.getOpcode()) {
10648   default: break;
10649   case ARMISD::ADDC:
10650   case ARMISD::ADDE:
10651   case ARMISD::SUBC:
10652   case ARMISD::SUBE:
10653     // These nodes' second result is a boolean
10654     if (Op.getResNo() == 0)
10655       break;
10656     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10657     break;
10658   case ARMISD::CMOV: {
10659     // Bits are known zero/one if known on the LHS and RHS.
10660     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10661     if (KnownZero == 0 && KnownOne == 0) return;
10662
10663     APInt KnownZeroRHS, KnownOneRHS;
10664     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10665     KnownZero &= KnownZeroRHS;
10666     KnownOne  &= KnownOneRHS;
10667     return;
10668   }
10669   }
10670 }
10671
10672 //===----------------------------------------------------------------------===//
10673 //                           ARM Inline Assembly Support
10674 //===----------------------------------------------------------------------===//
10675
10676 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10677   // Looking for "rev" which is V6+.
10678   if (!Subtarget->hasV6Ops())
10679     return false;
10680
10681   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10682   std::string AsmStr = IA->getAsmString();
10683   SmallVector<StringRef, 4> AsmPieces;
10684   SplitString(AsmStr, AsmPieces, ";\n");
10685
10686   switch (AsmPieces.size()) {
10687   default: return false;
10688   case 1:
10689     AsmStr = AsmPieces[0];
10690     AsmPieces.clear();
10691     SplitString(AsmStr, AsmPieces, " \t,");
10692
10693     // rev $0, $1
10694     if (AsmPieces.size() == 3 &&
10695         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10696         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10697       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10698       if (Ty && Ty->getBitWidth() == 32)
10699         return IntrinsicLowering::LowerToByteSwap(CI);
10700     }
10701     break;
10702   }
10703
10704   return false;
10705 }
10706
10707 /// getConstraintType - Given a constraint letter, return the type of
10708 /// constraint it is for this target.
10709 ARMTargetLowering::ConstraintType
10710 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10711   if (Constraint.size() == 1) {
10712     switch (Constraint[0]) {
10713     default:  break;
10714     case 'l': return C_RegisterClass;
10715     case 'w': return C_RegisterClass;
10716     case 'h': return C_RegisterClass;
10717     case 'x': return C_RegisterClass;
10718     case 't': return C_RegisterClass;
10719     case 'j': return C_Other; // Constant for movw.
10720       // An address with a single base register. Due to the way we
10721       // currently handle addresses it is the same as an 'r' memory constraint.
10722     case 'Q': return C_Memory;
10723     }
10724   } else if (Constraint.size() == 2) {
10725     switch (Constraint[0]) {
10726     default: break;
10727     // All 'U+' constraints are addresses.
10728     case 'U': return C_Memory;
10729     }
10730   }
10731   return TargetLowering::getConstraintType(Constraint);
10732 }
10733
10734 /// Examine constraint type and operand type and determine a weight value.
10735 /// This object must already have been set up with the operand type
10736 /// and the current alternative constraint selected.
10737 TargetLowering::ConstraintWeight
10738 ARMTargetLowering::getSingleConstraintMatchWeight(
10739     AsmOperandInfo &info, const char *constraint) const {
10740   ConstraintWeight weight = CW_Invalid;
10741   Value *CallOperandVal = info.CallOperandVal;
10742     // If we don't have a value, we can't do a match,
10743     // but allow it at the lowest weight.
10744   if (CallOperandVal == NULL)
10745     return CW_Default;
10746   Type *type = CallOperandVal->getType();
10747   // Look at the constraint type.
10748   switch (*constraint) {
10749   default:
10750     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10751     break;
10752   case 'l':
10753     if (type->isIntegerTy()) {
10754       if (Subtarget->isThumb())
10755         weight = CW_SpecificReg;
10756       else
10757         weight = CW_Register;
10758     }
10759     break;
10760   case 'w':
10761     if (type->isFloatingPointTy())
10762       weight = CW_Register;
10763     break;
10764   }
10765   return weight;
10766 }
10767
10768 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10769 RCPair
10770 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10771                                                 MVT VT) const {
10772   if (Constraint.size() == 1) {
10773     // GCC ARM Constraint Letters
10774     switch (Constraint[0]) {
10775     case 'l': // Low regs or general regs.
10776       if (Subtarget->isThumb())
10777         return RCPair(0U, &ARM::tGPRRegClass);
10778       return RCPair(0U, &ARM::GPRRegClass);
10779     case 'h': // High regs or no regs.
10780       if (Subtarget->isThumb())
10781         return RCPair(0U, &ARM::hGPRRegClass);
10782       break;
10783     case 'r':
10784       return RCPair(0U, &ARM::GPRRegClass);
10785     case 'w':
10786       if (VT == MVT::f32)
10787         return RCPair(0U, &ARM::SPRRegClass);
10788       if (VT.getSizeInBits() == 64)
10789         return RCPair(0U, &ARM::DPRRegClass);
10790       if (VT.getSizeInBits() == 128)
10791         return RCPair(0U, &ARM::QPRRegClass);
10792       break;
10793     case 'x':
10794       if (VT == MVT::f32)
10795         return RCPair(0U, &ARM::SPR_8RegClass);
10796       if (VT.getSizeInBits() == 64)
10797         return RCPair(0U, &ARM::DPR_8RegClass);
10798       if (VT.getSizeInBits() == 128)
10799         return RCPair(0U, &ARM::QPR_8RegClass);
10800       break;
10801     case 't':
10802       if (VT == MVT::f32)
10803         return RCPair(0U, &ARM::SPRRegClass);
10804       break;
10805     }
10806   }
10807   if (StringRef("{cc}").equals_lower(Constraint))
10808     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10809
10810   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10811 }
10812
10813 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10814 /// vector.  If it is invalid, don't add anything to Ops.
10815 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10816                                                      std::string &Constraint,
10817                                                      std::vector<SDValue>&Ops,
10818                                                      SelectionDAG &DAG) const {
10819   SDValue Result(0, 0);
10820
10821   // Currently only support length 1 constraints.
10822   if (Constraint.length() != 1) return;
10823
10824   char ConstraintLetter = Constraint[0];
10825   switch (ConstraintLetter) {
10826   default: break;
10827   case 'j':
10828   case 'I': case 'J': case 'K': case 'L':
10829   case 'M': case 'N': case 'O':
10830     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10831     if (!C)
10832       return;
10833
10834     int64_t CVal64 = C->getSExtValue();
10835     int CVal = (int) CVal64;
10836     // None of these constraints allow values larger than 32 bits.  Check
10837     // that the value fits in an int.
10838     if (CVal != CVal64)
10839       return;
10840
10841     switch (ConstraintLetter) {
10842       case 'j':
10843         // Constant suitable for movw, must be between 0 and
10844         // 65535.
10845         if (Subtarget->hasV6T2Ops())
10846           if (CVal >= 0 && CVal <= 65535)
10847             break;
10848         return;
10849       case 'I':
10850         if (Subtarget->isThumb1Only()) {
10851           // This must be a constant between 0 and 255, for ADD
10852           // immediates.
10853           if (CVal >= 0 && CVal <= 255)
10854             break;
10855         } else if (Subtarget->isThumb2()) {
10856           // A constant that can be used as an immediate value in a
10857           // data-processing instruction.
10858           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10859             break;
10860         } else {
10861           // A constant that can be used as an immediate value in a
10862           // data-processing instruction.
10863           if (ARM_AM::getSOImmVal(CVal) != -1)
10864             break;
10865         }
10866         return;
10867
10868       case 'J':
10869         if (Subtarget->isThumb()) {  // FIXME thumb2
10870           // This must be a constant between -255 and -1, for negated ADD
10871           // immediates. This can be used in GCC with an "n" modifier that
10872           // prints the negated value, for use with SUB instructions. It is
10873           // not useful otherwise but is implemented for compatibility.
10874           if (CVal >= -255 && CVal <= -1)
10875             break;
10876         } else {
10877           // This must be a constant between -4095 and 4095. It is not clear
10878           // what this constraint is intended for. Implemented for
10879           // compatibility with GCC.
10880           if (CVal >= -4095 && CVal <= 4095)
10881             break;
10882         }
10883         return;
10884
10885       case 'K':
10886         if (Subtarget->isThumb1Only()) {
10887           // A 32-bit value where only one byte has a nonzero value. Exclude
10888           // zero to match GCC. This constraint is used by GCC internally for
10889           // constants that can be loaded with a move/shift combination.
10890           // It is not useful otherwise but is implemented for compatibility.
10891           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10892             break;
10893         } else if (Subtarget->isThumb2()) {
10894           // A constant whose bitwise inverse can be used as an immediate
10895           // value in a data-processing instruction. This can be used in GCC
10896           // with a "B" modifier that prints the inverted value, for use with
10897           // BIC and MVN instructions. It is not useful otherwise but is
10898           // implemented for compatibility.
10899           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10900             break;
10901         } else {
10902           // A constant whose bitwise inverse can be used as an immediate
10903           // value in a data-processing instruction. This can be used in GCC
10904           // with a "B" modifier that prints the inverted value, for use with
10905           // BIC and MVN instructions. It is not useful otherwise but is
10906           // implemented for compatibility.
10907           if (ARM_AM::getSOImmVal(~CVal) != -1)
10908             break;
10909         }
10910         return;
10911
10912       case 'L':
10913         if (Subtarget->isThumb1Only()) {
10914           // This must be a constant between -7 and 7,
10915           // for 3-operand ADD/SUB immediate instructions.
10916           if (CVal >= -7 && CVal < 7)
10917             break;
10918         } else if (Subtarget->isThumb2()) {
10919           // A constant whose negation can be used as an immediate value in a
10920           // data-processing instruction. This can be used in GCC with an "n"
10921           // modifier that prints the negated value, for use with SUB
10922           // instructions. It is not useful otherwise but is implemented for
10923           // compatibility.
10924           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10925             break;
10926         } else {
10927           // A constant whose negation can be used as an immediate value in a
10928           // data-processing instruction. This can be used in GCC with an "n"
10929           // modifier that prints the negated value, for use with SUB
10930           // instructions. It is not useful otherwise but is implemented for
10931           // compatibility.
10932           if (ARM_AM::getSOImmVal(-CVal) != -1)
10933             break;
10934         }
10935         return;
10936
10937       case 'M':
10938         if (Subtarget->isThumb()) { // FIXME thumb2
10939           // This must be a multiple of 4 between 0 and 1020, for
10940           // ADD sp + immediate.
10941           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10942             break;
10943         } else {
10944           // A power of two or a constant between 0 and 32.  This is used in
10945           // GCC for the shift amount on shifted register operands, but it is
10946           // useful in general for any shift amounts.
10947           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10948             break;
10949         }
10950         return;
10951
10952       case 'N':
10953         if (Subtarget->isThumb()) {  // FIXME thumb2
10954           // This must be a constant between 0 and 31, for shift amounts.
10955           if (CVal >= 0 && CVal <= 31)
10956             break;
10957         }
10958         return;
10959
10960       case 'O':
10961         if (Subtarget->isThumb()) {  // FIXME thumb2
10962           // This must be a multiple of 4 between -508 and 508, for
10963           // ADD/SUB sp = sp + immediate.
10964           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10965             break;
10966         }
10967         return;
10968     }
10969     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10970     break;
10971   }
10972
10973   if (Result.getNode()) {
10974     Ops.push_back(Result);
10975     return;
10976   }
10977   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10978 }
10979
10980 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10981   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10982   unsigned Opcode = Op->getOpcode();
10983   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10984       "Invalid opcode for Div/Rem lowering");
10985   bool isSigned = (Opcode == ISD::SDIVREM);
10986   EVT VT = Op->getValueType(0);
10987   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10988
10989   RTLIB::Libcall LC;
10990   switch (VT.getSimpleVT().SimpleTy) {
10991   default: llvm_unreachable("Unexpected request for libcall!");
10992   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10993   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10994   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10995   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10996   }
10997
10998   SDValue InChain = DAG.getEntryNode();
10999
11000   TargetLowering::ArgListTy Args;
11001   TargetLowering::ArgListEntry Entry;
11002   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
11003     EVT ArgVT = Op->getOperand(i).getValueType();
11004     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11005     Entry.Node = Op->getOperand(i);
11006     Entry.Ty = ArgTy;
11007     Entry.isSExt = isSigned;
11008     Entry.isZExt = !isSigned;
11009     Args.push_back(Entry);
11010   }
11011
11012   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11013                                          getPointerTy());
11014
11015   Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
11016
11017   SDLoc dl(Op);
11018   TargetLowering::
11019   CallLoweringInfo CLI(InChain, RetTy, isSigned, !isSigned, false, true,
11020                     0, getLibcallCallingConv(LC), /*isTailCall=*/false,
11021                     /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
11022                     Callee, Args, DAG, dl);
11023   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11024
11025   return CallInfo.first;
11026 }
11027
11028 bool
11029 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11030   // The ARM target isn't yet aware of offsets.
11031   return false;
11032 }
11033
11034 bool ARM::isBitFieldInvertedMask(unsigned v) {
11035   if (v == 0xffffffff)
11036     return false;
11037
11038   // there can be 1's on either or both "outsides", all the "inside"
11039   // bits must be 0's
11040   unsigned TO = CountTrailingOnes_32(v);
11041   unsigned LO = CountLeadingOnes_32(v);
11042   v = (v >> TO) << TO;
11043   v = (v << LO) >> LO;
11044   return v == 0;
11045 }
11046
11047 /// isFPImmLegal - Returns true if the target can instruction select the
11048 /// specified FP immediate natively. If false, the legalizer will
11049 /// materialize the FP immediate as a load from a constant pool.
11050 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11051   if (!Subtarget->hasVFP3())
11052     return false;
11053   if (VT == MVT::f32)
11054     return ARM_AM::getFP32Imm(Imm) != -1;
11055   if (VT == MVT::f64)
11056     return ARM_AM::getFP64Imm(Imm) != -1;
11057   return false;
11058 }
11059
11060 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11061 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11062 /// specified in the intrinsic calls.
11063 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11064                                            const CallInst &I,
11065                                            unsigned Intrinsic) const {
11066   switch (Intrinsic) {
11067   case Intrinsic::arm_neon_vld1:
11068   case Intrinsic::arm_neon_vld2:
11069   case Intrinsic::arm_neon_vld3:
11070   case Intrinsic::arm_neon_vld4:
11071   case Intrinsic::arm_neon_vld2lane:
11072   case Intrinsic::arm_neon_vld3lane:
11073   case Intrinsic::arm_neon_vld4lane: {
11074     Info.opc = ISD::INTRINSIC_W_CHAIN;
11075     // Conservatively set memVT to the entire set of vectors loaded.
11076     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
11077     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11078     Info.ptrVal = I.getArgOperand(0);
11079     Info.offset = 0;
11080     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11081     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11082     Info.vol = false; // volatile loads with NEON intrinsics not supported
11083     Info.readMem = true;
11084     Info.writeMem = false;
11085     return true;
11086   }
11087   case Intrinsic::arm_neon_vst1:
11088   case Intrinsic::arm_neon_vst2:
11089   case Intrinsic::arm_neon_vst3:
11090   case Intrinsic::arm_neon_vst4:
11091   case Intrinsic::arm_neon_vst2lane:
11092   case Intrinsic::arm_neon_vst3lane:
11093   case Intrinsic::arm_neon_vst4lane: {
11094     Info.opc = ISD::INTRINSIC_VOID;
11095     // Conservatively set memVT to the entire set of vectors stored.
11096     unsigned NumElts = 0;
11097     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11098       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11099       if (!ArgTy->isVectorTy())
11100         break;
11101       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
11102     }
11103     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11104     Info.ptrVal = I.getArgOperand(0);
11105     Info.offset = 0;
11106     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11107     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11108     Info.vol = false; // volatile stores with NEON intrinsics not supported
11109     Info.readMem = false;
11110     Info.writeMem = true;
11111     return true;
11112   }
11113   case Intrinsic::arm_ldrex: {
11114     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11115     Info.opc = ISD::INTRINSIC_W_CHAIN;
11116     Info.memVT = MVT::getVT(PtrTy->getElementType());
11117     Info.ptrVal = I.getArgOperand(0);
11118     Info.offset = 0;
11119     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11120     Info.vol = true;
11121     Info.readMem = true;
11122     Info.writeMem = false;
11123     return true;
11124   }
11125   case Intrinsic::arm_strex: {
11126     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11127     Info.opc = ISD::INTRINSIC_W_CHAIN;
11128     Info.memVT = MVT::getVT(PtrTy->getElementType());
11129     Info.ptrVal = I.getArgOperand(1);
11130     Info.offset = 0;
11131     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11132     Info.vol = true;
11133     Info.readMem = false;
11134     Info.writeMem = true;
11135     return true;
11136   }
11137   case Intrinsic::arm_strexd: {
11138     Info.opc = ISD::INTRINSIC_W_CHAIN;
11139     Info.memVT = MVT::i64;
11140     Info.ptrVal = I.getArgOperand(2);
11141     Info.offset = 0;
11142     Info.align = 8;
11143     Info.vol = true;
11144     Info.readMem = false;
11145     Info.writeMem = true;
11146     return true;
11147   }
11148   case Intrinsic::arm_ldrexd: {
11149     Info.opc = ISD::INTRINSIC_W_CHAIN;
11150     Info.memVT = MVT::i64;
11151     Info.ptrVal = I.getArgOperand(0);
11152     Info.offset = 0;
11153     Info.align = 8;
11154     Info.vol = true;
11155     Info.readMem = true;
11156     Info.writeMem = false;
11157     return true;
11158   }
11159   default:
11160     break;
11161   }
11162
11163   return false;
11164 }