6beb1abd2229a3dba54cabf80fc161dda719e946
[oota-llvm.git] / lib / Target / ARM / ARMISelLowering.cpp
1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "arm-isel"
16 #include "ARMISelLowering.h"
17 #include "ARM.h"
18 #include "ARMCallingConv.h"
19 #include "ARMConstantPoolValue.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "ARMPerfectShuffle.h"
22 #include "ARMSubtarget.h"
23 #include "ARMTargetMachine.h"
24 #include "ARMTargetObjectFile.h"
25 #include "MCTargetDesc/ARMAddressingModes.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/IntrinsicLowering.h"
30 #include "llvm/CodeGen/MachineBasicBlock.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalValue.h"
41 #include "llvm/IR/Instruction.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/IR/Type.h"
45 #include "llvm/MC/MCSectionMachO.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/Target/TargetOptions.h"
51 using namespace llvm;
52
53 STATISTIC(NumTailCalls, "Number of tail calls");
54 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
55 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
56
57 // This option should go away when tail calls fully work.
58 static cl::opt<bool>
59 EnableARMTailCalls("arm-tail-calls", cl::Hidden,
60   cl::desc("Generate tail calls (TEMPORARY OPTION)."),
61   cl::init(false));
62
63 cl::opt<bool>
64 EnableARMLongCalls("arm-long-calls", cl::Hidden,
65   cl::desc("Generate calls via indirect call instructions"),
66   cl::init(false));
67
68 static cl::opt<bool>
69 ARMInterworking("arm-interworking", cl::Hidden,
70   cl::desc("Enable / disable ARM interworking (for debugging only)"),
71   cl::init(true));
72
73 namespace {
74   class ARMCCState : public CCState {
75   public:
76     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
77                const TargetMachine &TM, SmallVector<CCValAssign, 16> &locs,
78                LLVMContext &C, ParmContext PC)
79         : CCState(CC, isVarArg, MF, TM, locs, C) {
80       assert(((PC == Call) || (PC == Prologue)) &&
81              "ARMCCState users must specify whether their context is call"
82              "or prologue generation.");
83       CallOrPrologue = PC;
84     }
85   };
86 }
87
88 // The APCS parameter registers.
89 static const uint16_t GPRArgRegs[] = {
90   ARM::R0, ARM::R1, ARM::R2, ARM::R3
91 };
92
93 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
94                                        MVT PromotedBitwiseVT) {
95   if (VT != PromotedLdStVT) {
96     setOperationAction(ISD::LOAD, VT, Promote);
97     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
98
99     setOperationAction(ISD::STORE, VT, Promote);
100     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
101   }
102
103   MVT ElemTy = VT.getVectorElementType();
104   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
105     setOperationAction(ISD::SETCC, VT, Custom);
106   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
107   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
108   if (ElemTy == MVT::i32) {
109     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
110     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
111     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
112     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
113   } else {
114     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
115     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
116     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
117     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
118   }
119   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
120   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
121   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
122   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
123   setOperationAction(ISD::SELECT,            VT, Expand);
124   setOperationAction(ISD::SELECT_CC,         VT, Expand);
125   setOperationAction(ISD::VSELECT,           VT, Expand);
126   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
127   if (VT.isInteger()) {
128     setOperationAction(ISD::SHL, VT, Custom);
129     setOperationAction(ISD::SRA, VT, Custom);
130     setOperationAction(ISD::SRL, VT, Custom);
131   }
132
133   // Promote all bit-wise operations.
134   if (VT.isInteger() && VT != PromotedBitwiseVT) {
135     setOperationAction(ISD::AND, VT, Promote);
136     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
137     setOperationAction(ISD::OR,  VT, Promote);
138     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
139     setOperationAction(ISD::XOR, VT, Promote);
140     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
141   }
142
143   // Neon does not support vector divide/remainder operations.
144   setOperationAction(ISD::SDIV, VT, Expand);
145   setOperationAction(ISD::UDIV, VT, Expand);
146   setOperationAction(ISD::FDIV, VT, Expand);
147   setOperationAction(ISD::SREM, VT, Expand);
148   setOperationAction(ISD::UREM, VT, Expand);
149   setOperationAction(ISD::FREM, VT, Expand);
150 }
151
152 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
153   addRegisterClass(VT, &ARM::DPRRegClass);
154   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
155 }
156
157 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
158   addRegisterClass(VT, &ARM::QPRRegClass);
159   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
160 }
161
162 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
163   if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
164     return new TargetLoweringObjectFileMachO();
165
166   return new ARMElfTargetObjectFile();
167 }
168
169 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
170     : TargetLowering(TM, createTLOF(TM)) {
171   Subtarget = &TM.getSubtarget<ARMSubtarget>();
172   RegInfo = TM.getRegisterInfo();
173   Itins = TM.getInstrItineraryData();
174
175   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
176
177   if (Subtarget->isTargetDarwin()) {
178     // Uses VFP for Thumb libfuncs if available.
179     if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
180       // Single-precision floating-point arithmetic.
181       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
182       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
183       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
184       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
185
186       // Double-precision floating-point arithmetic.
187       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
188       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
189       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
190       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
191
192       // Single-precision comparisons.
193       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
194       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
195       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
196       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
197       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
198       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
199       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
200       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
201
202       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
203       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
204       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
205       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
206       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
207       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
208       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
209       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
210
211       // Double-precision comparisons.
212       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
213       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
214       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
215       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
216       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
217       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
218       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
219       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
220
221       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
222       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
223       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
224       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
225       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
226       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
227       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
228       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
229
230       // Floating-point to integer conversions.
231       // i64 conversions are done via library routines even when generating VFP
232       // instructions, so use the same ones.
233       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
234       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
235       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
236       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
237
238       // Conversions between floating types.
239       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
240       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
241
242       // Integer to floating-point conversions.
243       // i64 conversions are done via library routines even when generating VFP
244       // instructions, so use the same ones.
245       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
246       // e.g., __floatunsidf vs. __floatunssidfvfp.
247       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
248       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
249       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
250       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
251     }
252   }
253
254   // These libcalls are not available in 32-bit.
255   setLibcallName(RTLIB::SHL_I128, 0);
256   setLibcallName(RTLIB::SRL_I128, 0);
257   setLibcallName(RTLIB::SRA_I128, 0);
258
259   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetDarwin()) {
260     // Double-precision floating-point arithmetic helper functions
261     // RTABI chapter 4.1.2, Table 2
262     setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
263     setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
264     setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
265     setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
266     setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
267     setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
268     setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
269     setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
270
271     // Double-precision floating-point comparison helper functions
272     // RTABI chapter 4.1.2, Table 3
273     setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
274     setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
275     setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
276     setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
277     setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
278     setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
279     setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
280     setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
281     setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
282     setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
283     setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
284     setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
285     setLibcallName(RTLIB::UO_F64,  "__aeabi_dcmpun");
286     setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
287     setLibcallName(RTLIB::O_F64,   "__aeabi_dcmpun");
288     setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
289     setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
290     setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
291     setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
292     setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
293     setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
294     setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
295     setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
296     setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
297
298     // Single-precision floating-point arithmetic helper functions
299     // RTABI chapter 4.1.2, Table 4
300     setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
301     setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
302     setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
303     setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
304     setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
305     setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
306     setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
307     setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
308
309     // Single-precision floating-point comparison helper functions
310     // RTABI chapter 4.1.2, Table 5
311     setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
312     setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
313     setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
314     setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
315     setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
316     setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
317     setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
318     setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
319     setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
320     setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
321     setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
322     setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
323     setLibcallName(RTLIB::UO_F32,  "__aeabi_fcmpun");
324     setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
325     setLibcallName(RTLIB::O_F32,   "__aeabi_fcmpun");
326     setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
327     setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
328     setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
329     setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
330     setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
331     setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
332     setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
333     setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
334     setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
335
336     // Floating-point to integer conversions.
337     // RTABI chapter 4.1.2, Table 6
338     setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
339     setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
340     setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
341     setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
342     setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
343     setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
344     setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
345     setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
346     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
347     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
348     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
349     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
350     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
351     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
352     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
353     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
354
355     // Conversions between floating types.
356     // RTABI chapter 4.1.2, Table 7
357     setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
358     setLibcallName(RTLIB::FPEXT_F32_F64,   "__aeabi_f2d");
359     setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
360     setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
361
362     // Integer to floating-point conversions.
363     // RTABI chapter 4.1.2, Table 8
364     setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
365     setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
366     setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
367     setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
368     setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
369     setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
370     setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
371     setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
372     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
373     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
374     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
375     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
376     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
377     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
378     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
379     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
380
381     // Long long helper functions
382     // RTABI chapter 4.2, Table 9
383     setLibcallName(RTLIB::MUL_I64,  "__aeabi_lmul");
384     setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
385     setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
386     setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
387     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
388     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
389     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
390     setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
391     setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
392     setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
393
394     // Integer division functions
395     // RTABI chapter 4.3.1
396     setLibcallName(RTLIB::SDIV_I8,  "__aeabi_idiv");
397     setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
398     setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
399     setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
400     setLibcallName(RTLIB::UDIV_I8,  "__aeabi_uidiv");
401     setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
402     setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
403     setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
404     setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
405     setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
406     setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
407     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
408     setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
409     setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
410     setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
411     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
412
413     // Memory operations
414     // RTABI chapter 4.3.4
415     setLibcallName(RTLIB::MEMCPY,  "__aeabi_memcpy");
416     setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
417     setLibcallName(RTLIB::MEMSET,  "__aeabi_memset");
418     setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
419     setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
420     setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
421   }
422
423   // Use divmod compiler-rt calls for iOS 5.0 and later.
424   if (Subtarget->getTargetTriple().getOS() == Triple::IOS &&
425       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
426     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
427     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
428   }
429
430   if (Subtarget->isThumb1Only())
431     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
432   else
433     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
434   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
435       !Subtarget->isThumb1Only()) {
436     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
437     if (!Subtarget->isFPOnlySP())
438       addRegisterClass(MVT::f64, &ARM::DPRRegClass);
439
440     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
441   }
442
443   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
444        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
445     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
446          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
447       setTruncStoreAction((MVT::SimpleValueType)VT,
448                           (MVT::SimpleValueType)InnerVT, Expand);
449     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
450     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
451     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
452   }
453
454   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
455
456   if (Subtarget->hasNEON()) {
457     addDRTypeForNEON(MVT::v2f32);
458     addDRTypeForNEON(MVT::v8i8);
459     addDRTypeForNEON(MVT::v4i16);
460     addDRTypeForNEON(MVT::v2i32);
461     addDRTypeForNEON(MVT::v1i64);
462
463     addQRTypeForNEON(MVT::v4f32);
464     addQRTypeForNEON(MVT::v2f64);
465     addQRTypeForNEON(MVT::v16i8);
466     addQRTypeForNEON(MVT::v8i16);
467     addQRTypeForNEON(MVT::v4i32);
468     addQRTypeForNEON(MVT::v2i64);
469
470     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
471     // neither Neon nor VFP support any arithmetic operations on it.
472     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
473     // supported for v4f32.
474     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
475     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
476     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
477     // FIXME: Code duplication: FDIV and FREM are expanded always, see
478     // ARMTargetLowering::addTypeForNEON method for details.
479     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
480     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
481     // FIXME: Create unittest.
482     // In another words, find a way when "copysign" appears in DAG with vector
483     // operands.
484     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
485     // FIXME: Code duplication: SETCC has custom operation action, see
486     // ARMTargetLowering::addTypeForNEON method for details.
487     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
488     // FIXME: Create unittest for FNEG and for FABS.
489     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
490     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
491     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
492     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
493     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
494     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
495     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
496     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
497     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
498     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
499     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
500     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
501     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
502     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
503     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
504     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
505     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
506     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
507
508     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
509     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
510     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
511     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
512     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
513     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
514     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
515     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
516     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
517     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
518     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
519     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
520     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
521     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
522     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
523
524     // Neon does not support some operations on v1i64 and v2i64 types.
525     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
526     // Custom handling for some quad-vector types to detect VMULL.
527     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
528     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
529     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
530     // Custom handling for some vector types to avoid expensive expansions
531     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
532     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
533     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
534     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
535     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
536     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
537     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
538     // a destination type that is wider than the source, and nor does
539     // it have a FP_TO_[SU]INT instruction with a narrower destination than
540     // source.
541     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
542     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
543     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
544     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
545
546     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
547     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
548
549     // NEON does not have single instruction CTPOP for vectors with element
550     // types wider than 8-bits.  However, custom lowering can leverage the
551     // v8i8/v16i8 vcnt instruction.
552     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
553     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
554     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
555     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
556
557     setTargetDAGCombine(ISD::INTRINSIC_VOID);
558     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
559     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
560     setTargetDAGCombine(ISD::SHL);
561     setTargetDAGCombine(ISD::SRL);
562     setTargetDAGCombine(ISD::SRA);
563     setTargetDAGCombine(ISD::SIGN_EXTEND);
564     setTargetDAGCombine(ISD::ZERO_EXTEND);
565     setTargetDAGCombine(ISD::ANY_EXTEND);
566     setTargetDAGCombine(ISD::SELECT_CC);
567     setTargetDAGCombine(ISD::BUILD_VECTOR);
568     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
569     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
570     setTargetDAGCombine(ISD::STORE);
571     setTargetDAGCombine(ISD::FP_TO_SINT);
572     setTargetDAGCombine(ISD::FP_TO_UINT);
573     setTargetDAGCombine(ISD::FDIV);
574
575     // It is legal to extload from v4i8 to v4i16 or v4i32.
576     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
577                   MVT::v4i16, MVT::v2i16,
578                   MVT::v2i32};
579     for (unsigned i = 0; i < 6; ++i) {
580       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
581       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
582       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
583     }
584   }
585
586   // ARM and Thumb2 support UMLAL/SMLAL.
587   if (!Subtarget->isThumb1Only())
588     setTargetDAGCombine(ISD::ADDC);
589
590
591   computeRegisterProperties();
592
593   // ARM does not have f32 extending load.
594   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
595
596   // ARM does not have i1 sign extending load.
597   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
598
599   // ARM supports all 4 flavors of integer indexed load / store.
600   if (!Subtarget->isThumb1Only()) {
601     for (unsigned im = (unsigned)ISD::PRE_INC;
602          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
603       setIndexedLoadAction(im,  MVT::i1,  Legal);
604       setIndexedLoadAction(im,  MVT::i8,  Legal);
605       setIndexedLoadAction(im,  MVT::i16, Legal);
606       setIndexedLoadAction(im,  MVT::i32, Legal);
607       setIndexedStoreAction(im, MVT::i1,  Legal);
608       setIndexedStoreAction(im, MVT::i8,  Legal);
609       setIndexedStoreAction(im, MVT::i16, Legal);
610       setIndexedStoreAction(im, MVT::i32, Legal);
611     }
612   }
613
614   // i64 operation support.
615   setOperationAction(ISD::MUL,     MVT::i64, Expand);
616   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
617   if (Subtarget->isThumb1Only()) {
618     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
619     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
620   }
621   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
622       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
623     setOperationAction(ISD::MULHS, MVT::i32, Expand);
624
625   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
626   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
627   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
628   setOperationAction(ISD::SRL,       MVT::i64, Custom);
629   setOperationAction(ISD::SRA,       MVT::i64, Custom);
630
631   if (!Subtarget->isThumb1Only()) {
632     // FIXME: We should do this for Thumb1 as well.
633     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
634     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
635     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
636     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
637   }
638
639   // ARM does not have ROTL.
640   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
641   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
642   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
643   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
644     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
645
646   // These just redirect to CTTZ and CTLZ on ARM.
647   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
648   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
649
650   // Only ARMv6 has BSWAP.
651   if (!Subtarget->hasV6Ops())
652     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
653
654   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
655       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
656     // These are expanded into libcalls if the cpu doesn't have HW divider.
657     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
658     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
659   }
660   setOperationAction(ISD::SREM,  MVT::i32, Expand);
661   setOperationAction(ISD::UREM,  MVT::i32, Expand);
662   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
663   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
664
665   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
666   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
667   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
668   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
669   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
670
671   setOperationAction(ISD::TRAP, MVT::Other, Legal);
672
673   // Use the default implementation.
674   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
675   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
676   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
677   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
678   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
679   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
680
681   if (!Subtarget->isTargetDarwin()) {
682     // Non-Darwin platforms may return values in these registers via the
683     // personality function.
684     setOperationAction(ISD::EHSELECTION,      MVT::i32,   Expand);
685     setOperationAction(ISD::EXCEPTIONADDR,    MVT::i32,   Expand);
686     setExceptionPointerRegister(ARM::R0);
687     setExceptionSelectorRegister(ARM::R1);
688   }
689
690   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
691   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
692   // the default expansion.
693   // FIXME: This should be checking for v6k, not just v6.
694   if (Subtarget->hasDataBarrier() ||
695       (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
696     // membarrier needs custom lowering; the rest are legal and handled
697     // normally.
698     setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
699     setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
700     // Custom lowering for 64-bit ops
701     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i64, Custom);
702     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i64, Custom);
703     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i64, Custom);
704     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i64, Custom);
705     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i64, Custom);
706     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i64, Custom);
707     setOperationAction(ISD::ATOMIC_LOAD_MIN,  MVT::i64, Custom);
708     setOperationAction(ISD::ATOMIC_LOAD_MAX,  MVT::i64, Custom);
709     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
710     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
711     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
712     // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
713     setInsertFencesForAtomic(true);
714   } else {
715     // Set them all for expansion, which will force libcalls.
716     setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
717     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
718     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
719     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
720     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
721     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
722     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
723     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
724     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
725     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
726     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
727     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
728     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
729     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
730     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
731     // Unordered/Monotonic case.
732     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
733     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
734     // Since the libcalls include locking, fold in the fences
735     setShouldFoldAtomicFences(true);
736   }
737
738   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
739
740   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
741   if (!Subtarget->hasV6Ops()) {
742     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
743     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
744   }
745   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
746
747   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
748       !Subtarget->isThumb1Only()) {
749     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
750     // iff target supports vfp2.
751     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
752     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
753   }
754
755   // We want to custom lower some of our intrinsics.
756   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
757   if (Subtarget->isTargetDarwin()) {
758     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
759     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
760     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
761   }
762
763   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
764   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
765   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
766   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
767   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
768   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
769   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
770   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
771   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
772
773   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
774   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
775   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
776   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
777   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
778
779   // We don't support sin/cos/fmod/copysign/pow
780   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
781   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
782   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
783   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
784   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
785   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
786   setOperationAction(ISD::FREM,      MVT::f64, Expand);
787   setOperationAction(ISD::FREM,      MVT::f32, Expand);
788   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
789       !Subtarget->isThumb1Only()) {
790     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
791     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
792   }
793   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
794   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
795
796   if (!Subtarget->hasVFP4()) {
797     setOperationAction(ISD::FMA, MVT::f64, Expand);
798     setOperationAction(ISD::FMA, MVT::f32, Expand);
799   }
800
801   // Various VFP goodness
802   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
803     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
804     if (Subtarget->hasVFP2()) {
805       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
806       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
807       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
808       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
809     }
810     // Special handling for half-precision FP.
811     if (!Subtarget->hasFP16()) {
812       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
813       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
814     }
815   }
816
817   // We have target-specific dag combine patterns for the following nodes:
818   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
819   setTargetDAGCombine(ISD::ADD);
820   setTargetDAGCombine(ISD::SUB);
821   setTargetDAGCombine(ISD::MUL);
822   setTargetDAGCombine(ISD::AND);
823   setTargetDAGCombine(ISD::OR);
824   setTargetDAGCombine(ISD::XOR);
825
826   if (Subtarget->hasV6Ops())
827     setTargetDAGCombine(ISD::SRL);
828
829   setStackPointerRegisterToSaveRestore(ARM::SP);
830
831   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
832       !Subtarget->hasVFP2())
833     setSchedulingPreference(Sched::RegPressure);
834   else
835     setSchedulingPreference(Sched::Hybrid);
836
837   //// temporary - rewrite interface to use type
838   maxStoresPerMemset = 8;
839   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
840   maxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
841   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
842   maxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
843   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
844
845   // On ARM arguments smaller than 4 bytes are extended, so all arguments
846   // are at least 4 bytes aligned.
847   setMinStackArgumentAlignment(4);
848
849   benefitFromCodePlacementOpt = true;
850
851   // Prefer likely predicted branches to selects on out-of-order cores.
852   predictableSelectIsExpensive = Subtarget->isLikeA9();
853
854   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
855 }
856
857 // FIXME: It might make sense to define the representative register class as the
858 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
859 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
860 // SPR's representative would be DPR_VFP2. This should work well if register
861 // pressure tracking were modified such that a register use would increment the
862 // pressure of the register class's representative and all of it's super
863 // classes' representatives transitively. We have not implemented this because
864 // of the difficulty prior to coalescing of modeling operand register classes
865 // due to the common occurrence of cross class copies and subregister insertions
866 // and extractions.
867 std::pair<const TargetRegisterClass*, uint8_t>
868 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
869   const TargetRegisterClass *RRC = 0;
870   uint8_t Cost = 1;
871   switch (VT.SimpleTy) {
872   default:
873     return TargetLowering::findRepresentativeClass(VT);
874   // Use DPR as representative register class for all floating point
875   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
876   // the cost is 1 for both f32 and f64.
877   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
878   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
879     RRC = &ARM::DPRRegClass;
880     // When NEON is used for SP, only half of the register file is available
881     // because operations that define both SP and DP results will be constrained
882     // to the VFP2 class (D0-D15). We currently model this constraint prior to
883     // coalescing by double-counting the SP regs. See the FIXME above.
884     if (Subtarget->useNEONForSinglePrecisionFP())
885       Cost = 2;
886     break;
887   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
888   case MVT::v4f32: case MVT::v2f64:
889     RRC = &ARM::DPRRegClass;
890     Cost = 2;
891     break;
892   case MVT::v4i64:
893     RRC = &ARM::DPRRegClass;
894     Cost = 4;
895     break;
896   case MVT::v8i64:
897     RRC = &ARM::DPRRegClass;
898     Cost = 8;
899     break;
900   }
901   return std::make_pair(RRC, Cost);
902 }
903
904 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
905   switch (Opcode) {
906   default: return 0;
907   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
908   case ARMISD::WrapperDYN:    return "ARMISD::WrapperDYN";
909   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
910   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
911   case ARMISD::CALL:          return "ARMISD::CALL";
912   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
913   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
914   case ARMISD::tCALL:         return "ARMISD::tCALL";
915   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
916   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
917   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
918   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
919   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
920   case ARMISD::CMP:           return "ARMISD::CMP";
921   case ARMISD::CMN:           return "ARMISD::CMN";
922   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
923   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
924   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
925   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
926   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
927
928   case ARMISD::CMOV:          return "ARMISD::CMOV";
929
930   case ARMISD::RBIT:          return "ARMISD::RBIT";
931
932   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
933   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
934   case ARMISD::SITOF:         return "ARMISD::SITOF";
935   case ARMISD::UITOF:         return "ARMISD::UITOF";
936
937   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
938   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
939   case ARMISD::RRX:           return "ARMISD::RRX";
940
941   case ARMISD::ADDC:          return "ARMISD::ADDC";
942   case ARMISD::ADDE:          return "ARMISD::ADDE";
943   case ARMISD::SUBC:          return "ARMISD::SUBC";
944   case ARMISD::SUBE:          return "ARMISD::SUBE";
945
946   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
947   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
948
949   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
950   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
951
952   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
953
954   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
955
956   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
957
958   case ARMISD::MEMBARRIER:    return "ARMISD::MEMBARRIER";
959   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
960
961   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
962
963   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
964   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
965   case ARMISD::VCGE:          return "ARMISD::VCGE";
966   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
967   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
968   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
969   case ARMISD::VCGT:          return "ARMISD::VCGT";
970   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
971   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
972   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
973   case ARMISD::VTST:          return "ARMISD::VTST";
974
975   case ARMISD::VSHL:          return "ARMISD::VSHL";
976   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
977   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
978   case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
979   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
980   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
981   case ARMISD::VSHRN:         return "ARMISD::VSHRN";
982   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
983   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
984   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
985   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
986   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
987   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
988   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
989   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
990   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
991   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
992   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
993   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
994   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
995   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
996   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
997   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
998   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
999   case ARMISD::VDUP:          return "ARMISD::VDUP";
1000   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1001   case ARMISD::VEXT:          return "ARMISD::VEXT";
1002   case ARMISD::VREV64:        return "ARMISD::VREV64";
1003   case ARMISD::VREV32:        return "ARMISD::VREV32";
1004   case ARMISD::VREV16:        return "ARMISD::VREV16";
1005   case ARMISD::VZIP:          return "ARMISD::VZIP";
1006   case ARMISD::VUZP:          return "ARMISD::VUZP";
1007   case ARMISD::VTRN:          return "ARMISD::VTRN";
1008   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1009   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1010   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1011   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1012   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1013   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1014   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1015   case ARMISD::FMAX:          return "ARMISD::FMAX";
1016   case ARMISD::FMIN:          return "ARMISD::FMIN";
1017   case ARMISD::BFI:           return "ARMISD::BFI";
1018   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1019   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1020   case ARMISD::VBSL:          return "ARMISD::VBSL";
1021   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1022   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1023   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1024   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1025   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1026   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1027   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1028   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1029   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1030   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1031   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1032   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1033   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1034   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1035   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1036   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1037   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1038   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1039   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1040   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1041   }
1042 }
1043
1044 EVT ARMTargetLowering::getSetCCResultType(EVT VT) const {
1045   if (!VT.isVector()) return getPointerTy();
1046   return VT.changeVectorElementTypeToInteger();
1047 }
1048
1049 /// getRegClassFor - Return the register class that should be used for the
1050 /// specified value type.
1051 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1052   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1053   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1054   // load / store 4 to 8 consecutive D registers.
1055   if (Subtarget->hasNEON()) {
1056     if (VT == MVT::v4i64)
1057       return &ARM::QQPRRegClass;
1058     if (VT == MVT::v8i64)
1059       return &ARM::QQQQPRRegClass;
1060   }
1061   return TargetLowering::getRegClassFor(VT);
1062 }
1063
1064 // Create a fast isel object.
1065 FastISel *
1066 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1067                                   const TargetLibraryInfo *libInfo) const {
1068   return ARM::createFastISel(funcInfo, libInfo);
1069 }
1070
1071 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1072 /// be used for loads / stores from the global.
1073 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1074   return (Subtarget->isThumb1Only() ? 127 : 4095);
1075 }
1076
1077 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1078   unsigned NumVals = N->getNumValues();
1079   if (!NumVals)
1080     return Sched::RegPressure;
1081
1082   for (unsigned i = 0; i != NumVals; ++i) {
1083     EVT VT = N->getValueType(i);
1084     if (VT == MVT::Glue || VT == MVT::Other)
1085       continue;
1086     if (VT.isFloatingPoint() || VT.isVector())
1087       return Sched::ILP;
1088   }
1089
1090   if (!N->isMachineOpcode())
1091     return Sched::RegPressure;
1092
1093   // Load are scheduled for latency even if there instruction itinerary
1094   // is not available.
1095   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1096   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1097
1098   if (MCID.getNumDefs() == 0)
1099     return Sched::RegPressure;
1100   if (!Itins->isEmpty() &&
1101       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1102     return Sched::ILP;
1103
1104   return Sched::RegPressure;
1105 }
1106
1107 //===----------------------------------------------------------------------===//
1108 // Lowering Code
1109 //===----------------------------------------------------------------------===//
1110
1111 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1112 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1113   switch (CC) {
1114   default: llvm_unreachable("Unknown condition code!");
1115   case ISD::SETNE:  return ARMCC::NE;
1116   case ISD::SETEQ:  return ARMCC::EQ;
1117   case ISD::SETGT:  return ARMCC::GT;
1118   case ISD::SETGE:  return ARMCC::GE;
1119   case ISD::SETLT:  return ARMCC::LT;
1120   case ISD::SETLE:  return ARMCC::LE;
1121   case ISD::SETUGT: return ARMCC::HI;
1122   case ISD::SETUGE: return ARMCC::HS;
1123   case ISD::SETULT: return ARMCC::LO;
1124   case ISD::SETULE: return ARMCC::LS;
1125   }
1126 }
1127
1128 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1129 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1130                         ARMCC::CondCodes &CondCode2) {
1131   CondCode2 = ARMCC::AL;
1132   switch (CC) {
1133   default: llvm_unreachable("Unknown FP condition!");
1134   case ISD::SETEQ:
1135   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1136   case ISD::SETGT:
1137   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1138   case ISD::SETGE:
1139   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1140   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1141   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1142   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1143   case ISD::SETO:   CondCode = ARMCC::VC; break;
1144   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1145   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1146   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1147   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1148   case ISD::SETLT:
1149   case ISD::SETULT: CondCode = ARMCC::LT; break;
1150   case ISD::SETLE:
1151   case ISD::SETULE: CondCode = ARMCC::LE; break;
1152   case ISD::SETNE:
1153   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1154   }
1155 }
1156
1157 //===----------------------------------------------------------------------===//
1158 //                      Calling Convention Implementation
1159 //===----------------------------------------------------------------------===//
1160
1161 #include "ARMGenCallingConv.inc"
1162
1163 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1164 /// given CallingConvention value.
1165 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1166                                                  bool Return,
1167                                                  bool isVarArg) const {
1168   switch (CC) {
1169   default:
1170     llvm_unreachable("Unsupported calling convention");
1171   case CallingConv::Fast:
1172     if (Subtarget->hasVFP2() && !isVarArg) {
1173       if (!Subtarget->isAAPCS_ABI())
1174         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1175       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1176       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1177     }
1178     // Fallthrough
1179   case CallingConv::C: {
1180     // Use target triple & subtarget features to do actual dispatch.
1181     if (!Subtarget->isAAPCS_ABI())
1182       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1183     else if (Subtarget->hasVFP2() &&
1184              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1185              !isVarArg)
1186       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1187     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1188   }
1189   case CallingConv::ARM_AAPCS_VFP:
1190     if (!isVarArg)
1191       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1192     // Fallthrough
1193   case CallingConv::ARM_AAPCS:
1194     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1195   case CallingConv::ARM_APCS:
1196     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1197   case CallingConv::GHC:
1198     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1199   }
1200 }
1201
1202 /// LowerCallResult - Lower the result values of a call into the
1203 /// appropriate copies out of appropriate physical registers.
1204 SDValue
1205 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1206                                    CallingConv::ID CallConv, bool isVarArg,
1207                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1208                                    DebugLoc dl, SelectionDAG &DAG,
1209                                    SmallVectorImpl<SDValue> &InVals) const {
1210
1211   // Assign locations to each value returned by this call.
1212   SmallVector<CCValAssign, 16> RVLocs;
1213   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1214                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1215   CCInfo.AnalyzeCallResult(Ins,
1216                            CCAssignFnForNode(CallConv, /* Return*/ true,
1217                                              isVarArg));
1218
1219   // Copy all of the result registers out of their specified physreg.
1220   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1221     CCValAssign VA = RVLocs[i];
1222
1223     SDValue Val;
1224     if (VA.needsCustom()) {
1225       // Handle f64 or half of a v2f64.
1226       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1227                                       InFlag);
1228       Chain = Lo.getValue(1);
1229       InFlag = Lo.getValue(2);
1230       VA = RVLocs[++i]; // skip ahead to next loc
1231       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1232                                       InFlag);
1233       Chain = Hi.getValue(1);
1234       InFlag = Hi.getValue(2);
1235       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1236
1237       if (VA.getLocVT() == MVT::v2f64) {
1238         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1239         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1240                           DAG.getConstant(0, MVT::i32));
1241
1242         VA = RVLocs[++i]; // skip ahead to next loc
1243         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1244         Chain = Lo.getValue(1);
1245         InFlag = Lo.getValue(2);
1246         VA = RVLocs[++i]; // skip ahead to next loc
1247         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1248         Chain = Hi.getValue(1);
1249         InFlag = Hi.getValue(2);
1250         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1251         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1252                           DAG.getConstant(1, MVT::i32));
1253       }
1254     } else {
1255       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1256                                InFlag);
1257       Chain = Val.getValue(1);
1258       InFlag = Val.getValue(2);
1259     }
1260
1261     switch (VA.getLocInfo()) {
1262     default: llvm_unreachable("Unknown loc info!");
1263     case CCValAssign::Full: break;
1264     case CCValAssign::BCvt:
1265       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1266       break;
1267     }
1268
1269     InVals.push_back(Val);
1270   }
1271
1272   return Chain;
1273 }
1274
1275 /// LowerMemOpCallTo - Store the argument to the stack.
1276 SDValue
1277 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1278                                     SDValue StackPtr, SDValue Arg,
1279                                     DebugLoc dl, SelectionDAG &DAG,
1280                                     const CCValAssign &VA,
1281                                     ISD::ArgFlagsTy Flags) const {
1282   unsigned LocMemOffset = VA.getLocMemOffset();
1283   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1284   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1285   return DAG.getStore(Chain, dl, Arg, PtrOff,
1286                       MachinePointerInfo::getStack(LocMemOffset),
1287                       false, false, 0);
1288 }
1289
1290 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
1291                                          SDValue Chain, SDValue &Arg,
1292                                          RegsToPassVector &RegsToPass,
1293                                          CCValAssign &VA, CCValAssign &NextVA,
1294                                          SDValue &StackPtr,
1295                                          SmallVector<SDValue, 8> &MemOpChains,
1296                                          ISD::ArgFlagsTy Flags) const {
1297
1298   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1299                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1300   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1301
1302   if (NextVA.isRegLoc())
1303     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1304   else {
1305     assert(NextVA.isMemLoc());
1306     if (StackPtr.getNode() == 0)
1307       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1308
1309     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1310                                            dl, DAG, NextVA,
1311                                            Flags));
1312   }
1313 }
1314
1315 /// LowerCall - Lowering a call into a callseq_start <-
1316 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1317 /// nodes.
1318 SDValue
1319 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1320                              SmallVectorImpl<SDValue> &InVals) const {
1321   SelectionDAG &DAG                     = CLI.DAG;
1322   DebugLoc &dl                          = CLI.DL;
1323   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1324   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
1325   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
1326   SDValue Chain                         = CLI.Chain;
1327   SDValue Callee                        = CLI.Callee;
1328   bool &isTailCall                      = CLI.IsTailCall;
1329   CallingConv::ID CallConv              = CLI.CallConv;
1330   bool doesNotRet                       = CLI.DoesNotReturn;
1331   bool isVarArg                         = CLI.IsVarArg;
1332
1333   MachineFunction &MF = DAG.getMachineFunction();
1334   bool IsStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1335   bool IsSibCall = false;
1336   // Disable tail calls if they're not supported.
1337   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1338     isTailCall = false;
1339   if (isTailCall) {
1340     // Check if it's really possible to do a tail call.
1341     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1342                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1343                                                    Outs, OutVals, Ins, DAG);
1344     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1345     // detected sibcalls.
1346     if (isTailCall) {
1347       ++NumTailCalls;
1348       IsSibCall = true;
1349     }
1350   }
1351
1352   // Analyze operands of the call, assigning locations to each operand.
1353   SmallVector<CCValAssign, 16> ArgLocs;
1354   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1355                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1356   CCInfo.AnalyzeCallOperands(Outs,
1357                              CCAssignFnForNode(CallConv, /* Return*/ false,
1358                                                isVarArg));
1359
1360   // Get a count of how many bytes are to be pushed on the stack.
1361   unsigned NumBytes = CCInfo.getNextStackOffset();
1362
1363   // For tail calls, memory operands are available in our caller's stack.
1364   if (IsSibCall)
1365     NumBytes = 0;
1366
1367   // Adjust the stack pointer for the new arguments...
1368   // These operations are automatically eliminated by the prolog/epilog pass
1369   if (!IsSibCall)
1370     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1371
1372   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1373
1374   RegsToPassVector RegsToPass;
1375   SmallVector<SDValue, 8> MemOpChains;
1376
1377   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1378   // of tail call optimization, arguments are handled later.
1379   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1380        i != e;
1381        ++i, ++realArgIdx) {
1382     CCValAssign &VA = ArgLocs[i];
1383     SDValue Arg = OutVals[realArgIdx];
1384     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1385     bool isByVal = Flags.isByVal();
1386
1387     // Promote the value if needed.
1388     switch (VA.getLocInfo()) {
1389     default: llvm_unreachable("Unknown loc info!");
1390     case CCValAssign::Full: break;
1391     case CCValAssign::SExt:
1392       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1393       break;
1394     case CCValAssign::ZExt:
1395       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1396       break;
1397     case CCValAssign::AExt:
1398       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1399       break;
1400     case CCValAssign::BCvt:
1401       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1402       break;
1403     }
1404
1405     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1406     if (VA.needsCustom()) {
1407       if (VA.getLocVT() == MVT::v2f64) {
1408         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1409                                   DAG.getConstant(0, MVT::i32));
1410         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1411                                   DAG.getConstant(1, MVT::i32));
1412
1413         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1414                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1415
1416         VA = ArgLocs[++i]; // skip ahead to next loc
1417         if (VA.isRegLoc()) {
1418           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1419                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1420         } else {
1421           assert(VA.isMemLoc());
1422
1423           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1424                                                  dl, DAG, VA, Flags));
1425         }
1426       } else {
1427         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1428                          StackPtr, MemOpChains, Flags);
1429       }
1430     } else if (VA.isRegLoc()) {
1431       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1432     } else if (isByVal) {
1433       assert(VA.isMemLoc());
1434       unsigned offset = 0;
1435
1436       // True if this byval aggregate will be split between registers
1437       // and memory.
1438       if (CCInfo.isFirstByValRegValid()) {
1439         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1440         unsigned int i, j;
1441         for (i = 0, j = CCInfo.getFirstByValReg(); j < ARM::R4; i++, j++) {
1442           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1443           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1444           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1445                                      MachinePointerInfo(),
1446                                      false, false, false, 0);
1447           MemOpChains.push_back(Load.getValue(1));
1448           RegsToPass.push_back(std::make_pair(j, Load));
1449         }
1450         offset = ARM::R4 - CCInfo.getFirstByValReg();
1451         CCInfo.clearFirstByValReg();
1452       }
1453
1454       if (Flags.getByValSize() - 4*offset > 0) {
1455         unsigned LocMemOffset = VA.getLocMemOffset();
1456         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1457         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1458                                   StkPtrOff);
1459         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1460         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1461         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1462                                            MVT::i32);
1463         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1464
1465         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1466         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1467         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1468                                           Ops, array_lengthof(Ops)));
1469       }
1470     } else if (!IsSibCall) {
1471       assert(VA.isMemLoc());
1472
1473       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1474                                              dl, DAG, VA, Flags));
1475     }
1476   }
1477
1478   if (!MemOpChains.empty())
1479     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1480                         &MemOpChains[0], MemOpChains.size());
1481
1482   // Build a sequence of copy-to-reg nodes chained together with token chain
1483   // and flag operands which copy the outgoing args into the appropriate regs.
1484   SDValue InFlag;
1485   // Tail call byval lowering might overwrite argument registers so in case of
1486   // tail call optimization the copies to registers are lowered later.
1487   if (!isTailCall)
1488     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1489       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1490                                RegsToPass[i].second, InFlag);
1491       InFlag = Chain.getValue(1);
1492     }
1493
1494   // For tail calls lower the arguments to the 'real' stack slot.
1495   if (isTailCall) {
1496     // Force all the incoming stack arguments to be loaded from the stack
1497     // before any new outgoing arguments are stored to the stack, because the
1498     // outgoing stack slots may alias the incoming argument stack slots, and
1499     // the alias isn't otherwise explicit. This is slightly more conservative
1500     // than necessary, because it means that each store effectively depends
1501     // on every argument instead of just those arguments it would clobber.
1502
1503     // Do not flag preceding copytoreg stuff together with the following stuff.
1504     InFlag = SDValue();
1505     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1506       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1507                                RegsToPass[i].second, InFlag);
1508       InFlag = Chain.getValue(1);
1509     }
1510     InFlag =SDValue();
1511   }
1512
1513   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1514   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1515   // node so that legalize doesn't hack it.
1516   bool isDirect = false;
1517   bool isARMFunc = false;
1518   bool isLocalARMFunc = false;
1519   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1520
1521   if (EnableARMLongCalls) {
1522     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1523             && "long-calls with non-static relocation model!");
1524     // Handle a global address or an external symbol. If it's not one of
1525     // those, the target's already in a register, so we don't need to do
1526     // anything extra.
1527     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1528       const GlobalValue *GV = G->getGlobal();
1529       // Create a constant pool entry for the callee address
1530       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1531       ARMConstantPoolValue *CPV =
1532         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1533
1534       // Get the address of the callee into a register
1535       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1536       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1537       Callee = DAG.getLoad(getPointerTy(), dl,
1538                            DAG.getEntryNode(), CPAddr,
1539                            MachinePointerInfo::getConstantPool(),
1540                            false, false, false, 0);
1541     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1542       const char *Sym = S->getSymbol();
1543
1544       // Create a constant pool entry for the callee address
1545       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1546       ARMConstantPoolValue *CPV =
1547         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1548                                       ARMPCLabelIndex, 0);
1549       // Get the address of the callee into a register
1550       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1551       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1552       Callee = DAG.getLoad(getPointerTy(), dl,
1553                            DAG.getEntryNode(), CPAddr,
1554                            MachinePointerInfo::getConstantPool(),
1555                            false, false, false, 0);
1556     }
1557   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1558     const GlobalValue *GV = G->getGlobal();
1559     isDirect = true;
1560     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1561     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1562                    getTargetMachine().getRelocationModel() != Reloc::Static;
1563     isARMFunc = !Subtarget->isThumb() || isStub;
1564     // ARM call to a local ARM function is predicable.
1565     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1566     // tBX takes a register source operand.
1567     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1568       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1569       ARMConstantPoolValue *CPV =
1570         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1571       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1572       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1573       Callee = DAG.getLoad(getPointerTy(), dl,
1574                            DAG.getEntryNode(), CPAddr,
1575                            MachinePointerInfo::getConstantPool(),
1576                            false, false, false, 0);
1577       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1578       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1579                            getPointerTy(), Callee, PICLabel);
1580     } else {
1581       // On ELF targets for PIC code, direct calls should go through the PLT
1582       unsigned OpFlags = 0;
1583       if (Subtarget->isTargetELF() &&
1584                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1585         OpFlags = ARMII::MO_PLT;
1586       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1587     }
1588   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1589     isDirect = true;
1590     bool isStub = Subtarget->isTargetDarwin() &&
1591                   getTargetMachine().getRelocationModel() != Reloc::Static;
1592     isARMFunc = !Subtarget->isThumb() || isStub;
1593     // tBX takes a register source operand.
1594     const char *Sym = S->getSymbol();
1595     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1596       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1597       ARMConstantPoolValue *CPV =
1598         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1599                                       ARMPCLabelIndex, 4);
1600       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1601       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1602       Callee = DAG.getLoad(getPointerTy(), dl,
1603                            DAG.getEntryNode(), CPAddr,
1604                            MachinePointerInfo::getConstantPool(),
1605                            false, false, false, 0);
1606       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1607       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1608                            getPointerTy(), Callee, PICLabel);
1609     } else {
1610       unsigned OpFlags = 0;
1611       // On ELF targets for PIC code, direct calls should go through the PLT
1612       if (Subtarget->isTargetELF() &&
1613                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1614         OpFlags = ARMII::MO_PLT;
1615       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1616     }
1617   }
1618
1619   // FIXME: handle tail calls differently.
1620   unsigned CallOpc;
1621   bool HasMinSizeAttr = MF.getFunction()->getAttributes().
1622     hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
1623   if (Subtarget->isThumb()) {
1624     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1625       CallOpc = ARMISD::CALL_NOLINK;
1626     else
1627       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1628   } else {
1629     if (!isDirect && !Subtarget->hasV5TOps())
1630       CallOpc = ARMISD::CALL_NOLINK;
1631     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1632                // Emit regular call when code size is the priority
1633                !HasMinSizeAttr)
1634       // "mov lr, pc; b _foo" to avoid confusing the RSP
1635       CallOpc = ARMISD::CALL_NOLINK;
1636     else
1637       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1638   }
1639
1640   std::vector<SDValue> Ops;
1641   Ops.push_back(Chain);
1642   Ops.push_back(Callee);
1643
1644   // Add argument registers to the end of the list so that they are known live
1645   // into the call.
1646   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1647     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1648                                   RegsToPass[i].second.getValueType()));
1649
1650   // Add a register mask operand representing the call-preserved registers.
1651   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1652   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
1653   assert(Mask && "Missing call preserved mask for calling convention");
1654   Ops.push_back(DAG.getRegisterMask(Mask));
1655
1656   if (InFlag.getNode())
1657     Ops.push_back(InFlag);
1658
1659   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1660   if (isTailCall)
1661     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1662
1663   // Returns a chain and a flag for retval copy to use.
1664   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1665   InFlag = Chain.getValue(1);
1666
1667   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1668                              DAG.getIntPtrConstant(0, true), InFlag);
1669   if (!Ins.empty())
1670     InFlag = Chain.getValue(1);
1671
1672   // Handle result values, copying them out of physregs into vregs that we
1673   // return.
1674   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1675                          dl, DAG, InVals);
1676 }
1677
1678 /// HandleByVal - Every parameter *after* a byval parameter is passed
1679 /// on the stack.  Remember the next parameter register to allocate,
1680 /// and then confiscate the rest of the parameter registers to insure
1681 /// this.
1682 void
1683 ARMTargetLowering::HandleByVal(
1684     CCState *State, unsigned &size, unsigned Align) const {
1685   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1686   assert((State->getCallOrPrologue() == Prologue ||
1687           State->getCallOrPrologue() == Call) &&
1688          "unhandled ParmContext");
1689   if ((!State->isFirstByValRegValid()) &&
1690       (ARM::R0 <= reg) && (reg <= ARM::R3)) {
1691     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1692       unsigned AlignInRegs = Align / 4;
1693       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1694       for (unsigned i = 0; i < Waste; ++i)
1695         reg = State->AllocateReg(GPRArgRegs, 4);
1696     }
1697     if (reg != 0) {
1698       State->setFirstByValReg(reg);
1699       // At a call site, a byval parameter that is split between
1700       // registers and memory needs its size truncated here.  In a
1701       // function prologue, such byval parameters are reassembled in
1702       // memory, and are not truncated.
1703       if (State->getCallOrPrologue() == Call) {
1704         unsigned excess = 4 * (ARM::R4 - reg);
1705         assert(size >= excess && "expected larger existing stack allocation");
1706         size -= excess;
1707       }
1708     }
1709   }
1710   // Confiscate any remaining parameter registers to preclude their
1711   // assignment to subsequent parameters.
1712   while (State->AllocateReg(GPRArgRegs, 4))
1713     ;
1714 }
1715
1716 /// MatchingStackOffset - Return true if the given stack call argument is
1717 /// already available in the same position (relatively) of the caller's
1718 /// incoming argument stack.
1719 static
1720 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1721                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1722                          const TargetInstrInfo *TII) {
1723   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1724   int FI = INT_MAX;
1725   if (Arg.getOpcode() == ISD::CopyFromReg) {
1726     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1727     if (!TargetRegisterInfo::isVirtualRegister(VR))
1728       return false;
1729     MachineInstr *Def = MRI->getVRegDef(VR);
1730     if (!Def)
1731       return false;
1732     if (!Flags.isByVal()) {
1733       if (!TII->isLoadFromStackSlot(Def, FI))
1734         return false;
1735     } else {
1736       return false;
1737     }
1738   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1739     if (Flags.isByVal())
1740       // ByVal argument is passed in as a pointer but it's now being
1741       // dereferenced. e.g.
1742       // define @foo(%struct.X* %A) {
1743       //   tail call @bar(%struct.X* byval %A)
1744       // }
1745       return false;
1746     SDValue Ptr = Ld->getBasePtr();
1747     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1748     if (!FINode)
1749       return false;
1750     FI = FINode->getIndex();
1751   } else
1752     return false;
1753
1754   assert(FI != INT_MAX);
1755   if (!MFI->isFixedObjectIndex(FI))
1756     return false;
1757   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1758 }
1759
1760 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1761 /// for tail call optimization. Targets which want to do tail call
1762 /// optimization should implement this function.
1763 bool
1764 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1765                                                      CallingConv::ID CalleeCC,
1766                                                      bool isVarArg,
1767                                                      bool isCalleeStructRet,
1768                                                      bool isCallerStructRet,
1769                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1770                                     const SmallVectorImpl<SDValue> &OutVals,
1771                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1772                                                      SelectionDAG& DAG) const {
1773   const Function *CallerF = DAG.getMachineFunction().getFunction();
1774   CallingConv::ID CallerCC = CallerF->getCallingConv();
1775   bool CCMatch = CallerCC == CalleeCC;
1776
1777   // Look for obvious safe cases to perform tail call optimization that do not
1778   // require ABI changes. This is what gcc calls sibcall.
1779
1780   // Do not sibcall optimize vararg calls unless the call site is not passing
1781   // any arguments.
1782   if (isVarArg && !Outs.empty())
1783     return false;
1784
1785   // Also avoid sibcall optimization if either caller or callee uses struct
1786   // return semantics.
1787   if (isCalleeStructRet || isCallerStructRet)
1788     return false;
1789
1790   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1791   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1792   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1793   // support in the assembler and linker to be used. This would need to be
1794   // fixed to fully support tail calls in Thumb1.
1795   //
1796   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1797   // LR.  This means if we need to reload LR, it takes an extra instructions,
1798   // which outweighs the value of the tail call; but here we don't know yet
1799   // whether LR is going to be used.  Probably the right approach is to
1800   // generate the tail call here and turn it back into CALL/RET in
1801   // emitEpilogue if LR is used.
1802
1803   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1804   // but we need to make sure there are enough registers; the only valid
1805   // registers are the 4 used for parameters.  We don't currently do this
1806   // case.
1807   if (Subtarget->isThumb1Only())
1808     return false;
1809
1810   // If the calling conventions do not match, then we'd better make sure the
1811   // results are returned in the same way as what the caller expects.
1812   if (!CCMatch) {
1813     SmallVector<CCValAssign, 16> RVLocs1;
1814     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1815                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1816     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1817
1818     SmallVector<CCValAssign, 16> RVLocs2;
1819     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1820                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1821     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1822
1823     if (RVLocs1.size() != RVLocs2.size())
1824       return false;
1825     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1826       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1827         return false;
1828       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1829         return false;
1830       if (RVLocs1[i].isRegLoc()) {
1831         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1832           return false;
1833       } else {
1834         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1835           return false;
1836       }
1837     }
1838   }
1839
1840   // If Caller's vararg or byval argument has been split between registers and
1841   // stack, do not perform tail call, since part of the argument is in caller's
1842   // local frame.
1843   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1844                                       getInfo<ARMFunctionInfo>();
1845   if (AFI_Caller->getVarArgsRegSaveSize())
1846     return false;
1847
1848   // If the callee takes no arguments then go on to check the results of the
1849   // call.
1850   if (!Outs.empty()) {
1851     // Check if stack adjustment is needed. For now, do not do this if any
1852     // argument is passed on the stack.
1853     SmallVector<CCValAssign, 16> ArgLocs;
1854     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1855                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1856     CCInfo.AnalyzeCallOperands(Outs,
1857                                CCAssignFnForNode(CalleeCC, false, isVarArg));
1858     if (CCInfo.getNextStackOffset()) {
1859       MachineFunction &MF = DAG.getMachineFunction();
1860
1861       // Check if the arguments are already laid out in the right way as
1862       // the caller's fixed stack objects.
1863       MachineFrameInfo *MFI = MF.getFrameInfo();
1864       const MachineRegisterInfo *MRI = &MF.getRegInfo();
1865       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1866       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1867            i != e;
1868            ++i, ++realArgIdx) {
1869         CCValAssign &VA = ArgLocs[i];
1870         EVT RegVT = VA.getLocVT();
1871         SDValue Arg = OutVals[realArgIdx];
1872         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1873         if (VA.getLocInfo() == CCValAssign::Indirect)
1874           return false;
1875         if (VA.needsCustom()) {
1876           // f64 and vector types are split into multiple registers or
1877           // register/stack-slot combinations.  The types will not match
1878           // the registers; give up on memory f64 refs until we figure
1879           // out what to do about this.
1880           if (!VA.isRegLoc())
1881             return false;
1882           if (!ArgLocs[++i].isRegLoc())
1883             return false;
1884           if (RegVT == MVT::v2f64) {
1885             if (!ArgLocs[++i].isRegLoc())
1886               return false;
1887             if (!ArgLocs[++i].isRegLoc())
1888               return false;
1889           }
1890         } else if (!VA.isRegLoc()) {
1891           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1892                                    MFI, MRI, TII))
1893             return false;
1894         }
1895       }
1896     }
1897   }
1898
1899   return true;
1900 }
1901
1902 bool
1903 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1904                                   MachineFunction &MF, bool isVarArg,
1905                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
1906                                   LLVMContext &Context) const {
1907   SmallVector<CCValAssign, 16> RVLocs;
1908   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
1909   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
1910                                                     isVarArg));
1911 }
1912
1913 SDValue
1914 ARMTargetLowering::LowerReturn(SDValue Chain,
1915                                CallingConv::ID CallConv, bool isVarArg,
1916                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1917                                const SmallVectorImpl<SDValue> &OutVals,
1918                                DebugLoc dl, SelectionDAG &DAG) const {
1919
1920   // CCValAssign - represent the assignment of the return value to a location.
1921   SmallVector<CCValAssign, 16> RVLocs;
1922
1923   // CCState - Info about the registers and stack slots.
1924   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1925                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1926
1927   // Analyze outgoing return values.
1928   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1929                                                isVarArg));
1930
1931   // If this is the first return lowered for this function, add
1932   // the regs to the liveout set for the function.
1933   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1934     for (unsigned i = 0; i != RVLocs.size(); ++i)
1935       if (RVLocs[i].isRegLoc())
1936         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1937   }
1938
1939   SDValue Flag;
1940
1941   // Copy the result values into the output registers.
1942   for (unsigned i = 0, realRVLocIdx = 0;
1943        i != RVLocs.size();
1944        ++i, ++realRVLocIdx) {
1945     CCValAssign &VA = RVLocs[i];
1946     assert(VA.isRegLoc() && "Can only return in registers!");
1947
1948     SDValue Arg = OutVals[realRVLocIdx];
1949
1950     switch (VA.getLocInfo()) {
1951     default: llvm_unreachable("Unknown loc info!");
1952     case CCValAssign::Full: break;
1953     case CCValAssign::BCvt:
1954       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1955       break;
1956     }
1957
1958     if (VA.needsCustom()) {
1959       if (VA.getLocVT() == MVT::v2f64) {
1960         // Extract the first half and return it in two registers.
1961         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1962                                    DAG.getConstant(0, MVT::i32));
1963         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
1964                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
1965
1966         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1967         Flag = Chain.getValue(1);
1968         VA = RVLocs[++i]; // skip ahead to next loc
1969         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1970                                  HalfGPRs.getValue(1), Flag);
1971         Flag = Chain.getValue(1);
1972         VA = RVLocs[++i]; // skip ahead to next loc
1973
1974         // Extract the 2nd half and fall through to handle it as an f64 value.
1975         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1976                           DAG.getConstant(1, MVT::i32));
1977       }
1978       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
1979       // available.
1980       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1981                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1982       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1983       Flag = Chain.getValue(1);
1984       VA = RVLocs[++i]; // skip ahead to next loc
1985       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1986                                Flag);
1987     } else
1988       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1989
1990     // Guarantee that all emitted copies are
1991     // stuck together, avoiding something bad.
1992     Flag = Chain.getValue(1);
1993   }
1994
1995   SDValue result;
1996   if (Flag.getNode())
1997     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
1998   else // Return Void
1999     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain);
2000
2001   return result;
2002 }
2003
2004 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2005   if (N->getNumValues() != 1)
2006     return false;
2007   if (!N->hasNUsesOfValue(1, 0))
2008     return false;
2009
2010   SDValue TCChain = Chain;
2011   SDNode *Copy = *N->use_begin();
2012   if (Copy->getOpcode() == ISD::CopyToReg) {
2013     // If the copy has a glue operand, we conservatively assume it isn't safe to
2014     // perform a tail call.
2015     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2016       return false;
2017     TCChain = Copy->getOperand(0);
2018   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2019     SDNode *VMov = Copy;
2020     // f64 returned in a pair of GPRs.
2021     SmallPtrSet<SDNode*, 2> Copies;
2022     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2023          UI != UE; ++UI) {
2024       if (UI->getOpcode() != ISD::CopyToReg)
2025         return false;
2026       Copies.insert(*UI);
2027     }
2028     if (Copies.size() > 2)
2029       return false;
2030
2031     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2032          UI != UE; ++UI) {
2033       SDValue UseChain = UI->getOperand(0);
2034       if (Copies.count(UseChain.getNode()))
2035         // Second CopyToReg
2036         Copy = *UI;
2037       else
2038         // First CopyToReg
2039         TCChain = UseChain;
2040     }
2041   } else if (Copy->getOpcode() == ISD::BITCAST) {
2042     // f32 returned in a single GPR.
2043     if (!Copy->hasOneUse())
2044       return false;
2045     Copy = *Copy->use_begin();
2046     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2047       return false;
2048     Chain = Copy->getOperand(0);
2049   } else {
2050     return false;
2051   }
2052
2053   bool HasRet = false;
2054   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2055        UI != UE; ++UI) {
2056     if (UI->getOpcode() != ARMISD::RET_FLAG)
2057       return false;
2058     HasRet = true;
2059   }
2060
2061   if (!HasRet)
2062     return false;
2063
2064   Chain = TCChain;
2065   return true;
2066 }
2067
2068 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2069   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2070     return false;
2071
2072   if (!CI->isTailCall())
2073     return false;
2074
2075   return !Subtarget->isThumb1Only();
2076 }
2077
2078 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2079 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2080 // one of the above mentioned nodes. It has to be wrapped because otherwise
2081 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2082 // be used to form addressing mode. These wrapped nodes will be selected
2083 // into MOVi.
2084 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2085   EVT PtrVT = Op.getValueType();
2086   // FIXME there is no actual debug info here
2087   DebugLoc dl = Op.getDebugLoc();
2088   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2089   SDValue Res;
2090   if (CP->isMachineConstantPoolEntry())
2091     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2092                                     CP->getAlignment());
2093   else
2094     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2095                                     CP->getAlignment());
2096   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2097 }
2098
2099 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2100   return MachineJumpTableInfo::EK_Inline;
2101 }
2102
2103 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2104                                              SelectionDAG &DAG) const {
2105   MachineFunction &MF = DAG.getMachineFunction();
2106   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2107   unsigned ARMPCLabelIndex = 0;
2108   DebugLoc DL = Op.getDebugLoc();
2109   EVT PtrVT = getPointerTy();
2110   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2111   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2112   SDValue CPAddr;
2113   if (RelocM == Reloc::Static) {
2114     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2115   } else {
2116     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2117     ARMPCLabelIndex = AFI->createPICLabelUId();
2118     ARMConstantPoolValue *CPV =
2119       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2120                                       ARMCP::CPBlockAddress, PCAdj);
2121     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2122   }
2123   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2124   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2125                                MachinePointerInfo::getConstantPool(),
2126                                false, false, false, 0);
2127   if (RelocM == Reloc::Static)
2128     return Result;
2129   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2130   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2131 }
2132
2133 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2134 SDValue
2135 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2136                                                  SelectionDAG &DAG) const {
2137   DebugLoc dl = GA->getDebugLoc();
2138   EVT PtrVT = getPointerTy();
2139   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2140   MachineFunction &MF = DAG.getMachineFunction();
2141   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2142   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2143   ARMConstantPoolValue *CPV =
2144     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2145                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2146   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2147   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2148   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2149                          MachinePointerInfo::getConstantPool(),
2150                          false, false, false, 0);
2151   SDValue Chain = Argument.getValue(1);
2152
2153   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2154   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2155
2156   // call __tls_get_addr.
2157   ArgListTy Args;
2158   ArgListEntry Entry;
2159   Entry.Node = Argument;
2160   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2161   Args.push_back(Entry);
2162   // FIXME: is there useful debug info available here?
2163   TargetLowering::CallLoweringInfo CLI(Chain,
2164                 (Type *) Type::getInt32Ty(*DAG.getContext()),
2165                 false, false, false, false,
2166                 0, CallingConv::C, /*isTailCall=*/false,
2167                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2168                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2169   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2170   return CallResult.first;
2171 }
2172
2173 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2174 // "local exec" model.
2175 SDValue
2176 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2177                                         SelectionDAG &DAG,
2178                                         TLSModel::Model model) const {
2179   const GlobalValue *GV = GA->getGlobal();
2180   DebugLoc dl = GA->getDebugLoc();
2181   SDValue Offset;
2182   SDValue Chain = DAG.getEntryNode();
2183   EVT PtrVT = getPointerTy();
2184   // Get the Thread Pointer
2185   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2186
2187   if (model == TLSModel::InitialExec) {
2188     MachineFunction &MF = DAG.getMachineFunction();
2189     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2190     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2191     // Initial exec model.
2192     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2193     ARMConstantPoolValue *CPV =
2194       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2195                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2196                                       true);
2197     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2198     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2199     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2200                          MachinePointerInfo::getConstantPool(),
2201                          false, false, false, 0);
2202     Chain = Offset.getValue(1);
2203
2204     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2205     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2206
2207     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2208                          MachinePointerInfo::getConstantPool(),
2209                          false, false, false, 0);
2210   } else {
2211     // local exec model
2212     assert(model == TLSModel::LocalExec);
2213     ARMConstantPoolValue *CPV =
2214       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2215     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2216     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2217     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2218                          MachinePointerInfo::getConstantPool(),
2219                          false, false, false, 0);
2220   }
2221
2222   // The address of the thread local variable is the add of the thread
2223   // pointer with the offset of the variable.
2224   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2225 }
2226
2227 SDValue
2228 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2229   // TODO: implement the "local dynamic" model
2230   assert(Subtarget->isTargetELF() &&
2231          "TLS not implemented for non-ELF targets");
2232   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2233
2234   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2235
2236   switch (model) {
2237     case TLSModel::GeneralDynamic:
2238     case TLSModel::LocalDynamic:
2239       return LowerToTLSGeneralDynamicModel(GA, DAG);
2240     case TLSModel::InitialExec:
2241     case TLSModel::LocalExec:
2242       return LowerToTLSExecModels(GA, DAG, model);
2243   }
2244   llvm_unreachable("bogus TLS model");
2245 }
2246
2247 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2248                                                  SelectionDAG &DAG) const {
2249   EVT PtrVT = getPointerTy();
2250   DebugLoc dl = Op.getDebugLoc();
2251   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2252   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2253   if (RelocM == Reloc::PIC_) {
2254     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2255     ARMConstantPoolValue *CPV =
2256       ARMConstantPoolConstant::Create(GV,
2257                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2258     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2259     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2260     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2261                                  CPAddr,
2262                                  MachinePointerInfo::getConstantPool(),
2263                                  false, false, false, 0);
2264     SDValue Chain = Result.getValue(1);
2265     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2266     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2267     if (!UseGOTOFF)
2268       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2269                            MachinePointerInfo::getGOT(),
2270                            false, false, false, 0);
2271     return Result;
2272   }
2273
2274   // If we have T2 ops, we can materialize the address directly via movt/movw
2275   // pair. This is always cheaper.
2276   if (Subtarget->useMovt()) {
2277     ++NumMovwMovt;
2278     // FIXME: Once remat is capable of dealing with instructions with register
2279     // operands, expand this into two nodes.
2280     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2281                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2282   } else {
2283     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2284     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2285     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2286                        MachinePointerInfo::getConstantPool(),
2287                        false, false, false, 0);
2288   }
2289 }
2290
2291 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2292                                                     SelectionDAG &DAG) const {
2293   EVT PtrVT = getPointerTy();
2294   DebugLoc dl = Op.getDebugLoc();
2295   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2296   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2297   MachineFunction &MF = DAG.getMachineFunction();
2298   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2299
2300   // FIXME: Enable this for static codegen when tool issues are fixed.  Also
2301   // update ARMFastISel::ARMMaterializeGV.
2302   if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2303     ++NumMovwMovt;
2304     // FIXME: Once remat is capable of dealing with instructions with register
2305     // operands, expand this into two nodes.
2306     if (RelocM == Reloc::Static)
2307       return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2308                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2309
2310     unsigned Wrapper = (RelocM == Reloc::PIC_)
2311       ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2312     SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2313                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2314     if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2315       Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2316                            MachinePointerInfo::getGOT(),
2317                            false, false, false, 0);
2318     return Result;
2319   }
2320
2321   unsigned ARMPCLabelIndex = 0;
2322   SDValue CPAddr;
2323   if (RelocM == Reloc::Static) {
2324     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2325   } else {
2326     ARMPCLabelIndex = AFI->createPICLabelUId();
2327     unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2328     ARMConstantPoolValue *CPV =
2329       ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2330                                       PCAdj);
2331     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2332   }
2333   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2334
2335   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2336                                MachinePointerInfo::getConstantPool(),
2337                                false, false, false, 0);
2338   SDValue Chain = Result.getValue(1);
2339
2340   if (RelocM == Reloc::PIC_) {
2341     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2342     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2343   }
2344
2345   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2346     Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2347                          false, false, false, 0);
2348
2349   return Result;
2350 }
2351
2352 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2353                                                     SelectionDAG &DAG) const {
2354   assert(Subtarget->isTargetELF() &&
2355          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2356   MachineFunction &MF = DAG.getMachineFunction();
2357   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2358   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2359   EVT PtrVT = getPointerTy();
2360   DebugLoc dl = Op.getDebugLoc();
2361   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2362   ARMConstantPoolValue *CPV =
2363     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2364                                   ARMPCLabelIndex, PCAdj);
2365   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2366   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2367   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2368                                MachinePointerInfo::getConstantPool(),
2369                                false, false, false, 0);
2370   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2371   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2372 }
2373
2374 SDValue
2375 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2376   DebugLoc dl = Op.getDebugLoc();
2377   SDValue Val = DAG.getConstant(0, MVT::i32);
2378   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2379                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2380                      Op.getOperand(1), Val);
2381 }
2382
2383 SDValue
2384 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2385   DebugLoc dl = Op.getDebugLoc();
2386   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2387                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2388 }
2389
2390 SDValue
2391 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2392                                           const ARMSubtarget *Subtarget) const {
2393   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2394   DebugLoc dl = Op.getDebugLoc();
2395   switch (IntNo) {
2396   default: return SDValue();    // Don't custom lower most intrinsics.
2397   case Intrinsic::arm_thread_pointer: {
2398     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2399     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2400   }
2401   case Intrinsic::eh_sjlj_lsda: {
2402     MachineFunction &MF = DAG.getMachineFunction();
2403     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2404     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2405     EVT PtrVT = getPointerTy();
2406     DebugLoc dl = Op.getDebugLoc();
2407     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2408     SDValue CPAddr;
2409     unsigned PCAdj = (RelocM != Reloc::PIC_)
2410       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2411     ARMConstantPoolValue *CPV =
2412       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2413                                       ARMCP::CPLSDA, PCAdj);
2414     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2415     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2416     SDValue Result =
2417       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2418                   MachinePointerInfo::getConstantPool(),
2419                   false, false, false, 0);
2420
2421     if (RelocM == Reloc::PIC_) {
2422       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2423       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2424     }
2425     return Result;
2426   }
2427   case Intrinsic::arm_neon_vmulls:
2428   case Intrinsic::arm_neon_vmullu: {
2429     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2430       ? ARMISD::VMULLs : ARMISD::VMULLu;
2431     return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2432                        Op.getOperand(1), Op.getOperand(2));
2433   }
2434   }
2435 }
2436
2437 static SDValue LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG,
2438                                const ARMSubtarget *Subtarget) {
2439   DebugLoc dl = Op.getDebugLoc();
2440   if (!Subtarget->hasDataBarrier()) {
2441     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2442     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2443     // here.
2444     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2445            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2446     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2447                        DAG.getConstant(0, MVT::i32));
2448   }
2449
2450   SDValue Op5 = Op.getOperand(5);
2451   bool isDeviceBarrier = cast<ConstantSDNode>(Op5)->getZExtValue() != 0;
2452   unsigned isLL = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2453   unsigned isLS = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2454   bool isOnlyStoreBarrier = (isLL == 0 && isLS == 0);
2455
2456   ARM_MB::MemBOpt DMBOpt;
2457   if (isDeviceBarrier)
2458     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ST : ARM_MB::SY;
2459   else
2460     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ISHST : ARM_MB::ISH;
2461   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2462                      DAG.getConstant(DMBOpt, MVT::i32));
2463 }
2464
2465
2466 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2467                                  const ARMSubtarget *Subtarget) {
2468   // FIXME: handle "fence singlethread" more efficiently.
2469   DebugLoc dl = Op.getDebugLoc();
2470   if (!Subtarget->hasDataBarrier()) {
2471     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2472     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2473     // here.
2474     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2475            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2476     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2477                        DAG.getConstant(0, MVT::i32));
2478   }
2479
2480   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2481                      DAG.getConstant(ARM_MB::ISH, MVT::i32));
2482 }
2483
2484 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2485                              const ARMSubtarget *Subtarget) {
2486   // ARM pre v5TE and Thumb1 does not have preload instructions.
2487   if (!(Subtarget->isThumb2() ||
2488         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2489     // Just preserve the chain.
2490     return Op.getOperand(0);
2491
2492   DebugLoc dl = Op.getDebugLoc();
2493   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2494   if (!isRead &&
2495       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2496     // ARMv7 with MP extension has PLDW.
2497     return Op.getOperand(0);
2498
2499   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2500   if (Subtarget->isThumb()) {
2501     // Invert the bits.
2502     isRead = ~isRead & 1;
2503     isData = ~isData & 1;
2504   }
2505
2506   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2507                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2508                      DAG.getConstant(isData, MVT::i32));
2509 }
2510
2511 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2512   MachineFunction &MF = DAG.getMachineFunction();
2513   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2514
2515   // vastart just stores the address of the VarArgsFrameIndex slot into the
2516   // memory location argument.
2517   DebugLoc dl = Op.getDebugLoc();
2518   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2519   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2520   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2521   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2522                       MachinePointerInfo(SV), false, false, 0);
2523 }
2524
2525 SDValue
2526 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2527                                         SDValue &Root, SelectionDAG &DAG,
2528                                         DebugLoc dl) const {
2529   MachineFunction &MF = DAG.getMachineFunction();
2530   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2531
2532   const TargetRegisterClass *RC;
2533   if (AFI->isThumb1OnlyFunction())
2534     RC = &ARM::tGPRRegClass;
2535   else
2536     RC = &ARM::GPRRegClass;
2537
2538   // Transform the arguments stored in physical registers into virtual ones.
2539   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2540   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2541
2542   SDValue ArgValue2;
2543   if (NextVA.isMemLoc()) {
2544     MachineFrameInfo *MFI = MF.getFrameInfo();
2545     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2546
2547     // Create load node to retrieve arguments from the stack.
2548     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2549     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2550                             MachinePointerInfo::getFixedStack(FI),
2551                             false, false, false, 0);
2552   } else {
2553     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2554     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2555   }
2556
2557   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2558 }
2559
2560 void
2561 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2562                                   unsigned &VARegSize, unsigned &VARegSaveSize)
2563   const {
2564   unsigned NumGPRs;
2565   if (CCInfo.isFirstByValRegValid())
2566     NumGPRs = ARM::R4 - CCInfo.getFirstByValReg();
2567   else {
2568     unsigned int firstUnalloced;
2569     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2570                                                 sizeof(GPRArgRegs) /
2571                                                 sizeof(GPRArgRegs[0]));
2572     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2573   }
2574
2575   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2576   VARegSize = NumGPRs * 4;
2577   VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
2578 }
2579
2580 // The remaining GPRs hold either the beginning of variable-argument
2581 // data, or the beginning of an aggregate passed by value (usuall
2582 // byval).  Either way, we allocate stack slots adjacent to the data
2583 // provided by our caller, and store the unallocated registers there.
2584 // If this is a variadic function, the va_list pointer will begin with
2585 // these values; otherwise, this reassembles a (byval) structure that
2586 // was split between registers and memory.
2587 void
2588 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2589                                         DebugLoc dl, SDValue &Chain,
2590                                         const Value *OrigArg,
2591                                         unsigned OffsetFromOrigArg,
2592                                         unsigned ArgOffset,
2593                                         bool ForceMutable) const {
2594   MachineFunction &MF = DAG.getMachineFunction();
2595   MachineFrameInfo *MFI = MF.getFrameInfo();
2596   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2597   unsigned firstRegToSaveIndex;
2598   if (CCInfo.isFirstByValRegValid())
2599     firstRegToSaveIndex = CCInfo.getFirstByValReg() - ARM::R0;
2600   else {
2601     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2602       (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2603   }
2604
2605   unsigned VARegSize, VARegSaveSize;
2606   computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2607   if (VARegSaveSize) {
2608     // If this function is vararg, store any remaining integer argument regs
2609     // to their spots on the stack so that they may be loaded by deferencing
2610     // the result of va_next.
2611     AFI->setVarArgsRegSaveSize(VARegSaveSize);
2612     AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(VARegSaveSize,
2613                                                      ArgOffset + VARegSaveSize
2614                                                      - VARegSize,
2615                                                      false));
2616     SDValue FIN = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(),
2617                                     getPointerTy());
2618
2619     SmallVector<SDValue, 4> MemOps;
2620     for (unsigned i = 0; firstRegToSaveIndex < 4; ++firstRegToSaveIndex, ++i) {
2621       const TargetRegisterClass *RC;
2622       if (AFI->isThumb1OnlyFunction())
2623         RC = &ARM::tGPRRegClass;
2624       else
2625         RC = &ARM::GPRRegClass;
2626
2627       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2628       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2629       SDValue Store =
2630         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2631                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2632                      false, false, 0);
2633       MemOps.push_back(Store);
2634       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2635                         DAG.getConstant(4, getPointerTy()));
2636     }
2637     if (!MemOps.empty())
2638       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2639                           &MemOps[0], MemOps.size());
2640   } else
2641     // This will point to the next argument passed via stack.
2642     AFI->setVarArgsFrameIndex(
2643         MFI->CreateFixedObject(4, ArgOffset, !ForceMutable));
2644 }
2645
2646 SDValue
2647 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2648                                         CallingConv::ID CallConv, bool isVarArg,
2649                                         const SmallVectorImpl<ISD::InputArg>
2650                                           &Ins,
2651                                         DebugLoc dl, SelectionDAG &DAG,
2652                                         SmallVectorImpl<SDValue> &InVals)
2653                                           const {
2654   MachineFunction &MF = DAG.getMachineFunction();
2655   MachineFrameInfo *MFI = MF.getFrameInfo();
2656
2657   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2658
2659   // Assign locations to all of the incoming arguments.
2660   SmallVector<CCValAssign, 16> ArgLocs;
2661   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2662                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2663   CCInfo.AnalyzeFormalArguments(Ins,
2664                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2665                                                   isVarArg));
2666   
2667   SmallVector<SDValue, 16> ArgValues;
2668   int lastInsIndex = -1;
2669   SDValue ArgValue;
2670   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2671   unsigned CurArgIdx = 0;
2672   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2673     CCValAssign &VA = ArgLocs[i];
2674     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2675     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2676     // Arguments stored in registers.
2677     if (VA.isRegLoc()) {
2678       EVT RegVT = VA.getLocVT();
2679
2680       if (VA.needsCustom()) {
2681         // f64 and vector types are split up into multiple registers or
2682         // combinations of registers and stack slots.
2683         if (VA.getLocVT() == MVT::v2f64) {
2684           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2685                                                    Chain, DAG, dl);
2686           VA = ArgLocs[++i]; // skip ahead to next loc
2687           SDValue ArgValue2;
2688           if (VA.isMemLoc()) {
2689             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2690             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2691             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2692                                     MachinePointerInfo::getFixedStack(FI),
2693                                     false, false, false, 0);
2694           } else {
2695             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2696                                              Chain, DAG, dl);
2697           }
2698           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2699           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2700                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2701           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2702                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2703         } else
2704           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2705
2706       } else {
2707         const TargetRegisterClass *RC;
2708
2709         if (RegVT == MVT::f32)
2710           RC = &ARM::SPRRegClass;
2711         else if (RegVT == MVT::f64)
2712           RC = &ARM::DPRRegClass;
2713         else if (RegVT == MVT::v2f64)
2714           RC = &ARM::QPRRegClass;
2715         else if (RegVT == MVT::i32)
2716           RC = AFI->isThumb1OnlyFunction() ?
2717             (const TargetRegisterClass*)&ARM::tGPRRegClass :
2718             (const TargetRegisterClass*)&ARM::GPRRegClass;
2719         else
2720           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2721
2722         // Transform the arguments in physical registers into virtual ones.
2723         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2724         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2725       }
2726
2727       // If this is an 8 or 16-bit value, it is really passed promoted
2728       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2729       // truncate to the right size.
2730       switch (VA.getLocInfo()) {
2731       default: llvm_unreachable("Unknown loc info!");
2732       case CCValAssign::Full: break;
2733       case CCValAssign::BCvt:
2734         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2735         break;
2736       case CCValAssign::SExt:
2737         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2738                                DAG.getValueType(VA.getValVT()));
2739         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2740         break;
2741       case CCValAssign::ZExt:
2742         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2743                                DAG.getValueType(VA.getValVT()));
2744         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2745         break;
2746       }
2747
2748       InVals.push_back(ArgValue);
2749
2750     } else { // VA.isRegLoc()
2751
2752       // sanity check
2753       assert(VA.isMemLoc());
2754       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2755
2756       int index = ArgLocs[i].getValNo();
2757
2758       // Some Ins[] entries become multiple ArgLoc[] entries.
2759       // Process them only once.
2760       if (index != lastInsIndex)
2761         {
2762           ISD::ArgFlagsTy Flags = Ins[index].Flags;
2763           // FIXME: For now, all byval parameter objects are marked mutable.
2764           // This can be changed with more analysis.
2765           // In case of tail call optimization mark all arguments mutable.
2766           // Since they could be overwritten by lowering of arguments in case of
2767           // a tail call.
2768           if (Flags.isByVal()) {
2769             ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2770             if (!AFI->getVarArgsFrameIndex()) {
2771               VarArgStyleRegisters(CCInfo, DAG,
2772                                    dl, Chain, CurOrigArg,
2773                                    Ins[VA.getValNo()].PartOffset,
2774                                    VA.getLocMemOffset(),
2775                                    true /*force mutable frames*/);
2776               int VAFrameIndex = AFI->getVarArgsFrameIndex();
2777               InVals.push_back(DAG.getFrameIndex(VAFrameIndex, getPointerTy()));
2778             } else {
2779               int FI = MFI->CreateFixedObject(Flags.getByValSize(),
2780                                               VA.getLocMemOffset(), false);
2781               InVals.push_back(DAG.getFrameIndex(FI, getPointerTy()));              
2782             }
2783           } else {
2784             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2785                                             VA.getLocMemOffset(), true);
2786
2787             // Create load nodes to retrieve arguments from the stack.
2788             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2789             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2790                                          MachinePointerInfo::getFixedStack(FI),
2791                                          false, false, false, 0));
2792           }
2793           lastInsIndex = index;
2794         }
2795     }
2796   }
2797
2798   // varargs
2799   if (isVarArg)
2800     VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 0, 0,
2801                          CCInfo.getNextStackOffset());
2802
2803   return Chain;
2804 }
2805
2806 /// isFloatingPointZero - Return true if this is +0.0.
2807 static bool isFloatingPointZero(SDValue Op) {
2808   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2809     return CFP->getValueAPF().isPosZero();
2810   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2811     // Maybe this has already been legalized into the constant pool?
2812     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2813       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2814       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2815         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2816           return CFP->getValueAPF().isPosZero();
2817     }
2818   }
2819   return false;
2820 }
2821
2822 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2823 /// the given operands.
2824 SDValue
2825 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2826                              SDValue &ARMcc, SelectionDAG &DAG,
2827                              DebugLoc dl) const {
2828   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2829     unsigned C = RHSC->getZExtValue();
2830     if (!isLegalICmpImmediate(C)) {
2831       // Constant does not fit, try adjusting it by one?
2832       switch (CC) {
2833       default: break;
2834       case ISD::SETLT:
2835       case ISD::SETGE:
2836         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2837           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2838           RHS = DAG.getConstant(C-1, MVT::i32);
2839         }
2840         break;
2841       case ISD::SETULT:
2842       case ISD::SETUGE:
2843         if (C != 0 && isLegalICmpImmediate(C-1)) {
2844           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2845           RHS = DAG.getConstant(C-1, MVT::i32);
2846         }
2847         break;
2848       case ISD::SETLE:
2849       case ISD::SETGT:
2850         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
2851           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2852           RHS = DAG.getConstant(C+1, MVT::i32);
2853         }
2854         break;
2855       case ISD::SETULE:
2856       case ISD::SETUGT:
2857         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
2858           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2859           RHS = DAG.getConstant(C+1, MVT::i32);
2860         }
2861         break;
2862       }
2863     }
2864   }
2865
2866   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2867   ARMISD::NodeType CompareType;
2868   switch (CondCode) {
2869   default:
2870     CompareType = ARMISD::CMP;
2871     break;
2872   case ARMCC::EQ:
2873   case ARMCC::NE:
2874     // Uses only Z Flag
2875     CompareType = ARMISD::CMPZ;
2876     break;
2877   }
2878   ARMcc = DAG.getConstant(CondCode, MVT::i32);
2879   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
2880 }
2881
2882 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
2883 SDValue
2884 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
2885                              DebugLoc dl) const {
2886   SDValue Cmp;
2887   if (!isFloatingPointZero(RHS))
2888     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
2889   else
2890     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
2891   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
2892 }
2893
2894 /// duplicateCmp - Glue values can have only one use, so this function
2895 /// duplicates a comparison node.
2896 SDValue
2897 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
2898   unsigned Opc = Cmp.getOpcode();
2899   DebugLoc DL = Cmp.getDebugLoc();
2900   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
2901     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2902
2903   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
2904   Cmp = Cmp.getOperand(0);
2905   Opc = Cmp.getOpcode();
2906   if (Opc == ARMISD::CMPFP)
2907     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2908   else {
2909     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
2910     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
2911   }
2912   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
2913 }
2914
2915 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2916   SDValue Cond = Op.getOperand(0);
2917   SDValue SelectTrue = Op.getOperand(1);
2918   SDValue SelectFalse = Op.getOperand(2);
2919   DebugLoc dl = Op.getDebugLoc();
2920
2921   // Convert:
2922   //
2923   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
2924   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
2925   //
2926   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
2927     const ConstantSDNode *CMOVTrue =
2928       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
2929     const ConstantSDNode *CMOVFalse =
2930       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2931
2932     if (CMOVTrue && CMOVFalse) {
2933       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
2934       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
2935
2936       SDValue True;
2937       SDValue False;
2938       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
2939         True = SelectTrue;
2940         False = SelectFalse;
2941       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
2942         True = SelectFalse;
2943         False = SelectTrue;
2944       }
2945
2946       if (True.getNode() && False.getNode()) {
2947         EVT VT = Op.getValueType();
2948         SDValue ARMcc = Cond.getOperand(2);
2949         SDValue CCR = Cond.getOperand(3);
2950         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
2951         assert(True.getValueType() == VT);
2952         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
2953       }
2954     }
2955   }
2956
2957   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
2958   // undefined bits before doing a full-word comparison with zero.
2959   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
2960                      DAG.getConstant(1, Cond.getValueType()));
2961
2962   return DAG.getSelectCC(dl, Cond,
2963                          DAG.getConstant(0, Cond.getValueType()),
2964                          SelectTrue, SelectFalse, ISD::SETNE);
2965 }
2966
2967 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2968   EVT VT = Op.getValueType();
2969   SDValue LHS = Op.getOperand(0);
2970   SDValue RHS = Op.getOperand(1);
2971   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2972   SDValue TrueVal = Op.getOperand(2);
2973   SDValue FalseVal = Op.getOperand(3);
2974   DebugLoc dl = Op.getDebugLoc();
2975
2976   if (LHS.getValueType() == MVT::i32) {
2977     SDValue ARMcc;
2978     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2979     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2980     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
2981   }
2982
2983   ARMCC::CondCodes CondCode, CondCode2;
2984   FPCCToARMCC(CC, CondCode, CondCode2);
2985
2986   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
2987   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
2988   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2989   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
2990                                ARMcc, CCR, Cmp);
2991   if (CondCode2 != ARMCC::AL) {
2992     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
2993     // FIXME: Needs another CMP because flag can have but one use.
2994     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
2995     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
2996                          Result, TrueVal, ARMcc2, CCR, Cmp2);
2997   }
2998   return Result;
2999 }
3000
3001 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3002 /// to morph to an integer compare sequence.
3003 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3004                            const ARMSubtarget *Subtarget) {
3005   SDNode *N = Op.getNode();
3006   if (!N->hasOneUse())
3007     // Otherwise it requires moving the value from fp to integer registers.
3008     return false;
3009   if (!N->getNumValues())
3010     return false;
3011   EVT VT = Op.getValueType();
3012   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3013     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3014     // vmrs are very slow, e.g. cortex-a8.
3015     return false;
3016
3017   if (isFloatingPointZero(Op)) {
3018     SeenZero = true;
3019     return true;
3020   }
3021   return ISD::isNormalLoad(N);
3022 }
3023
3024 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3025   if (isFloatingPointZero(Op))
3026     return DAG.getConstant(0, MVT::i32);
3027
3028   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3029     return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3030                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3031                        Ld->isVolatile(), Ld->isNonTemporal(),
3032                        Ld->isInvariant(), Ld->getAlignment());
3033
3034   llvm_unreachable("Unknown VFP cmp argument!");
3035 }
3036
3037 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3038                            SDValue &RetVal1, SDValue &RetVal2) {
3039   if (isFloatingPointZero(Op)) {
3040     RetVal1 = DAG.getConstant(0, MVT::i32);
3041     RetVal2 = DAG.getConstant(0, MVT::i32);
3042     return;
3043   }
3044
3045   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3046     SDValue Ptr = Ld->getBasePtr();
3047     RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3048                           Ld->getChain(), Ptr,
3049                           Ld->getPointerInfo(),
3050                           Ld->isVolatile(), Ld->isNonTemporal(),
3051                           Ld->isInvariant(), Ld->getAlignment());
3052
3053     EVT PtrType = Ptr.getValueType();
3054     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3055     SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
3056                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3057     RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
3058                           Ld->getChain(), NewPtr,
3059                           Ld->getPointerInfo().getWithOffset(4),
3060                           Ld->isVolatile(), Ld->isNonTemporal(),
3061                           Ld->isInvariant(), NewAlign);
3062     return;
3063   }
3064
3065   llvm_unreachable("Unknown VFP cmp argument!");
3066 }
3067
3068 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3069 /// f32 and even f64 comparisons to integer ones.
3070 SDValue
3071 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3072   SDValue Chain = Op.getOperand(0);
3073   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3074   SDValue LHS = Op.getOperand(2);
3075   SDValue RHS = Op.getOperand(3);
3076   SDValue Dest = Op.getOperand(4);
3077   DebugLoc dl = Op.getDebugLoc();
3078
3079   bool LHSSeenZero = false;
3080   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3081   bool RHSSeenZero = false;
3082   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3083   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3084     // If unsafe fp math optimization is enabled and there are no other uses of
3085     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3086     // to an integer comparison.
3087     if (CC == ISD::SETOEQ)
3088       CC = ISD::SETEQ;
3089     else if (CC == ISD::SETUNE)
3090       CC = ISD::SETNE;
3091
3092     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3093     SDValue ARMcc;
3094     if (LHS.getValueType() == MVT::f32) {
3095       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3096                         bitcastf32Toi32(LHS, DAG), Mask);
3097       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3098                         bitcastf32Toi32(RHS, DAG), Mask);
3099       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3100       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3101       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3102                          Chain, Dest, ARMcc, CCR, Cmp);
3103     }
3104
3105     SDValue LHS1, LHS2;
3106     SDValue RHS1, RHS2;
3107     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3108     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3109     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3110     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3111     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3112     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3113     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3114     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3115     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3116   }
3117
3118   return SDValue();
3119 }
3120
3121 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3122   SDValue Chain = Op.getOperand(0);
3123   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3124   SDValue LHS = Op.getOperand(2);
3125   SDValue RHS = Op.getOperand(3);
3126   SDValue Dest = Op.getOperand(4);
3127   DebugLoc dl = Op.getDebugLoc();
3128
3129   if (LHS.getValueType() == MVT::i32) {
3130     SDValue ARMcc;
3131     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3132     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3133     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3134                        Chain, Dest, ARMcc, CCR, Cmp);
3135   }
3136
3137   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3138
3139   if (getTargetMachine().Options.UnsafeFPMath &&
3140       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3141        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3142     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3143     if (Result.getNode())
3144       return Result;
3145   }
3146
3147   ARMCC::CondCodes CondCode, CondCode2;
3148   FPCCToARMCC(CC, CondCode, CondCode2);
3149
3150   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3151   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3152   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3153   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3154   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3155   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3156   if (CondCode2 != ARMCC::AL) {
3157     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3158     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3159     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3160   }
3161   return Res;
3162 }
3163
3164 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3165   SDValue Chain = Op.getOperand(0);
3166   SDValue Table = Op.getOperand(1);
3167   SDValue Index = Op.getOperand(2);
3168   DebugLoc dl = Op.getDebugLoc();
3169
3170   EVT PTy = getPointerTy();
3171   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3172   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3173   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3174   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3175   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3176   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3177   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3178   if (Subtarget->isThumb2()) {
3179     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3180     // which does another jump to the destination. This also makes it easier
3181     // to translate it to TBB / TBH later.
3182     // FIXME: This might not work if the function is extremely large.
3183     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3184                        Addr, Op.getOperand(2), JTI, UId);
3185   }
3186   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3187     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3188                        MachinePointerInfo::getJumpTable(),
3189                        false, false, false, 0);
3190     Chain = Addr.getValue(1);
3191     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3192     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3193   } else {
3194     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3195                        MachinePointerInfo::getJumpTable(),
3196                        false, false, false, 0);
3197     Chain = Addr.getValue(1);
3198     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3199   }
3200 }
3201
3202 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3203   EVT VT = Op.getValueType();
3204   DebugLoc dl = Op.getDebugLoc();
3205
3206   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3207     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3208       return Op;
3209     return DAG.UnrollVectorOp(Op.getNode());
3210   }
3211
3212   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3213          "Invalid type for custom lowering!");
3214   if (VT != MVT::v4i16)
3215     return DAG.UnrollVectorOp(Op.getNode());
3216
3217   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3218   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3219 }
3220
3221 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3222   EVT VT = Op.getValueType();
3223   if (VT.isVector())
3224     return LowerVectorFP_TO_INT(Op, DAG);
3225
3226   DebugLoc dl = Op.getDebugLoc();
3227   unsigned Opc;
3228
3229   switch (Op.getOpcode()) {
3230   default: llvm_unreachable("Invalid opcode!");
3231   case ISD::FP_TO_SINT:
3232     Opc = ARMISD::FTOSI;
3233     break;
3234   case ISD::FP_TO_UINT:
3235     Opc = ARMISD::FTOUI;
3236     break;
3237   }
3238   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3239   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3240 }
3241
3242 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3243   EVT VT = Op.getValueType();
3244   DebugLoc dl = Op.getDebugLoc();
3245
3246   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3247     if (VT.getVectorElementType() == MVT::f32)
3248       return Op;
3249     return DAG.UnrollVectorOp(Op.getNode());
3250   }
3251
3252   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3253          "Invalid type for custom lowering!");
3254   if (VT != MVT::v4f32)
3255     return DAG.UnrollVectorOp(Op.getNode());
3256
3257   unsigned CastOpc;
3258   unsigned Opc;
3259   switch (Op.getOpcode()) {
3260   default: llvm_unreachable("Invalid opcode!");
3261   case ISD::SINT_TO_FP:
3262     CastOpc = ISD::SIGN_EXTEND;
3263     Opc = ISD::SINT_TO_FP;
3264     break;
3265   case ISD::UINT_TO_FP:
3266     CastOpc = ISD::ZERO_EXTEND;
3267     Opc = ISD::UINT_TO_FP;
3268     break;
3269   }
3270
3271   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3272   return DAG.getNode(Opc, dl, VT, Op);
3273 }
3274
3275 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3276   EVT VT = Op.getValueType();
3277   if (VT.isVector())
3278     return LowerVectorINT_TO_FP(Op, DAG);
3279
3280   DebugLoc dl = Op.getDebugLoc();
3281   unsigned Opc;
3282
3283   switch (Op.getOpcode()) {
3284   default: llvm_unreachable("Invalid opcode!");
3285   case ISD::SINT_TO_FP:
3286     Opc = ARMISD::SITOF;
3287     break;
3288   case ISD::UINT_TO_FP:
3289     Opc = ARMISD::UITOF;
3290     break;
3291   }
3292
3293   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3294   return DAG.getNode(Opc, dl, VT, Op);
3295 }
3296
3297 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3298   // Implement fcopysign with a fabs and a conditional fneg.
3299   SDValue Tmp0 = Op.getOperand(0);
3300   SDValue Tmp1 = Op.getOperand(1);
3301   DebugLoc dl = Op.getDebugLoc();
3302   EVT VT = Op.getValueType();
3303   EVT SrcVT = Tmp1.getValueType();
3304   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3305     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3306   bool UseNEON = !InGPR && Subtarget->hasNEON();
3307
3308   if (UseNEON) {
3309     // Use VBSL to copy the sign bit.
3310     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3311     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3312                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3313     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3314     if (VT == MVT::f64)
3315       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3316                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3317                          DAG.getConstant(32, MVT::i32));
3318     else /*if (VT == MVT::f32)*/
3319       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3320     if (SrcVT == MVT::f32) {
3321       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3322       if (VT == MVT::f64)
3323         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3324                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3325                            DAG.getConstant(32, MVT::i32));
3326     } else if (VT == MVT::f32)
3327       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3328                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3329                          DAG.getConstant(32, MVT::i32));
3330     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3331     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3332
3333     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3334                                             MVT::i32);
3335     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3336     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3337                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3338
3339     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3340                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3341                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3342     if (VT == MVT::f32) {
3343       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3344       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3345                         DAG.getConstant(0, MVT::i32));
3346     } else {
3347       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3348     }
3349
3350     return Res;
3351   }
3352
3353   // Bitcast operand 1 to i32.
3354   if (SrcVT == MVT::f64)
3355     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3356                        &Tmp1, 1).getValue(1);
3357   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3358
3359   // Or in the signbit with integer operations.
3360   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3361   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3362   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3363   if (VT == MVT::f32) {
3364     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3365                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3366     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3367                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3368   }
3369
3370   // f64: Or the high part with signbit and then combine two parts.
3371   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3372                      &Tmp0, 1);
3373   SDValue Lo = Tmp0.getValue(0);
3374   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3375   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3376   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3377 }
3378
3379 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3380   MachineFunction &MF = DAG.getMachineFunction();
3381   MachineFrameInfo *MFI = MF.getFrameInfo();
3382   MFI->setReturnAddressIsTaken(true);
3383
3384   EVT VT = Op.getValueType();
3385   DebugLoc dl = Op.getDebugLoc();
3386   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3387   if (Depth) {
3388     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3389     SDValue Offset = DAG.getConstant(4, MVT::i32);
3390     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3391                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3392                        MachinePointerInfo(), false, false, false, 0);
3393   }
3394
3395   // Return LR, which contains the return address. Mark it an implicit live-in.
3396   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3397   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3398 }
3399
3400 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3401   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3402   MFI->setFrameAddressIsTaken(true);
3403
3404   EVT VT = Op.getValueType();
3405   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
3406   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3407   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3408     ? ARM::R7 : ARM::R11;
3409   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3410   while (Depth--)
3411     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3412                             MachinePointerInfo(),
3413                             false, false, false, 0);
3414   return FrameAddr;
3415 }
3416
3417 /// ExpandBITCAST - If the target supports VFP, this function is called to
3418 /// expand a bit convert where either the source or destination type is i64 to
3419 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3420 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3421 /// vectors), since the legalizer won't know what to do with that.
3422 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3423   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3424   DebugLoc dl = N->getDebugLoc();
3425   SDValue Op = N->getOperand(0);
3426
3427   // This function is only supposed to be called for i64 types, either as the
3428   // source or destination of the bit convert.
3429   EVT SrcVT = Op.getValueType();
3430   EVT DstVT = N->getValueType(0);
3431   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3432          "ExpandBITCAST called for non-i64 type");
3433
3434   // Turn i64->f64 into VMOVDRR.
3435   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3436     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3437                              DAG.getConstant(0, MVT::i32));
3438     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3439                              DAG.getConstant(1, MVT::i32));
3440     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3441                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3442   }
3443
3444   // Turn f64->i64 into VMOVRRD.
3445   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3446     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3447                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3448     // Merge the pieces into a single i64 value.
3449     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3450   }
3451
3452   return SDValue();
3453 }
3454
3455 /// getZeroVector - Returns a vector of specified type with all zero elements.
3456 /// Zero vectors are used to represent vector negation and in those cases
3457 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3458 /// not support i64 elements, so sometimes the zero vectors will need to be
3459 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3460 /// zero vector.
3461 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3462   assert(VT.isVector() && "Expected a vector type");
3463   // The canonical modified immediate encoding of a zero vector is....0!
3464   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3465   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3466   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3467   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3468 }
3469
3470 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3471 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3472 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3473                                                 SelectionDAG &DAG) const {
3474   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3475   EVT VT = Op.getValueType();
3476   unsigned VTBits = VT.getSizeInBits();
3477   DebugLoc dl = Op.getDebugLoc();
3478   SDValue ShOpLo = Op.getOperand(0);
3479   SDValue ShOpHi = Op.getOperand(1);
3480   SDValue ShAmt  = Op.getOperand(2);
3481   SDValue ARMcc;
3482   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3483
3484   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3485
3486   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3487                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3488   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3489   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3490                                    DAG.getConstant(VTBits, MVT::i32));
3491   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3492   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3493   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3494
3495   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3496   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3497                           ARMcc, DAG, dl);
3498   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3499   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3500                            CCR, Cmp);
3501
3502   SDValue Ops[2] = { Lo, Hi };
3503   return DAG.getMergeValues(Ops, 2, dl);
3504 }
3505
3506 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3507 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3508 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3509                                                SelectionDAG &DAG) const {
3510   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3511   EVT VT = Op.getValueType();
3512   unsigned VTBits = VT.getSizeInBits();
3513   DebugLoc dl = Op.getDebugLoc();
3514   SDValue ShOpLo = Op.getOperand(0);
3515   SDValue ShOpHi = Op.getOperand(1);
3516   SDValue ShAmt  = Op.getOperand(2);
3517   SDValue ARMcc;
3518
3519   assert(Op.getOpcode() == ISD::SHL_PARTS);
3520   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3521                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3522   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3523   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3524                                    DAG.getConstant(VTBits, MVT::i32));
3525   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3526   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3527
3528   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3529   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3530   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3531                           ARMcc, DAG, dl);
3532   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3533   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3534                            CCR, Cmp);
3535
3536   SDValue Ops[2] = { Lo, Hi };
3537   return DAG.getMergeValues(Ops, 2, dl);
3538 }
3539
3540 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3541                                             SelectionDAG &DAG) const {
3542   // The rounding mode is in bits 23:22 of the FPSCR.
3543   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3544   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3545   // so that the shift + and get folded into a bitfield extract.
3546   DebugLoc dl = Op.getDebugLoc();
3547   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3548                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3549                                               MVT::i32));
3550   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3551                                   DAG.getConstant(1U << 22, MVT::i32));
3552   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3553                               DAG.getConstant(22, MVT::i32));
3554   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3555                      DAG.getConstant(3, MVT::i32));
3556 }
3557
3558 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3559                          const ARMSubtarget *ST) {
3560   EVT VT = N->getValueType(0);
3561   DebugLoc dl = N->getDebugLoc();
3562
3563   if (!ST->hasV6T2Ops())
3564     return SDValue();
3565
3566   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3567   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3568 }
3569
3570 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3571 /// for each 16-bit element from operand, repeated.  The basic idea is to
3572 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3573 ///
3574 /// Trace for v4i16:
3575 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
3576 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3577 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3578 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6] 
3579 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
3580 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
3581 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3582 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
3583 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3584   EVT VT = N->getValueType(0);
3585   DebugLoc DL = N->getDebugLoc();
3586
3587   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
3588   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
3589   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
3590   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
3591   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
3592   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
3593 }
3594
3595 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
3596 /// bit-count for each 16-bit element from the operand.  We need slightly
3597 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
3598 /// 64/128-bit registers.
3599 /// 
3600 /// Trace for v4i16:
3601 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
3602 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
3603 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
3604 /// v4i16:Extracted = [k0    k1    k2    k3    ]
3605 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
3606   EVT VT = N->getValueType(0);
3607   DebugLoc DL = N->getDebugLoc();
3608
3609   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
3610   if (VT.is64BitVector()) {
3611     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
3612     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
3613                        DAG.getIntPtrConstant(0));
3614   } else {
3615     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
3616                                     BitCounts, DAG.getIntPtrConstant(0));
3617     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
3618   }
3619 }
3620
3621 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
3622 /// bit-count for each 32-bit element from the operand.  The idea here is
3623 /// to split the vector into 16-bit elements, leverage the 16-bit count
3624 /// routine, and then combine the results.
3625 ///
3626 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
3627 /// input    = [v0    v1    ] (vi: 32-bit elements)
3628 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
3629 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
3630 /// vrev: N0 = [k1 k0 k3 k2 ] 
3631 ///            [k0 k1 k2 k3 ]
3632 ///       N1 =+[k1 k0 k3 k2 ]
3633 ///            [k0 k2 k1 k3 ]
3634 ///       N2 =+[k1 k3 k0 k2 ]
3635 ///            [k0    k2    k1    k3    ]
3636 /// Extended =+[k1    k3    k0    k2    ]
3637 ///            [k0    k2    ]
3638 /// Extracted=+[k1    k3    ]
3639 ///
3640 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
3641   EVT VT = N->getValueType(0);
3642   DebugLoc DL = N->getDebugLoc();
3643
3644   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
3645
3646   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
3647   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
3648   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
3649   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
3650   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
3651
3652   if (VT.is64BitVector()) {
3653     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
3654     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
3655                        DAG.getIntPtrConstant(0));
3656   } else {
3657     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
3658                                     DAG.getIntPtrConstant(0));
3659     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
3660   }
3661 }
3662
3663 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
3664                           const ARMSubtarget *ST) {
3665   EVT VT = N->getValueType(0);
3666
3667   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
3668   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
3669           VT == MVT::v4i16 || VT == MVT::v8i16) &&
3670          "Unexpected type for custom ctpop lowering");
3671
3672   if (VT.getVectorElementType() == MVT::i32)
3673     return lowerCTPOP32BitElements(N, DAG);
3674   else
3675     return lowerCTPOP16BitElements(N, DAG);
3676 }
3677
3678 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3679                           const ARMSubtarget *ST) {
3680   EVT VT = N->getValueType(0);
3681   DebugLoc dl = N->getDebugLoc();
3682
3683   if (!VT.isVector())
3684     return SDValue();
3685
3686   // Lower vector shifts on NEON to use VSHL.
3687   assert(ST->hasNEON() && "unexpected vector shift");
3688
3689   // Left shifts translate directly to the vshiftu intrinsic.
3690   if (N->getOpcode() == ISD::SHL)
3691     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3692                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3693                        N->getOperand(0), N->getOperand(1));
3694
3695   assert((N->getOpcode() == ISD::SRA ||
3696           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3697
3698   // NEON uses the same intrinsics for both left and right shifts.  For
3699   // right shifts, the shift amounts are negative, so negate the vector of
3700   // shift amounts.
3701   EVT ShiftVT = N->getOperand(1).getValueType();
3702   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3703                                      getZeroVector(ShiftVT, DAG, dl),
3704                                      N->getOperand(1));
3705   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3706                              Intrinsic::arm_neon_vshifts :
3707                              Intrinsic::arm_neon_vshiftu);
3708   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3709                      DAG.getConstant(vshiftInt, MVT::i32),
3710                      N->getOperand(0), NegatedCount);
3711 }
3712
3713 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3714                                 const ARMSubtarget *ST) {
3715   EVT VT = N->getValueType(0);
3716   DebugLoc dl = N->getDebugLoc();
3717
3718   // We can get here for a node like i32 = ISD::SHL i32, i64
3719   if (VT != MVT::i64)
3720     return SDValue();
3721
3722   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3723          "Unknown shift to lower!");
3724
3725   // We only lower SRA, SRL of 1 here, all others use generic lowering.
3726   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3727       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3728     return SDValue();
3729
3730   // If we are in thumb mode, we don't have RRX.
3731   if (ST->isThumb1Only()) return SDValue();
3732
3733   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
3734   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3735                            DAG.getConstant(0, MVT::i32));
3736   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3737                            DAG.getConstant(1, MVT::i32));
3738
3739   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3740   // captures the result into a carry flag.
3741   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3742   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3743
3744   // The low part is an ARMISD::RRX operand, which shifts the carry in.
3745   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3746
3747   // Merge the pieces into a single i64 value.
3748  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3749 }
3750
3751 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3752   SDValue TmpOp0, TmpOp1;
3753   bool Invert = false;
3754   bool Swap = false;
3755   unsigned Opc = 0;
3756
3757   SDValue Op0 = Op.getOperand(0);
3758   SDValue Op1 = Op.getOperand(1);
3759   SDValue CC = Op.getOperand(2);
3760   EVT VT = Op.getValueType();
3761   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3762   DebugLoc dl = Op.getDebugLoc();
3763
3764   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3765     switch (SetCCOpcode) {
3766     default: llvm_unreachable("Illegal FP comparison");
3767     case ISD::SETUNE:
3768     case ISD::SETNE:  Invert = true; // Fallthrough
3769     case ISD::SETOEQ:
3770     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3771     case ISD::SETOLT:
3772     case ISD::SETLT: Swap = true; // Fallthrough
3773     case ISD::SETOGT:
3774     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3775     case ISD::SETOLE:
3776     case ISD::SETLE:  Swap = true; // Fallthrough
3777     case ISD::SETOGE:
3778     case ISD::SETGE: Opc = ARMISD::VCGE; break;
3779     case ISD::SETUGE: Swap = true; // Fallthrough
3780     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3781     case ISD::SETUGT: Swap = true; // Fallthrough
3782     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3783     case ISD::SETUEQ: Invert = true; // Fallthrough
3784     case ISD::SETONE:
3785       // Expand this to (OLT | OGT).
3786       TmpOp0 = Op0;
3787       TmpOp1 = Op1;
3788       Opc = ISD::OR;
3789       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3790       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3791       break;
3792     case ISD::SETUO: Invert = true; // Fallthrough
3793     case ISD::SETO:
3794       // Expand this to (OLT | OGE).
3795       TmpOp0 = Op0;
3796       TmpOp1 = Op1;
3797       Opc = ISD::OR;
3798       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3799       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3800       break;
3801     }
3802   } else {
3803     // Integer comparisons.
3804     switch (SetCCOpcode) {
3805     default: llvm_unreachable("Illegal integer comparison");
3806     case ISD::SETNE:  Invert = true;
3807     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3808     case ISD::SETLT:  Swap = true;
3809     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3810     case ISD::SETLE:  Swap = true;
3811     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
3812     case ISD::SETULT: Swap = true;
3813     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
3814     case ISD::SETULE: Swap = true;
3815     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
3816     }
3817
3818     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
3819     if (Opc == ARMISD::VCEQ) {
3820
3821       SDValue AndOp;
3822       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3823         AndOp = Op0;
3824       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
3825         AndOp = Op1;
3826
3827       // Ignore bitconvert.
3828       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
3829         AndOp = AndOp.getOperand(0);
3830
3831       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
3832         Opc = ARMISD::VTST;
3833         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
3834         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
3835         Invert = !Invert;
3836       }
3837     }
3838   }
3839
3840   if (Swap)
3841     std::swap(Op0, Op1);
3842
3843   // If one of the operands is a constant vector zero, attempt to fold the
3844   // comparison to a specialized compare-against-zero form.
3845   SDValue SingleOp;
3846   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3847     SingleOp = Op0;
3848   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
3849     if (Opc == ARMISD::VCGE)
3850       Opc = ARMISD::VCLEZ;
3851     else if (Opc == ARMISD::VCGT)
3852       Opc = ARMISD::VCLTZ;
3853     SingleOp = Op1;
3854   }
3855
3856   SDValue Result;
3857   if (SingleOp.getNode()) {
3858     switch (Opc) {
3859     case ARMISD::VCEQ:
3860       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
3861     case ARMISD::VCGE:
3862       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
3863     case ARMISD::VCLEZ:
3864       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
3865     case ARMISD::VCGT:
3866       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
3867     case ARMISD::VCLTZ:
3868       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
3869     default:
3870       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3871     }
3872   } else {
3873      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3874   }
3875
3876   if (Invert)
3877     Result = DAG.getNOT(dl, Result, VT);
3878
3879   return Result;
3880 }
3881
3882 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
3883 /// valid vector constant for a NEON instruction with a "modified immediate"
3884 /// operand (e.g., VMOV).  If so, return the encoded value.
3885 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
3886                                  unsigned SplatBitSize, SelectionDAG &DAG,
3887                                  EVT &VT, bool is128Bits, NEONModImmType type) {
3888   unsigned OpCmode, Imm;
3889
3890   // SplatBitSize is set to the smallest size that splats the vector, so a
3891   // zero vector will always have SplatBitSize == 8.  However, NEON modified
3892   // immediate instructions others than VMOV do not support the 8-bit encoding
3893   // of a zero vector, and the default encoding of zero is supposed to be the
3894   // 32-bit version.
3895   if (SplatBits == 0)
3896     SplatBitSize = 32;
3897
3898   switch (SplatBitSize) {
3899   case 8:
3900     if (type != VMOVModImm)
3901       return SDValue();
3902     // Any 1-byte value is OK.  Op=0, Cmode=1110.
3903     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
3904     OpCmode = 0xe;
3905     Imm = SplatBits;
3906     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
3907     break;
3908
3909   case 16:
3910     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
3911     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3912     if ((SplatBits & ~0xff) == 0) {
3913       // Value = 0x00nn: Op=x, Cmode=100x.
3914       OpCmode = 0x8;
3915       Imm = SplatBits;
3916       break;
3917     }
3918     if ((SplatBits & ~0xff00) == 0) {
3919       // Value = 0xnn00: Op=x, Cmode=101x.
3920       OpCmode = 0xa;
3921       Imm = SplatBits >> 8;
3922       break;
3923     }
3924     return SDValue();
3925
3926   case 32:
3927     // NEON's 32-bit VMOV supports splat values where:
3928     // * only one byte is nonzero, or
3929     // * the least significant byte is 0xff and the second byte is nonzero, or
3930     // * the least significant 2 bytes are 0xff and the third is nonzero.
3931     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3932     if ((SplatBits & ~0xff) == 0) {
3933       // Value = 0x000000nn: Op=x, Cmode=000x.
3934       OpCmode = 0;
3935       Imm = SplatBits;
3936       break;
3937     }
3938     if ((SplatBits & ~0xff00) == 0) {
3939       // Value = 0x0000nn00: Op=x, Cmode=001x.
3940       OpCmode = 0x2;
3941       Imm = SplatBits >> 8;
3942       break;
3943     }
3944     if ((SplatBits & ~0xff0000) == 0) {
3945       // Value = 0x00nn0000: Op=x, Cmode=010x.
3946       OpCmode = 0x4;
3947       Imm = SplatBits >> 16;
3948       break;
3949     }
3950     if ((SplatBits & ~0xff000000) == 0) {
3951       // Value = 0xnn000000: Op=x, Cmode=011x.
3952       OpCmode = 0x6;
3953       Imm = SplatBits >> 24;
3954       break;
3955     }
3956
3957     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
3958     if (type == OtherModImm) return SDValue();
3959
3960     if ((SplatBits & ~0xffff) == 0 &&
3961         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
3962       // Value = 0x0000nnff: Op=x, Cmode=1100.
3963       OpCmode = 0xc;
3964       Imm = SplatBits >> 8;
3965       SplatBits |= 0xff;
3966       break;
3967     }
3968
3969     if ((SplatBits & ~0xffffff) == 0 &&
3970         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
3971       // Value = 0x00nnffff: Op=x, Cmode=1101.
3972       OpCmode = 0xd;
3973       Imm = SplatBits >> 16;
3974       SplatBits |= 0xffff;
3975       break;
3976     }
3977
3978     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
3979     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
3980     // VMOV.I32.  A (very) minor optimization would be to replicate the value
3981     // and fall through here to test for a valid 64-bit splat.  But, then the
3982     // caller would also need to check and handle the change in size.
3983     return SDValue();
3984
3985   case 64: {
3986     if (type != VMOVModImm)
3987       return SDValue();
3988     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
3989     uint64_t BitMask = 0xff;
3990     uint64_t Val = 0;
3991     unsigned ImmMask = 1;
3992     Imm = 0;
3993     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
3994       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
3995         Val |= BitMask;
3996         Imm |= ImmMask;
3997       } else if ((SplatBits & BitMask) != 0) {
3998         return SDValue();
3999       }
4000       BitMask <<= 8;
4001       ImmMask <<= 1;
4002     }
4003     // Op=1, Cmode=1110.
4004     OpCmode = 0x1e;
4005     SplatBits = Val;
4006     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4007     break;
4008   }
4009
4010   default:
4011     llvm_unreachable("unexpected size for isNEONModifiedImm");
4012   }
4013
4014   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4015   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4016 }
4017
4018 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4019                                            const ARMSubtarget *ST) const {
4020   if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
4021     return SDValue();
4022
4023   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4024   assert(Op.getValueType() == MVT::f32 &&
4025          "ConstantFP custom lowering should only occur for f32.");
4026
4027   // Try splatting with a VMOV.f32...
4028   APFloat FPVal = CFP->getValueAPF();
4029   int ImmVal = ARM_AM::getFP32Imm(FPVal);
4030   if (ImmVal != -1) {
4031     DebugLoc DL = Op.getDebugLoc();
4032     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4033     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4034                                       NewVal);
4035     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4036                        DAG.getConstant(0, MVT::i32));
4037   }
4038
4039   // If that fails, try a VMOV.i32
4040   EVT VMovVT;
4041   unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
4042   SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
4043                                      VMOVModImm);
4044   if (NewVal != SDValue()) {
4045     DebugLoc DL = Op.getDebugLoc();
4046     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4047                                       NewVal);
4048     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4049                                        VecConstant);
4050     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4051                        DAG.getConstant(0, MVT::i32));
4052   }
4053
4054   // Finally, try a VMVN.i32
4055   NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
4056                              VMVNModImm);
4057   if (NewVal != SDValue()) {
4058     DebugLoc DL = Op.getDebugLoc();
4059     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4060     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4061                                        VecConstant);
4062     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4063                        DAG.getConstant(0, MVT::i32));
4064   }
4065
4066   return SDValue();
4067 }
4068
4069 // check if an VEXT instruction can handle the shuffle mask when the
4070 // vector sources of the shuffle are the same.
4071 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4072   unsigned NumElts = VT.getVectorNumElements();
4073
4074   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4075   if (M[0] < 0)
4076     return false;
4077
4078   Imm = M[0];
4079
4080   // If this is a VEXT shuffle, the immediate value is the index of the first
4081   // element.  The other shuffle indices must be the successive elements after
4082   // the first one.
4083   unsigned ExpectedElt = Imm;
4084   for (unsigned i = 1; i < NumElts; ++i) {
4085     // Increment the expected index.  If it wraps around, just follow it
4086     // back to index zero and keep going.
4087     ++ExpectedElt;
4088     if (ExpectedElt == NumElts)
4089       ExpectedElt = 0;
4090
4091     if (M[i] < 0) continue; // ignore UNDEF indices
4092     if (ExpectedElt != static_cast<unsigned>(M[i]))
4093       return false;
4094   }
4095
4096   return true;
4097 }
4098
4099
4100 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4101                        bool &ReverseVEXT, unsigned &Imm) {
4102   unsigned NumElts = VT.getVectorNumElements();
4103   ReverseVEXT = false;
4104
4105   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4106   if (M[0] < 0)
4107     return false;
4108
4109   Imm = M[0];
4110
4111   // If this is a VEXT shuffle, the immediate value is the index of the first
4112   // element.  The other shuffle indices must be the successive elements after
4113   // the first one.
4114   unsigned ExpectedElt = Imm;
4115   for (unsigned i = 1; i < NumElts; ++i) {
4116     // Increment the expected index.  If it wraps around, it may still be
4117     // a VEXT but the source vectors must be swapped.
4118     ExpectedElt += 1;
4119     if (ExpectedElt == NumElts * 2) {
4120       ExpectedElt = 0;
4121       ReverseVEXT = true;
4122     }
4123
4124     if (M[i] < 0) continue; // ignore UNDEF indices
4125     if (ExpectedElt != static_cast<unsigned>(M[i]))
4126       return false;
4127   }
4128
4129   // Adjust the index value if the source operands will be swapped.
4130   if (ReverseVEXT)
4131     Imm -= NumElts;
4132
4133   return true;
4134 }
4135
4136 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4137 /// instruction with the specified blocksize.  (The order of the elements
4138 /// within each block of the vector is reversed.)
4139 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4140   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4141          "Only possible block sizes for VREV are: 16, 32, 64");
4142
4143   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4144   if (EltSz == 64)
4145     return false;
4146
4147   unsigned NumElts = VT.getVectorNumElements();
4148   unsigned BlockElts = M[0] + 1;
4149   // If the first shuffle index is UNDEF, be optimistic.
4150   if (M[0] < 0)
4151     BlockElts = BlockSize / EltSz;
4152
4153   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4154     return false;
4155
4156   for (unsigned i = 0; i < NumElts; ++i) {
4157     if (M[i] < 0) continue; // ignore UNDEF indices
4158     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4159       return false;
4160   }
4161
4162   return true;
4163 }
4164
4165 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4166   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4167   // range, then 0 is placed into the resulting vector. So pretty much any mask
4168   // of 8 elements can work here.
4169   return VT == MVT::v8i8 && M.size() == 8;
4170 }
4171
4172 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4173   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4174   if (EltSz == 64)
4175     return false;
4176
4177   unsigned NumElts = VT.getVectorNumElements();
4178   WhichResult = (M[0] == 0 ? 0 : 1);
4179   for (unsigned i = 0; i < NumElts; i += 2) {
4180     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4181         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4182       return false;
4183   }
4184   return true;
4185 }
4186
4187 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4188 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4189 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4190 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4191   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4192   if (EltSz == 64)
4193     return false;
4194
4195   unsigned NumElts = VT.getVectorNumElements();
4196   WhichResult = (M[0] == 0 ? 0 : 1);
4197   for (unsigned i = 0; i < NumElts; i += 2) {
4198     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4199         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4200       return false;
4201   }
4202   return true;
4203 }
4204
4205 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4206   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4207   if (EltSz == 64)
4208     return false;
4209
4210   unsigned NumElts = VT.getVectorNumElements();
4211   WhichResult = (M[0] == 0 ? 0 : 1);
4212   for (unsigned i = 0; i != NumElts; ++i) {
4213     if (M[i] < 0) continue; // ignore UNDEF indices
4214     if ((unsigned) M[i] != 2 * i + WhichResult)
4215       return false;
4216   }
4217
4218   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4219   if (VT.is64BitVector() && EltSz == 32)
4220     return false;
4221
4222   return true;
4223 }
4224
4225 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4226 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4227 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4228 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4229   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4230   if (EltSz == 64)
4231     return false;
4232
4233   unsigned Half = VT.getVectorNumElements() / 2;
4234   WhichResult = (M[0] == 0 ? 0 : 1);
4235   for (unsigned j = 0; j != 2; ++j) {
4236     unsigned Idx = WhichResult;
4237     for (unsigned i = 0; i != Half; ++i) {
4238       int MIdx = M[i + j * Half];
4239       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4240         return false;
4241       Idx += 2;
4242     }
4243   }
4244
4245   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4246   if (VT.is64BitVector() && EltSz == 32)
4247     return false;
4248
4249   return true;
4250 }
4251
4252 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4253   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4254   if (EltSz == 64)
4255     return false;
4256
4257   unsigned NumElts = VT.getVectorNumElements();
4258   WhichResult = (M[0] == 0 ? 0 : 1);
4259   unsigned Idx = WhichResult * NumElts / 2;
4260   for (unsigned i = 0; i != NumElts; i += 2) {
4261     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4262         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4263       return false;
4264     Idx += 1;
4265   }
4266
4267   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4268   if (VT.is64BitVector() && EltSz == 32)
4269     return false;
4270
4271   return true;
4272 }
4273
4274 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4275 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4276 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4277 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4278   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4279   if (EltSz == 64)
4280     return false;
4281
4282   unsigned NumElts = VT.getVectorNumElements();
4283   WhichResult = (M[0] == 0 ? 0 : 1);
4284   unsigned Idx = WhichResult * NumElts / 2;
4285   for (unsigned i = 0; i != NumElts; i += 2) {
4286     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4287         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4288       return false;
4289     Idx += 1;
4290   }
4291
4292   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4293   if (VT.is64BitVector() && EltSz == 32)
4294     return false;
4295
4296   return true;
4297 }
4298
4299 // If N is an integer constant that can be moved into a register in one
4300 // instruction, return an SDValue of such a constant (will become a MOV
4301 // instruction).  Otherwise return null.
4302 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4303                                      const ARMSubtarget *ST, DebugLoc dl) {
4304   uint64_t Val;
4305   if (!isa<ConstantSDNode>(N))
4306     return SDValue();
4307   Val = cast<ConstantSDNode>(N)->getZExtValue();
4308
4309   if (ST->isThumb1Only()) {
4310     if (Val <= 255 || ~Val <= 255)
4311       return DAG.getConstant(Val, MVT::i32);
4312   } else {
4313     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4314       return DAG.getConstant(Val, MVT::i32);
4315   }
4316   return SDValue();
4317 }
4318
4319 // If this is a case we can't handle, return null and let the default
4320 // expansion code take care of it.
4321 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4322                                              const ARMSubtarget *ST) const {
4323   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4324   DebugLoc dl = Op.getDebugLoc();
4325   EVT VT = Op.getValueType();
4326
4327   APInt SplatBits, SplatUndef;
4328   unsigned SplatBitSize;
4329   bool HasAnyUndefs;
4330   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4331     if (SplatBitSize <= 64) {
4332       // Check if an immediate VMOV works.
4333       EVT VmovVT;
4334       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4335                                       SplatUndef.getZExtValue(), SplatBitSize,
4336                                       DAG, VmovVT, VT.is128BitVector(),
4337                                       VMOVModImm);
4338       if (Val.getNode()) {
4339         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4340         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4341       }
4342
4343       // Try an immediate VMVN.
4344       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4345       Val = isNEONModifiedImm(NegatedImm,
4346                                       SplatUndef.getZExtValue(), SplatBitSize,
4347                                       DAG, VmovVT, VT.is128BitVector(),
4348                                       VMVNModImm);
4349       if (Val.getNode()) {
4350         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4351         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4352       }
4353
4354       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4355       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4356         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4357         if (ImmVal != -1) {
4358           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4359           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4360         }
4361       }
4362     }
4363   }
4364
4365   // Scan through the operands to see if only one value is used.
4366   //
4367   // As an optimisation, even if more than one value is used it may be more
4368   // profitable to splat with one value then change some lanes.
4369   //
4370   // Heuristically we decide to do this if the vector has a "dominant" value,
4371   // defined as splatted to more than half of the lanes.
4372   unsigned NumElts = VT.getVectorNumElements();
4373   bool isOnlyLowElement = true;
4374   bool usesOnlyOneValue = true;
4375   bool hasDominantValue = false;
4376   bool isConstant = true;
4377
4378   // Map of the number of times a particular SDValue appears in the
4379   // element list.
4380   DenseMap<SDValue, unsigned> ValueCounts;
4381   SDValue Value;
4382   for (unsigned i = 0; i < NumElts; ++i) {
4383     SDValue V = Op.getOperand(i);
4384     if (V.getOpcode() == ISD::UNDEF)
4385       continue;
4386     if (i > 0)
4387       isOnlyLowElement = false;
4388     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4389       isConstant = false;
4390
4391     ValueCounts.insert(std::make_pair(V, 0));
4392     unsigned &Count = ValueCounts[V];
4393     
4394     // Is this value dominant? (takes up more than half of the lanes)
4395     if (++Count > (NumElts / 2)) {
4396       hasDominantValue = true;
4397       Value = V;
4398     }
4399   }
4400   if (ValueCounts.size() != 1)
4401     usesOnlyOneValue = false;
4402   if (!Value.getNode() && ValueCounts.size() > 0)
4403     Value = ValueCounts.begin()->first;
4404
4405   if (ValueCounts.size() == 0)
4406     return DAG.getUNDEF(VT);
4407
4408   if (isOnlyLowElement)
4409     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4410
4411   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4412
4413   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4414   // i32 and try again.
4415   if (hasDominantValue && EltSize <= 32) {
4416     if (!isConstant) {
4417       SDValue N;
4418
4419       // If we are VDUPing a value that comes directly from a vector, that will
4420       // cause an unnecessary move to and from a GPR, where instead we could
4421       // just use VDUPLANE.
4422       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
4423         // We need to create a new undef vector to use for the VDUPLANE if the
4424         // size of the vector from which we get the value is different than the
4425         // size of the vector that we need to create. We will insert the element
4426         // such that the register coalescer will remove unnecessary copies.
4427         if (VT != Value->getOperand(0).getValueType()) {
4428           ConstantSDNode *constIndex;
4429           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4430           assert(constIndex && "The index is not a constant!");
4431           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4432                              VT.getVectorNumElements();
4433           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4434                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4435                         Value, DAG.getConstant(index, MVT::i32)),
4436                            DAG.getConstant(index, MVT::i32));
4437         } else {
4438           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4439                         Value->getOperand(0), Value->getOperand(1));
4440         }
4441       }
4442       else
4443         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4444
4445       if (!usesOnlyOneValue) {
4446         // The dominant value was splatted as 'N', but we now have to insert
4447         // all differing elements.
4448         for (unsigned I = 0; I < NumElts; ++I) {
4449           if (Op.getOperand(I) == Value)
4450             continue;
4451           SmallVector<SDValue, 3> Ops;
4452           Ops.push_back(N);
4453           Ops.push_back(Op.getOperand(I));
4454           Ops.push_back(DAG.getConstant(I, MVT::i32));
4455           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4456         }
4457       }
4458       return N;
4459     }
4460     if (VT.getVectorElementType().isFloatingPoint()) {
4461       SmallVector<SDValue, 8> Ops;
4462       for (unsigned i = 0; i < NumElts; ++i)
4463         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4464                                   Op.getOperand(i)));
4465       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4466       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4467       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4468       if (Val.getNode())
4469         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4470     }
4471     if (usesOnlyOneValue) {
4472       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4473       if (isConstant && Val.getNode())
4474         return DAG.getNode(ARMISD::VDUP, dl, VT, Val); 
4475     }
4476   }
4477
4478   // If all elements are constants and the case above didn't get hit, fall back
4479   // to the default expansion, which will generate a load from the constant
4480   // pool.
4481   if (isConstant)
4482     return SDValue();
4483
4484   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4485   if (NumElts >= 4) {
4486     SDValue shuffle = ReconstructShuffle(Op, DAG);
4487     if (shuffle != SDValue())
4488       return shuffle;
4489   }
4490
4491   // Vectors with 32- or 64-bit elements can be built by directly assigning
4492   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4493   // will be legalized.
4494   if (EltSize >= 32) {
4495     // Do the expansion with floating-point types, since that is what the VFP
4496     // registers are defined to use, and since i64 is not legal.
4497     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4498     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4499     SmallVector<SDValue, 8> Ops;
4500     for (unsigned i = 0; i < NumElts; ++i)
4501       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4502     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4503     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4504   }
4505
4506   return SDValue();
4507 }
4508
4509 // Gather data to see if the operation can be modelled as a
4510 // shuffle in combination with VEXTs.
4511 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4512                                               SelectionDAG &DAG) const {
4513   DebugLoc dl = Op.getDebugLoc();
4514   EVT VT = Op.getValueType();
4515   unsigned NumElts = VT.getVectorNumElements();
4516
4517   SmallVector<SDValue, 2> SourceVecs;
4518   SmallVector<unsigned, 2> MinElts;
4519   SmallVector<unsigned, 2> MaxElts;
4520
4521   for (unsigned i = 0; i < NumElts; ++i) {
4522     SDValue V = Op.getOperand(i);
4523     if (V.getOpcode() == ISD::UNDEF)
4524       continue;
4525     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4526       // A shuffle can only come from building a vector from various
4527       // elements of other vectors.
4528       return SDValue();
4529     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4530                VT.getVectorElementType()) {
4531       // This code doesn't know how to handle shuffles where the vector
4532       // element types do not match (this happens because type legalization
4533       // promotes the return type of EXTRACT_VECTOR_ELT).
4534       // FIXME: It might be appropriate to extend this code to handle
4535       // mismatched types.
4536       return SDValue();
4537     }
4538
4539     // Record this extraction against the appropriate vector if possible...
4540     SDValue SourceVec = V.getOperand(0);
4541     // If the element number isn't a constant, we can't effectively
4542     // analyze what's going on.
4543     if (!isa<ConstantSDNode>(V.getOperand(1)))
4544       return SDValue();
4545     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4546     bool FoundSource = false;
4547     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4548       if (SourceVecs[j] == SourceVec) {
4549         if (MinElts[j] > EltNo)
4550           MinElts[j] = EltNo;
4551         if (MaxElts[j] < EltNo)
4552           MaxElts[j] = EltNo;
4553         FoundSource = true;
4554         break;
4555       }
4556     }
4557
4558     // Or record a new source if not...
4559     if (!FoundSource) {
4560       SourceVecs.push_back(SourceVec);
4561       MinElts.push_back(EltNo);
4562       MaxElts.push_back(EltNo);
4563     }
4564   }
4565
4566   // Currently only do something sane when at most two source vectors
4567   // involved.
4568   if (SourceVecs.size() > 2)
4569     return SDValue();
4570
4571   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4572   int VEXTOffsets[2] = {0, 0};
4573
4574   // This loop extracts the usage patterns of the source vectors
4575   // and prepares appropriate SDValues for a shuffle if possible.
4576   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4577     if (SourceVecs[i].getValueType() == VT) {
4578       // No VEXT necessary
4579       ShuffleSrcs[i] = SourceVecs[i];
4580       VEXTOffsets[i] = 0;
4581       continue;
4582     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4583       // It probably isn't worth padding out a smaller vector just to
4584       // break it down again in a shuffle.
4585       return SDValue();
4586     }
4587
4588     // Since only 64-bit and 128-bit vectors are legal on ARM and
4589     // we've eliminated the other cases...
4590     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4591            "unexpected vector sizes in ReconstructShuffle");
4592
4593     if (MaxElts[i] - MinElts[i] >= NumElts) {
4594       // Span too large for a VEXT to cope
4595       return SDValue();
4596     }
4597
4598     if (MinElts[i] >= NumElts) {
4599       // The extraction can just take the second half
4600       VEXTOffsets[i] = NumElts;
4601       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4602                                    SourceVecs[i],
4603                                    DAG.getIntPtrConstant(NumElts));
4604     } else if (MaxElts[i] < NumElts) {
4605       // The extraction can just take the first half
4606       VEXTOffsets[i] = 0;
4607       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4608                                    SourceVecs[i],
4609                                    DAG.getIntPtrConstant(0));
4610     } else {
4611       // An actual VEXT is needed
4612       VEXTOffsets[i] = MinElts[i];
4613       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4614                                      SourceVecs[i],
4615                                      DAG.getIntPtrConstant(0));
4616       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4617                                      SourceVecs[i],
4618                                      DAG.getIntPtrConstant(NumElts));
4619       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4620                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
4621     }
4622   }
4623
4624   SmallVector<int, 8> Mask;
4625
4626   for (unsigned i = 0; i < NumElts; ++i) {
4627     SDValue Entry = Op.getOperand(i);
4628     if (Entry.getOpcode() == ISD::UNDEF) {
4629       Mask.push_back(-1);
4630       continue;
4631     }
4632
4633     SDValue ExtractVec = Entry.getOperand(0);
4634     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4635                                           .getOperand(1))->getSExtValue();
4636     if (ExtractVec == SourceVecs[0]) {
4637       Mask.push_back(ExtractElt - VEXTOffsets[0]);
4638     } else {
4639       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4640     }
4641   }
4642
4643   // Final check before we try to produce nonsense...
4644   if (isShuffleMaskLegal(Mask, VT))
4645     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4646                                 &Mask[0]);
4647
4648   return SDValue();
4649 }
4650
4651 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4652 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4653 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4654 /// are assumed to be legal.
4655 bool
4656 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4657                                       EVT VT) const {
4658   if (VT.getVectorNumElements() == 4 &&
4659       (VT.is128BitVector() || VT.is64BitVector())) {
4660     unsigned PFIndexes[4];
4661     for (unsigned i = 0; i != 4; ++i) {
4662       if (M[i] < 0)
4663         PFIndexes[i] = 8;
4664       else
4665         PFIndexes[i] = M[i];
4666     }
4667
4668     // Compute the index in the perfect shuffle table.
4669     unsigned PFTableIndex =
4670       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4671     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4672     unsigned Cost = (PFEntry >> 30);
4673
4674     if (Cost <= 4)
4675       return true;
4676   }
4677
4678   bool ReverseVEXT;
4679   unsigned Imm, WhichResult;
4680
4681   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4682   return (EltSize >= 32 ||
4683           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4684           isVREVMask(M, VT, 64) ||
4685           isVREVMask(M, VT, 32) ||
4686           isVREVMask(M, VT, 16) ||
4687           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4688           isVTBLMask(M, VT) ||
4689           isVTRNMask(M, VT, WhichResult) ||
4690           isVUZPMask(M, VT, WhichResult) ||
4691           isVZIPMask(M, VT, WhichResult) ||
4692           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4693           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4694           isVZIP_v_undef_Mask(M, VT, WhichResult));
4695 }
4696
4697 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4698 /// the specified operations to build the shuffle.
4699 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4700                                       SDValue RHS, SelectionDAG &DAG,
4701                                       DebugLoc dl) {
4702   unsigned OpNum = (PFEntry >> 26) & 0x0F;
4703   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4704   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
4705
4706   enum {
4707     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4708     OP_VREV,
4709     OP_VDUP0,
4710     OP_VDUP1,
4711     OP_VDUP2,
4712     OP_VDUP3,
4713     OP_VEXT1,
4714     OP_VEXT2,
4715     OP_VEXT3,
4716     OP_VUZPL, // VUZP, left result
4717     OP_VUZPR, // VUZP, right result
4718     OP_VZIPL, // VZIP, left result
4719     OP_VZIPR, // VZIP, right result
4720     OP_VTRNL, // VTRN, left result
4721     OP_VTRNR  // VTRN, right result
4722   };
4723
4724   if (OpNum == OP_COPY) {
4725     if (LHSID == (1*9+2)*9+3) return LHS;
4726     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4727     return RHS;
4728   }
4729
4730   SDValue OpLHS, OpRHS;
4731   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4732   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4733   EVT VT = OpLHS.getValueType();
4734
4735   switch (OpNum) {
4736   default: llvm_unreachable("Unknown shuffle opcode!");
4737   case OP_VREV:
4738     // VREV divides the vector in half and swaps within the half.
4739     if (VT.getVectorElementType() == MVT::i32 ||
4740         VT.getVectorElementType() == MVT::f32)
4741       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4742     // vrev <4 x i16> -> VREV32
4743     if (VT.getVectorElementType() == MVT::i16)
4744       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4745     // vrev <4 x i8> -> VREV16
4746     assert(VT.getVectorElementType() == MVT::i8);
4747     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4748   case OP_VDUP0:
4749   case OP_VDUP1:
4750   case OP_VDUP2:
4751   case OP_VDUP3:
4752     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4753                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4754   case OP_VEXT1:
4755   case OP_VEXT2:
4756   case OP_VEXT3:
4757     return DAG.getNode(ARMISD::VEXT, dl, VT,
4758                        OpLHS, OpRHS,
4759                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4760   case OP_VUZPL:
4761   case OP_VUZPR:
4762     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4763                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4764   case OP_VZIPL:
4765   case OP_VZIPR:
4766     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4767                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4768   case OP_VTRNL:
4769   case OP_VTRNR:
4770     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4771                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4772   }
4773 }
4774
4775 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4776                                        ArrayRef<int> ShuffleMask,
4777                                        SelectionDAG &DAG) {
4778   // Check to see if we can use the VTBL instruction.
4779   SDValue V1 = Op.getOperand(0);
4780   SDValue V2 = Op.getOperand(1);
4781   DebugLoc DL = Op.getDebugLoc();
4782
4783   SmallVector<SDValue, 8> VTBLMask;
4784   for (ArrayRef<int>::iterator
4785          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
4786     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
4787
4788   if (V2.getNode()->getOpcode() == ISD::UNDEF)
4789     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
4790                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4791                                    &VTBLMask[0], 8));
4792
4793   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
4794                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4795                                  &VTBLMask[0], 8));
4796 }
4797
4798 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4799   SDValue V1 = Op.getOperand(0);
4800   SDValue V2 = Op.getOperand(1);
4801   DebugLoc dl = Op.getDebugLoc();
4802   EVT VT = Op.getValueType();
4803   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4804
4805   // Convert shuffles that are directly supported on NEON to target-specific
4806   // DAG nodes, instead of keeping them as shuffles and matching them again
4807   // during code selection.  This is more efficient and avoids the possibility
4808   // of inconsistencies between legalization and selection.
4809   // FIXME: floating-point vectors should be canonicalized to integer vectors
4810   // of the same time so that they get CSEd properly.
4811   ArrayRef<int> ShuffleMask = SVN->getMask();
4812
4813   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4814   if (EltSize <= 32) {
4815     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4816       int Lane = SVN->getSplatIndex();
4817       // If this is undef splat, generate it via "just" vdup, if possible.
4818       if (Lane == -1) Lane = 0;
4819
4820       // Test if V1 is a SCALAR_TO_VECTOR.
4821       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4822         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4823       }
4824       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
4825       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
4826       // reaches it).
4827       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
4828           !isa<ConstantSDNode>(V1.getOperand(0))) {
4829         bool IsScalarToVector = true;
4830         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
4831           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
4832             IsScalarToVector = false;
4833             break;
4834           }
4835         if (IsScalarToVector)
4836           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4837       }
4838       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
4839                          DAG.getConstant(Lane, MVT::i32));
4840     }
4841
4842     bool ReverseVEXT;
4843     unsigned Imm;
4844     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
4845       if (ReverseVEXT)
4846         std::swap(V1, V2);
4847       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
4848                          DAG.getConstant(Imm, MVT::i32));
4849     }
4850
4851     if (isVREVMask(ShuffleMask, VT, 64))
4852       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
4853     if (isVREVMask(ShuffleMask, VT, 32))
4854       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
4855     if (isVREVMask(ShuffleMask, VT, 16))
4856       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
4857
4858     if (V2->getOpcode() == ISD::UNDEF &&
4859         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
4860       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
4861                          DAG.getConstant(Imm, MVT::i32));
4862     }
4863
4864     // Check for Neon shuffles that modify both input vectors in place.
4865     // If both results are used, i.e., if there are two shuffles with the same
4866     // source operands and with masks corresponding to both results of one of
4867     // these operations, DAG memoization will ensure that a single node is
4868     // used for both shuffles.
4869     unsigned WhichResult;
4870     if (isVTRNMask(ShuffleMask, VT, WhichResult))
4871       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4872                          V1, V2).getValue(WhichResult);
4873     if (isVUZPMask(ShuffleMask, VT, WhichResult))
4874       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4875                          V1, V2).getValue(WhichResult);
4876     if (isVZIPMask(ShuffleMask, VT, WhichResult))
4877       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4878                          V1, V2).getValue(WhichResult);
4879
4880     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
4881       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4882                          V1, V1).getValue(WhichResult);
4883     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4884       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4885                          V1, V1).getValue(WhichResult);
4886     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4887       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4888                          V1, V1).getValue(WhichResult);
4889   }
4890
4891   // If the shuffle is not directly supported and it has 4 elements, use
4892   // the PerfectShuffle-generated table to synthesize it from other shuffles.
4893   unsigned NumElts = VT.getVectorNumElements();
4894   if (NumElts == 4) {
4895     unsigned PFIndexes[4];
4896     for (unsigned i = 0; i != 4; ++i) {
4897       if (ShuffleMask[i] < 0)
4898         PFIndexes[i] = 8;
4899       else
4900         PFIndexes[i] = ShuffleMask[i];
4901     }
4902
4903     // Compute the index in the perfect shuffle table.
4904     unsigned PFTableIndex =
4905       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4906     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4907     unsigned Cost = (PFEntry >> 30);
4908
4909     if (Cost <= 4)
4910       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4911   }
4912
4913   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
4914   if (EltSize >= 32) {
4915     // Do the expansion with floating-point types, since that is what the VFP
4916     // registers are defined to use, and since i64 is not legal.
4917     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4918     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4919     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
4920     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
4921     SmallVector<SDValue, 8> Ops;
4922     for (unsigned i = 0; i < NumElts; ++i) {
4923       if (ShuffleMask[i] < 0)
4924         Ops.push_back(DAG.getUNDEF(EltVT));
4925       else
4926         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
4927                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
4928                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
4929                                                   MVT::i32)));
4930     }
4931     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4932     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4933   }
4934
4935   if (VT == MVT::v8i8) {
4936     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
4937     if (NewOp.getNode())
4938       return NewOp;
4939   }
4940
4941   return SDValue();
4942 }
4943
4944 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4945   // INSERT_VECTOR_ELT is legal only for immediate indexes.
4946   SDValue Lane = Op.getOperand(2);
4947   if (!isa<ConstantSDNode>(Lane))
4948     return SDValue();
4949
4950   return Op;
4951 }
4952
4953 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4954   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
4955   SDValue Lane = Op.getOperand(1);
4956   if (!isa<ConstantSDNode>(Lane))
4957     return SDValue();
4958
4959   SDValue Vec = Op.getOperand(0);
4960   if (Op.getValueType() == MVT::i32 &&
4961       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
4962     DebugLoc dl = Op.getDebugLoc();
4963     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
4964   }
4965
4966   return Op;
4967 }
4968
4969 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
4970   // The only time a CONCAT_VECTORS operation can have legal types is when
4971   // two 64-bit vectors are concatenated to a 128-bit vector.
4972   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
4973          "unexpected CONCAT_VECTORS");
4974   DebugLoc dl = Op.getDebugLoc();
4975   SDValue Val = DAG.getUNDEF(MVT::v2f64);
4976   SDValue Op0 = Op.getOperand(0);
4977   SDValue Op1 = Op.getOperand(1);
4978   if (Op0.getOpcode() != ISD::UNDEF)
4979     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4980                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
4981                       DAG.getIntPtrConstant(0));
4982   if (Op1.getOpcode() != ISD::UNDEF)
4983     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4984                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
4985                       DAG.getIntPtrConstant(1));
4986   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
4987 }
4988
4989 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
4990 /// element has been zero/sign-extended, depending on the isSigned parameter,
4991 /// from an integer type half its size.
4992 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
4993                                    bool isSigned) {
4994   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
4995   EVT VT = N->getValueType(0);
4996   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
4997     SDNode *BVN = N->getOperand(0).getNode();
4998     if (BVN->getValueType(0) != MVT::v4i32 ||
4999         BVN->getOpcode() != ISD::BUILD_VECTOR)
5000       return false;
5001     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5002     unsigned HiElt = 1 - LoElt;
5003     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5004     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5005     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5006     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5007     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5008       return false;
5009     if (isSigned) {
5010       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5011           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5012         return true;
5013     } else {
5014       if (Hi0->isNullValue() && Hi1->isNullValue())
5015         return true;
5016     }
5017     return false;
5018   }
5019
5020   if (N->getOpcode() != ISD::BUILD_VECTOR)
5021     return false;
5022
5023   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5024     SDNode *Elt = N->getOperand(i).getNode();
5025     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5026       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5027       unsigned HalfSize = EltSize / 2;
5028       if (isSigned) {
5029         if (!isIntN(HalfSize, C->getSExtValue()))
5030           return false;
5031       } else {
5032         if (!isUIntN(HalfSize, C->getZExtValue()))
5033           return false;
5034       }
5035       continue;
5036     }
5037     return false;
5038   }
5039
5040   return true;
5041 }
5042
5043 /// isSignExtended - Check if a node is a vector value that is sign-extended
5044 /// or a constant BUILD_VECTOR with sign-extended elements.
5045 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5046   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5047     return true;
5048   if (isExtendedBUILD_VECTOR(N, DAG, true))
5049     return true;
5050   return false;
5051 }
5052
5053 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5054 /// or a constant BUILD_VECTOR with zero-extended elements.
5055 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5056   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5057     return true;
5058   if (isExtendedBUILD_VECTOR(N, DAG, false))
5059     return true;
5060   return false;
5061 }
5062
5063 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5064 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5065 /// We insert the required extension here to get the vector to fill a D register.
5066 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5067                                             const EVT &OrigTy,
5068                                             const EVT &ExtTy,
5069                                             unsigned ExtOpcode) {
5070   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5071   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5072   // 64-bits we need to insert a new extension so that it will be 64-bits.
5073   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5074   if (OrigTy.getSizeInBits() >= 64)
5075     return N;
5076
5077   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5078   MVT::SimpleValueType OrigSimpleTy = OrigTy.getSimpleVT().SimpleTy;
5079   EVT NewVT;
5080   switch (OrigSimpleTy) {
5081   default: llvm_unreachable("Unexpected Orig Vector Type");
5082   case MVT::v2i8:
5083   case MVT::v2i16:
5084     NewVT = MVT::v2i32;
5085     break;
5086   case MVT::v4i8:
5087     NewVT = MVT::v4i16;
5088     break;
5089   }
5090   return DAG.getNode(ExtOpcode, N->getDebugLoc(), NewVT, N);
5091 }
5092
5093 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5094 /// does not do any sign/zero extension. If the original vector is less
5095 /// than 64 bits, an appropriate extension will be added after the load to
5096 /// reach a total size of 64 bits. We have to add the extension separately
5097 /// because ARM does not have a sign/zero extending load for vectors.
5098 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5099   SDValue NonExtendingLoad =
5100     DAG.getLoad(LD->getMemoryVT(), LD->getDebugLoc(), LD->getChain(),
5101                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5102                 LD->isNonTemporal(), LD->isInvariant(),
5103                 LD->getAlignment());
5104   unsigned ExtOp = 0;
5105   switch (LD->getExtensionType()) {
5106   default: llvm_unreachable("Unexpected LoadExtType");
5107   case ISD::EXTLOAD:
5108   case ISD::SEXTLOAD: ExtOp = ISD::SIGN_EXTEND; break;
5109   case ISD::ZEXTLOAD: ExtOp = ISD::ZERO_EXTEND; break;
5110   }
5111   MVT::SimpleValueType MemType = LD->getMemoryVT().getSimpleVT().SimpleTy;
5112   MVT::SimpleValueType ExtType = LD->getValueType(0).getSimpleVT().SimpleTy;
5113   return AddRequiredExtensionForVMULL(NonExtendingLoad, DAG,
5114                                       MemType, ExtType, ExtOp);
5115 }
5116
5117 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5118 /// extending load, or BUILD_VECTOR with extended elements, return the
5119 /// unextended value. The unextended vector should be 64 bits so that it can
5120 /// be used as an operand to a VMULL instruction. If the original vector size
5121 /// before extension is less than 64 bits we add a an extension to resize
5122 /// the vector to 64 bits.
5123 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5124   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5125     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5126                                         N->getOperand(0)->getValueType(0),
5127                                         N->getValueType(0),
5128                                         N->getOpcode());
5129
5130   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5131     return SkipLoadExtensionForVMULL(LD, DAG);
5132
5133   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5134   // have been legalized as a BITCAST from v4i32.
5135   if (N->getOpcode() == ISD::BITCAST) {
5136     SDNode *BVN = N->getOperand(0).getNode();
5137     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5138            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5139     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5140     return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
5141                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5142   }
5143   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5144   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5145   EVT VT = N->getValueType(0);
5146   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5147   unsigned NumElts = VT.getVectorNumElements();
5148   MVT TruncVT = MVT::getIntegerVT(EltSize);
5149   SmallVector<SDValue, 8> Ops;
5150   for (unsigned i = 0; i != NumElts; ++i) {
5151     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5152     const APInt &CInt = C->getAPIntValue();
5153     // Element types smaller than 32 bits are not legal, so use i32 elements.
5154     // The values are implicitly truncated so sext vs. zext doesn't matter.
5155     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5156   }
5157   return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
5158                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5159 }
5160
5161 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5162   unsigned Opcode = N->getOpcode();
5163   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5164     SDNode *N0 = N->getOperand(0).getNode();
5165     SDNode *N1 = N->getOperand(1).getNode();
5166     return N0->hasOneUse() && N1->hasOneUse() &&
5167       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5168   }
5169   return false;
5170 }
5171
5172 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5173   unsigned Opcode = N->getOpcode();
5174   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5175     SDNode *N0 = N->getOperand(0).getNode();
5176     SDNode *N1 = N->getOperand(1).getNode();
5177     return N0->hasOneUse() && N1->hasOneUse() &&
5178       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5179   }
5180   return false;
5181 }
5182
5183 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5184   // Multiplications are only custom-lowered for 128-bit vectors so that
5185   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5186   EVT VT = Op.getValueType();
5187   assert(VT.is128BitVector() && VT.isInteger() &&
5188          "unexpected type for custom-lowering ISD::MUL");
5189   SDNode *N0 = Op.getOperand(0).getNode();
5190   SDNode *N1 = Op.getOperand(1).getNode();
5191   unsigned NewOpc = 0;
5192   bool isMLA = false;
5193   bool isN0SExt = isSignExtended(N0, DAG);
5194   bool isN1SExt = isSignExtended(N1, DAG);
5195   if (isN0SExt && isN1SExt)
5196     NewOpc = ARMISD::VMULLs;
5197   else {
5198     bool isN0ZExt = isZeroExtended(N0, DAG);
5199     bool isN1ZExt = isZeroExtended(N1, DAG);
5200     if (isN0ZExt && isN1ZExt)
5201       NewOpc = ARMISD::VMULLu;
5202     else if (isN1SExt || isN1ZExt) {
5203       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5204       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5205       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5206         NewOpc = ARMISD::VMULLs;
5207         isMLA = true;
5208       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5209         NewOpc = ARMISD::VMULLu;
5210         isMLA = true;
5211       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5212         std::swap(N0, N1);
5213         NewOpc = ARMISD::VMULLu;
5214         isMLA = true;
5215       }
5216     }
5217
5218     if (!NewOpc) {
5219       if (VT == MVT::v2i64)
5220         // Fall through to expand this.  It is not legal.
5221         return SDValue();
5222       else
5223         // Other vector multiplications are legal.
5224         return Op;
5225     }
5226   }
5227
5228   // Legalize to a VMULL instruction.
5229   DebugLoc DL = Op.getDebugLoc();
5230   SDValue Op0;
5231   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5232   if (!isMLA) {
5233     Op0 = SkipExtensionForVMULL(N0, DAG);
5234     assert(Op0.getValueType().is64BitVector() &&
5235            Op1.getValueType().is64BitVector() &&
5236            "unexpected types for extended operands to VMULL");
5237     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5238   }
5239
5240   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5241   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5242   //   vmull q0, d4, d6
5243   //   vmlal q0, d5, d6
5244   // is faster than
5245   //   vaddl q0, d4, d5
5246   //   vmovl q1, d6
5247   //   vmul  q0, q0, q1
5248   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5249   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5250   EVT Op1VT = Op1.getValueType();
5251   return DAG.getNode(N0->getOpcode(), DL, VT,
5252                      DAG.getNode(NewOpc, DL, VT,
5253                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5254                      DAG.getNode(NewOpc, DL, VT,
5255                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5256 }
5257
5258 static SDValue
5259 LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
5260   // Convert to float
5261   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5262   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5263   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5264   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5265   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5266   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5267   // Get reciprocal estimate.
5268   // float4 recip = vrecpeq_f32(yf);
5269   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5270                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5271   // Because char has a smaller range than uchar, we can actually get away
5272   // without any newton steps.  This requires that we use a weird bias
5273   // of 0xb000, however (again, this has been exhaustively tested).
5274   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5275   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5276   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5277   Y = DAG.getConstant(0xb000, MVT::i32);
5278   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5279   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5280   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5281   // Convert back to short.
5282   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5283   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5284   return X;
5285 }
5286
5287 static SDValue
5288 LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
5289   SDValue N2;
5290   // Convert to float.
5291   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5292   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5293   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5294   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5295   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5296   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5297
5298   // Use reciprocal estimate and one refinement step.
5299   // float4 recip = vrecpeq_f32(yf);
5300   // recip *= vrecpsq_f32(yf, recip);
5301   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5302                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5303   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5304                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5305                    N1, N2);
5306   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5307   // Because short has a smaller range than ushort, we can actually get away
5308   // with only a single newton step.  This requires that we use a weird bias
5309   // of 89, however (again, this has been exhaustively tested).
5310   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5311   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5312   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5313   N1 = DAG.getConstant(0x89, MVT::i32);
5314   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5315   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5316   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5317   // Convert back to integer and return.
5318   // return vmovn_s32(vcvt_s32_f32(result));
5319   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5320   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5321   return N0;
5322 }
5323
5324 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5325   EVT VT = Op.getValueType();
5326   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5327          "unexpected type for custom-lowering ISD::SDIV");
5328
5329   DebugLoc dl = Op.getDebugLoc();
5330   SDValue N0 = Op.getOperand(0);
5331   SDValue N1 = Op.getOperand(1);
5332   SDValue N2, N3;
5333
5334   if (VT == MVT::v8i8) {
5335     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5336     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5337
5338     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5339                      DAG.getIntPtrConstant(4));
5340     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5341                      DAG.getIntPtrConstant(4));
5342     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5343                      DAG.getIntPtrConstant(0));
5344     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5345                      DAG.getIntPtrConstant(0));
5346
5347     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5348     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5349
5350     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5351     N0 = LowerCONCAT_VECTORS(N0, DAG);
5352
5353     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5354     return N0;
5355   }
5356   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5357 }
5358
5359 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5360   EVT VT = Op.getValueType();
5361   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5362          "unexpected type for custom-lowering ISD::UDIV");
5363
5364   DebugLoc dl = Op.getDebugLoc();
5365   SDValue N0 = Op.getOperand(0);
5366   SDValue N1 = Op.getOperand(1);
5367   SDValue N2, N3;
5368
5369   if (VT == MVT::v8i8) {
5370     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5371     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5372
5373     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5374                      DAG.getIntPtrConstant(4));
5375     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5376                      DAG.getIntPtrConstant(4));
5377     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5378                      DAG.getIntPtrConstant(0));
5379     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5380                      DAG.getIntPtrConstant(0));
5381
5382     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5383     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5384
5385     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5386     N0 = LowerCONCAT_VECTORS(N0, DAG);
5387
5388     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5389                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5390                      N0);
5391     return N0;
5392   }
5393
5394   // v4i16 sdiv ... Convert to float.
5395   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5396   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5397   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5398   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5399   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5400   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5401
5402   // Use reciprocal estimate and two refinement steps.
5403   // float4 recip = vrecpeq_f32(yf);
5404   // recip *= vrecpsq_f32(yf, recip);
5405   // recip *= vrecpsq_f32(yf, recip);
5406   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5407                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5408   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5409                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5410                    BN1, N2);
5411   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5412   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5413                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5414                    BN1, N2);
5415   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5416   // Simply multiplying by the reciprocal estimate can leave us a few ulps
5417   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5418   // and that it will never cause us to return an answer too large).
5419   // float4 result = as_float4(as_int4(xf*recip) + 2);
5420   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5421   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5422   N1 = DAG.getConstant(2, MVT::i32);
5423   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5424   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5425   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5426   // Convert back to integer and return.
5427   // return vmovn_u32(vcvt_s32_f32(result));
5428   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5429   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5430   return N0;
5431 }
5432
5433 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5434   EVT VT = Op.getNode()->getValueType(0);
5435   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5436
5437   unsigned Opc;
5438   bool ExtraOp = false;
5439   switch (Op.getOpcode()) {
5440   default: llvm_unreachable("Invalid code");
5441   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5442   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5443   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5444   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5445   }
5446
5447   if (!ExtraOp)
5448     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5449                        Op.getOperand(1));
5450   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5451                      Op.getOperand(1), Op.getOperand(2));
5452 }
5453
5454 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5455   // Monotonic load/store is legal for all targets
5456   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5457     return Op;
5458
5459   // Aquire/Release load/store is not legal for targets without a
5460   // dmb or equivalent available.
5461   return SDValue();
5462 }
5463
5464
5465 static void
5466 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5467                     SelectionDAG &DAG, unsigned NewOp) {
5468   DebugLoc dl = Node->getDebugLoc();
5469   assert (Node->getValueType(0) == MVT::i64 &&
5470           "Only know how to expand i64 atomics");
5471
5472   SmallVector<SDValue, 6> Ops;
5473   Ops.push_back(Node->getOperand(0)); // Chain
5474   Ops.push_back(Node->getOperand(1)); // Ptr
5475   // Low part of Val1
5476   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5477                             Node->getOperand(2), DAG.getIntPtrConstant(0)));
5478   // High part of Val1
5479   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5480                             Node->getOperand(2), DAG.getIntPtrConstant(1)));
5481   if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5482     // High part of Val1
5483     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5484                               Node->getOperand(3), DAG.getIntPtrConstant(0)));
5485     // High part of Val2
5486     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5487                               Node->getOperand(3), DAG.getIntPtrConstant(1)));
5488   }
5489   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5490   SDValue Result =
5491     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5492                             cast<MemSDNode>(Node)->getMemOperand());
5493   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5494   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5495   Results.push_back(Result.getValue(2));
5496 }
5497
5498 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5499   switch (Op.getOpcode()) {
5500   default: llvm_unreachable("Don't know how to custom lower this!");
5501   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
5502   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
5503   case ISD::GlobalAddress:
5504     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5505       LowerGlobalAddressELF(Op, DAG);
5506   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5507   case ISD::SELECT:        return LowerSELECT(Op, DAG);
5508   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
5509   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
5510   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
5511   case ISD::VASTART:       return LowerVASTART(Op, DAG);
5512   case ISD::MEMBARRIER:    return LowerMEMBARRIER(Op, DAG, Subtarget);
5513   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5514   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
5515   case ISD::SINT_TO_FP:
5516   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
5517   case ISD::FP_TO_SINT:
5518   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
5519   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
5520   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
5521   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
5522   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5523   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5524   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5525   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5526                                                                Subtarget);
5527   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
5528   case ISD::SHL:
5529   case ISD::SRL:
5530   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
5531   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
5532   case ISD::SRL_PARTS:
5533   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
5534   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5535   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
5536   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
5537   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
5538   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5539   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5540   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5541   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5542   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5543   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
5544   case ISD::MUL:           return LowerMUL(Op, DAG);
5545   case ISD::SDIV:          return LowerSDIV(Op, DAG);
5546   case ISD::UDIV:          return LowerUDIV(Op, DAG);
5547   case ISD::ADDC:
5548   case ISD::ADDE:
5549   case ISD::SUBC:
5550   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5551   case ISD::ATOMIC_LOAD:
5552   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
5553   }
5554 }
5555
5556 /// ReplaceNodeResults - Replace the results of node with an illegal result
5557 /// type with new values built out of custom code.
5558 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5559                                            SmallVectorImpl<SDValue>&Results,
5560                                            SelectionDAG &DAG) const {
5561   SDValue Res;
5562   switch (N->getOpcode()) {
5563   default:
5564     llvm_unreachable("Don't know how to custom expand this!");
5565   case ISD::BITCAST:
5566     Res = ExpandBITCAST(N, DAG);
5567     break;
5568   case ISD::SRL:
5569   case ISD::SRA:
5570     Res = Expand64BitShift(N, DAG, Subtarget);
5571     break;
5572   case ISD::ATOMIC_LOAD_ADD:
5573     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5574     return;
5575   case ISD::ATOMIC_LOAD_AND:
5576     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5577     return;
5578   case ISD::ATOMIC_LOAD_NAND:
5579     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5580     return;
5581   case ISD::ATOMIC_LOAD_OR:
5582     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5583     return;
5584   case ISD::ATOMIC_LOAD_SUB:
5585     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5586     return;
5587   case ISD::ATOMIC_LOAD_XOR:
5588     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5589     return;
5590   case ISD::ATOMIC_SWAP:
5591     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5592     return;
5593   case ISD::ATOMIC_CMP_SWAP:
5594     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5595     return;
5596   case ISD::ATOMIC_LOAD_MIN:
5597     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMIN64_DAG);
5598     return;
5599   case ISD::ATOMIC_LOAD_UMIN:
5600     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMIN64_DAG);
5601     return;
5602   case ISD::ATOMIC_LOAD_MAX:
5603     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMAX64_DAG);
5604     return;
5605   case ISD::ATOMIC_LOAD_UMAX:
5606     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMAX64_DAG);
5607     return;
5608   }
5609   if (Res.getNode())
5610     Results.push_back(Res);
5611 }
5612
5613 //===----------------------------------------------------------------------===//
5614 //                           ARM Scheduler Hooks
5615 //===----------------------------------------------------------------------===//
5616
5617 MachineBasicBlock *
5618 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5619                                      MachineBasicBlock *BB,
5620                                      unsigned Size) const {
5621   unsigned dest    = MI->getOperand(0).getReg();
5622   unsigned ptr     = MI->getOperand(1).getReg();
5623   unsigned oldval  = MI->getOperand(2).getReg();
5624   unsigned newval  = MI->getOperand(3).getReg();
5625   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5626   DebugLoc dl = MI->getDebugLoc();
5627   bool isThumb2 = Subtarget->isThumb2();
5628
5629   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5630   unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
5631     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5632     (const TargetRegisterClass*)&ARM::GPRRegClass);
5633
5634   if (isThumb2) {
5635     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5636     MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
5637     MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
5638   }
5639
5640   unsigned ldrOpc, strOpc;
5641   switch (Size) {
5642   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5643   case 1:
5644     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5645     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5646     break;
5647   case 2:
5648     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5649     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5650     break;
5651   case 4:
5652     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5653     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5654     break;
5655   }
5656
5657   MachineFunction *MF = BB->getParent();
5658   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5659   MachineFunction::iterator It = BB;
5660   ++It; // insert the new blocks after the current block
5661
5662   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5663   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5664   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5665   MF->insert(It, loop1MBB);
5666   MF->insert(It, loop2MBB);
5667   MF->insert(It, exitMBB);
5668
5669   // Transfer the remainder of BB and its successor edges to exitMBB.
5670   exitMBB->splice(exitMBB->begin(), BB,
5671                   llvm::next(MachineBasicBlock::iterator(MI)),
5672                   BB->end());
5673   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5674
5675   //  thisMBB:
5676   //   ...
5677   //   fallthrough --> loop1MBB
5678   BB->addSuccessor(loop1MBB);
5679
5680   // loop1MBB:
5681   //   ldrex dest, [ptr]
5682   //   cmp dest, oldval
5683   //   bne exitMBB
5684   BB = loop1MBB;
5685   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5686   if (ldrOpc == ARM::t2LDREX)
5687     MIB.addImm(0);
5688   AddDefaultPred(MIB);
5689   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5690                  .addReg(dest).addReg(oldval));
5691   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5692     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5693   BB->addSuccessor(loop2MBB);
5694   BB->addSuccessor(exitMBB);
5695
5696   // loop2MBB:
5697   //   strex scratch, newval, [ptr]
5698   //   cmp scratch, #0
5699   //   bne loop1MBB
5700   BB = loop2MBB;
5701   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5702   if (strOpc == ARM::t2STREX)
5703     MIB.addImm(0);
5704   AddDefaultPred(MIB);
5705   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5706                  .addReg(scratch).addImm(0));
5707   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5708     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5709   BB->addSuccessor(loop1MBB);
5710   BB->addSuccessor(exitMBB);
5711
5712   //  exitMBB:
5713   //   ...
5714   BB = exitMBB;
5715
5716   MI->eraseFromParent();   // The instruction is gone now.
5717
5718   return BB;
5719 }
5720
5721 MachineBasicBlock *
5722 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5723                                     unsigned Size, unsigned BinOpcode) const {
5724   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5725   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5726
5727   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5728   MachineFunction *MF = BB->getParent();
5729   MachineFunction::iterator It = BB;
5730   ++It;
5731
5732   unsigned dest = MI->getOperand(0).getReg();
5733   unsigned ptr = MI->getOperand(1).getReg();
5734   unsigned incr = MI->getOperand(2).getReg();
5735   DebugLoc dl = MI->getDebugLoc();
5736   bool isThumb2 = Subtarget->isThumb2();
5737
5738   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5739   if (isThumb2) {
5740     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5741     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5742   }
5743
5744   unsigned ldrOpc, strOpc;
5745   switch (Size) {
5746   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5747   case 1:
5748     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5749     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5750     break;
5751   case 2:
5752     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5753     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5754     break;
5755   case 4:
5756     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5757     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5758     break;
5759   }
5760
5761   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5762   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5763   MF->insert(It, loopMBB);
5764   MF->insert(It, exitMBB);
5765
5766   // Transfer the remainder of BB and its successor edges to exitMBB.
5767   exitMBB->splice(exitMBB->begin(), BB,
5768                   llvm::next(MachineBasicBlock::iterator(MI)),
5769                   BB->end());
5770   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5771
5772   const TargetRegisterClass *TRC = isThumb2 ?
5773     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5774     (const TargetRegisterClass*)&ARM::GPRRegClass;
5775   unsigned scratch = MRI.createVirtualRegister(TRC);
5776   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
5777
5778   //  thisMBB:
5779   //   ...
5780   //   fallthrough --> loopMBB
5781   BB->addSuccessor(loopMBB);
5782
5783   //  loopMBB:
5784   //   ldrex dest, ptr
5785   //   <binop> scratch2, dest, incr
5786   //   strex scratch, scratch2, ptr
5787   //   cmp scratch, #0
5788   //   bne- loopMBB
5789   //   fallthrough --> exitMBB
5790   BB = loopMBB;
5791   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5792   if (ldrOpc == ARM::t2LDREX)
5793     MIB.addImm(0);
5794   AddDefaultPred(MIB);
5795   if (BinOpcode) {
5796     // operand order needs to go the other way for NAND
5797     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
5798       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5799                      addReg(incr).addReg(dest)).addReg(0);
5800     else
5801       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5802                      addReg(dest).addReg(incr)).addReg(0);
5803   }
5804
5805   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5806   if (strOpc == ARM::t2STREX)
5807     MIB.addImm(0);
5808   AddDefaultPred(MIB);
5809   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5810                  .addReg(scratch).addImm(0));
5811   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5812     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5813
5814   BB->addSuccessor(loopMBB);
5815   BB->addSuccessor(exitMBB);
5816
5817   //  exitMBB:
5818   //   ...
5819   BB = exitMBB;
5820
5821   MI->eraseFromParent();   // The instruction is gone now.
5822
5823   return BB;
5824 }
5825
5826 MachineBasicBlock *
5827 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
5828                                           MachineBasicBlock *BB,
5829                                           unsigned Size,
5830                                           bool signExtend,
5831                                           ARMCC::CondCodes Cond) const {
5832   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5833
5834   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5835   MachineFunction *MF = BB->getParent();
5836   MachineFunction::iterator It = BB;
5837   ++It;
5838
5839   unsigned dest = MI->getOperand(0).getReg();
5840   unsigned ptr = MI->getOperand(1).getReg();
5841   unsigned incr = MI->getOperand(2).getReg();
5842   unsigned oldval = dest;
5843   DebugLoc dl = MI->getDebugLoc();
5844   bool isThumb2 = Subtarget->isThumb2();
5845
5846   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5847   if (isThumb2) {
5848     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5849     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5850   }
5851
5852   unsigned ldrOpc, strOpc, extendOpc;
5853   switch (Size) {
5854   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5855   case 1:
5856     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5857     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5858     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
5859     break;
5860   case 2:
5861     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5862     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5863     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
5864     break;
5865   case 4:
5866     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5867     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5868     extendOpc = 0;
5869     break;
5870   }
5871
5872   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5873   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5874   MF->insert(It, loopMBB);
5875   MF->insert(It, exitMBB);
5876
5877   // Transfer the remainder of BB and its successor edges to exitMBB.
5878   exitMBB->splice(exitMBB->begin(), BB,
5879                   llvm::next(MachineBasicBlock::iterator(MI)),
5880                   BB->end());
5881   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5882
5883   const TargetRegisterClass *TRC = isThumb2 ?
5884     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5885     (const TargetRegisterClass*)&ARM::GPRRegClass;
5886   unsigned scratch = MRI.createVirtualRegister(TRC);
5887   unsigned scratch2 = MRI.createVirtualRegister(TRC);
5888
5889   //  thisMBB:
5890   //   ...
5891   //   fallthrough --> loopMBB
5892   BB->addSuccessor(loopMBB);
5893
5894   //  loopMBB:
5895   //   ldrex dest, ptr
5896   //   (sign extend dest, if required)
5897   //   cmp dest, incr
5898   //   cmov.cond scratch2, incr, dest
5899   //   strex scratch, scratch2, ptr
5900   //   cmp scratch, #0
5901   //   bne- loopMBB
5902   //   fallthrough --> exitMBB
5903   BB = loopMBB;
5904   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5905   if (ldrOpc == ARM::t2LDREX)
5906     MIB.addImm(0);
5907   AddDefaultPred(MIB);
5908
5909   // Sign extend the value, if necessary.
5910   if (signExtend && extendOpc) {
5911     oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
5912     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
5913                      .addReg(dest)
5914                      .addImm(0));
5915   }
5916
5917   // Build compare and cmov instructions.
5918   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5919                  .addReg(oldval).addReg(incr));
5920   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
5921          .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
5922
5923   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5924   if (strOpc == ARM::t2STREX)
5925     MIB.addImm(0);
5926   AddDefaultPred(MIB);
5927   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5928                  .addReg(scratch).addImm(0));
5929   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5930     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5931
5932   BB->addSuccessor(loopMBB);
5933   BB->addSuccessor(exitMBB);
5934
5935   //  exitMBB:
5936   //   ...
5937   BB = exitMBB;
5938
5939   MI->eraseFromParent();   // The instruction is gone now.
5940
5941   return BB;
5942 }
5943
5944 MachineBasicBlock *
5945 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
5946                                       unsigned Op1, unsigned Op2,
5947                                       bool NeedsCarry, bool IsCmpxchg,
5948                                       bool IsMinMax, ARMCC::CondCodes CC) const {
5949   // This also handles ATOMIC_SWAP, indicated by Op1==0.
5950   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5951
5952   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5953   MachineFunction *MF = BB->getParent();
5954   MachineFunction::iterator It = BB;
5955   ++It;
5956
5957   unsigned destlo = MI->getOperand(0).getReg();
5958   unsigned desthi = MI->getOperand(1).getReg();
5959   unsigned ptr = MI->getOperand(2).getReg();
5960   unsigned vallo = MI->getOperand(3).getReg();
5961   unsigned valhi = MI->getOperand(4).getReg();
5962   DebugLoc dl = MI->getDebugLoc();
5963   bool isThumb2 = Subtarget->isThumb2();
5964
5965   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5966   if (isThumb2) {
5967     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
5968     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
5969     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
5970   }
5971
5972   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5973   MachineBasicBlock *contBB = 0, *cont2BB = 0;
5974   if (IsCmpxchg || IsMinMax)
5975     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
5976   if (IsCmpxchg)
5977     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
5978   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5979
5980   MF->insert(It, loopMBB);
5981   if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
5982   if (IsCmpxchg) MF->insert(It, cont2BB);
5983   MF->insert(It, exitMBB);
5984
5985   // Transfer the remainder of BB and its successor edges to exitMBB.
5986   exitMBB->splice(exitMBB->begin(), BB,
5987                   llvm::next(MachineBasicBlock::iterator(MI)),
5988                   BB->end());
5989   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5990
5991   const TargetRegisterClass *TRC = isThumb2 ?
5992     (const TargetRegisterClass*)&ARM::tGPRRegClass :
5993     (const TargetRegisterClass*)&ARM::GPRRegClass;
5994   unsigned storesuccess = MRI.createVirtualRegister(TRC);
5995
5996   //  thisMBB:
5997   //   ...
5998   //   fallthrough --> loopMBB
5999   BB->addSuccessor(loopMBB);
6000
6001   //  loopMBB:
6002   //   ldrexd r2, r3, ptr
6003   //   <binopa> r0, r2, incr
6004   //   <binopb> r1, r3, incr
6005   //   strexd storesuccess, r0, r1, ptr
6006   //   cmp storesuccess, #0
6007   //   bne- loopMBB
6008   //   fallthrough --> exitMBB
6009   BB = loopMBB;
6010
6011   // Load
6012   if (isThumb2) {
6013     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2LDREXD))
6014                    .addReg(destlo, RegState::Define)
6015                    .addReg(desthi, RegState::Define)
6016                    .addReg(ptr));
6017   } else {
6018     unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6019     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDREXD))
6020                    .addReg(GPRPair0, RegState::Define).addReg(ptr));
6021     // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
6022     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6023       .addReg(GPRPair0, 0, ARM::gsub_0);
6024     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6025       .addReg(GPRPair0, 0, ARM::gsub_1);
6026   }
6027
6028   unsigned StoreLo, StoreHi;
6029   if (IsCmpxchg) {
6030     // Add early exit
6031     for (unsigned i = 0; i < 2; i++) {
6032       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6033                                                          ARM::CMPrr))
6034                      .addReg(i == 0 ? destlo : desthi)
6035                      .addReg(i == 0 ? vallo : valhi));
6036       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6037         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6038       BB->addSuccessor(exitMBB);
6039       BB->addSuccessor(i == 0 ? contBB : cont2BB);
6040       BB = (i == 0 ? contBB : cont2BB);
6041     }
6042
6043     // Copy to physregs for strexd
6044     StoreLo = MI->getOperand(5).getReg();
6045     StoreHi = MI->getOperand(6).getReg();
6046   } else if (Op1) {
6047     // Perform binary operation
6048     unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6049     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6050                    .addReg(destlo).addReg(vallo))
6051         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6052     unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6053     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6054                    .addReg(desthi).addReg(valhi))
6055         .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6056
6057     StoreLo = tmpRegLo;
6058     StoreHi = tmpRegHi;
6059   } else {
6060     // Copy to physregs for strexd
6061     StoreLo = vallo;
6062     StoreHi = valhi;
6063   }
6064   if (IsMinMax) {
6065     // Compare and branch to exit block.
6066     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6067       .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6068     BB->addSuccessor(exitMBB);
6069     BB->addSuccessor(contBB);
6070     BB = contBB;
6071     StoreLo = vallo;
6072     StoreHi = valhi;
6073   }
6074
6075   // Store
6076   if (isThumb2) {
6077     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2STREXD), storesuccess)
6078                    .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6079   } else {
6080     // Marshal a pair...
6081     unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6082     unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6083     unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6084     BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6085     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6086       .addReg(UndefPair)
6087       .addReg(StoreLo)
6088       .addImm(ARM::gsub_0);
6089     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6090       .addReg(r1)
6091       .addReg(StoreHi)
6092       .addImm(ARM::gsub_1);
6093
6094     // ...and store it
6095     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::STREXD), storesuccess)
6096                    .addReg(StorePair).addReg(ptr));
6097   }
6098   // Cmp+jump
6099   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6100                  .addReg(storesuccess).addImm(0));
6101   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6102     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6103
6104   BB->addSuccessor(loopMBB);
6105   BB->addSuccessor(exitMBB);
6106
6107   //  exitMBB:
6108   //   ...
6109   BB = exitMBB;
6110
6111   MI->eraseFromParent();   // The instruction is gone now.
6112
6113   return BB;
6114 }
6115
6116 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6117 /// registers the function context.
6118 void ARMTargetLowering::
6119 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6120                        MachineBasicBlock *DispatchBB, int FI) const {
6121   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6122   DebugLoc dl = MI->getDebugLoc();
6123   MachineFunction *MF = MBB->getParent();
6124   MachineRegisterInfo *MRI = &MF->getRegInfo();
6125   MachineConstantPool *MCP = MF->getConstantPool();
6126   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6127   const Function *F = MF->getFunction();
6128
6129   bool isThumb = Subtarget->isThumb();
6130   bool isThumb2 = Subtarget->isThumb2();
6131
6132   unsigned PCLabelId = AFI->createPICLabelUId();
6133   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6134   ARMConstantPoolValue *CPV =
6135     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6136   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6137
6138   const TargetRegisterClass *TRC = isThumb ?
6139     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6140     (const TargetRegisterClass*)&ARM::GPRRegClass;
6141
6142   // Grab constant pool and fixed stack memory operands.
6143   MachineMemOperand *CPMMO =
6144     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6145                              MachineMemOperand::MOLoad, 4, 4);
6146
6147   MachineMemOperand *FIMMOSt =
6148     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6149                              MachineMemOperand::MOStore, 4, 4);
6150
6151   // Load the address of the dispatch MBB into the jump buffer.
6152   if (isThumb2) {
6153     // Incoming value: jbuf
6154     //   ldr.n  r5, LCPI1_1
6155     //   orr    r5, r5, #1
6156     //   add    r5, pc
6157     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6158     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6159     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6160                    .addConstantPoolIndex(CPI)
6161                    .addMemOperand(CPMMO));
6162     // Set the low bit because of thumb mode.
6163     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6164     AddDefaultCC(
6165       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6166                      .addReg(NewVReg1, RegState::Kill)
6167                      .addImm(0x01)));
6168     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6169     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6170       .addReg(NewVReg2, RegState::Kill)
6171       .addImm(PCLabelId);
6172     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6173                    .addReg(NewVReg3, RegState::Kill)
6174                    .addFrameIndex(FI)
6175                    .addImm(36)  // &jbuf[1] :: pc
6176                    .addMemOperand(FIMMOSt));
6177   } else if (isThumb) {
6178     // Incoming value: jbuf
6179     //   ldr.n  r1, LCPI1_4
6180     //   add    r1, pc
6181     //   mov    r2, #1
6182     //   orrs   r1, r2
6183     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6184     //   str    r1, [r2]
6185     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6186     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6187                    .addConstantPoolIndex(CPI)
6188                    .addMemOperand(CPMMO));
6189     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6190     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6191       .addReg(NewVReg1, RegState::Kill)
6192       .addImm(PCLabelId);
6193     // Set the low bit because of thumb mode.
6194     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6195     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6196                    .addReg(ARM::CPSR, RegState::Define)
6197                    .addImm(1));
6198     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6199     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6200                    .addReg(ARM::CPSR, RegState::Define)
6201                    .addReg(NewVReg2, RegState::Kill)
6202                    .addReg(NewVReg3, RegState::Kill));
6203     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6204     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6205                    .addFrameIndex(FI)
6206                    .addImm(36)); // &jbuf[1] :: pc
6207     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6208                    .addReg(NewVReg4, RegState::Kill)
6209                    .addReg(NewVReg5, RegState::Kill)
6210                    .addImm(0)
6211                    .addMemOperand(FIMMOSt));
6212   } else {
6213     // Incoming value: jbuf
6214     //   ldr  r1, LCPI1_1
6215     //   add  r1, pc, r1
6216     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6217     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6218     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6219                    .addConstantPoolIndex(CPI)
6220                    .addImm(0)
6221                    .addMemOperand(CPMMO));
6222     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6223     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6224                    .addReg(NewVReg1, RegState::Kill)
6225                    .addImm(PCLabelId));
6226     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6227                    .addReg(NewVReg2, RegState::Kill)
6228                    .addFrameIndex(FI)
6229                    .addImm(36)  // &jbuf[1] :: pc
6230                    .addMemOperand(FIMMOSt));
6231   }
6232 }
6233
6234 MachineBasicBlock *ARMTargetLowering::
6235 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6236   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6237   DebugLoc dl = MI->getDebugLoc();
6238   MachineFunction *MF = MBB->getParent();
6239   MachineRegisterInfo *MRI = &MF->getRegInfo();
6240   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6241   MachineFrameInfo *MFI = MF->getFrameInfo();
6242   int FI = MFI->getFunctionContextIndex();
6243
6244   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6245     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6246     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6247
6248   // Get a mapping of the call site numbers to all of the landing pads they're
6249   // associated with.
6250   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6251   unsigned MaxCSNum = 0;
6252   MachineModuleInfo &MMI = MF->getMMI();
6253   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6254        ++BB) {
6255     if (!BB->isLandingPad()) continue;
6256
6257     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6258     // pad.
6259     for (MachineBasicBlock::iterator
6260            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6261       if (!II->isEHLabel()) continue;
6262
6263       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6264       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6265
6266       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6267       for (SmallVectorImpl<unsigned>::iterator
6268              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6269            CSI != CSE; ++CSI) {
6270         CallSiteNumToLPad[*CSI].push_back(BB);
6271         MaxCSNum = std::max(MaxCSNum, *CSI);
6272       }
6273       break;
6274     }
6275   }
6276
6277   // Get an ordered list of the machine basic blocks for the jump table.
6278   std::vector<MachineBasicBlock*> LPadList;
6279   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6280   LPadList.reserve(CallSiteNumToLPad.size());
6281   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6282     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6283     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6284            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6285       LPadList.push_back(*II);
6286       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6287     }
6288   }
6289
6290   assert(!LPadList.empty() &&
6291          "No landing pad destinations for the dispatch jump table!");
6292
6293   // Create the jump table and associated information.
6294   MachineJumpTableInfo *JTI =
6295     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6296   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6297   unsigned UId = AFI->createJumpTableUId();
6298
6299   // Create the MBBs for the dispatch code.
6300
6301   // Shove the dispatch's address into the return slot in the function context.
6302   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6303   DispatchBB->setIsLandingPad();
6304
6305   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6306   BuildMI(TrapBB, dl, TII->get(Subtarget->isThumb() ? ARM::tTRAP : ARM::TRAP));
6307   DispatchBB->addSuccessor(TrapBB);
6308
6309   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6310   DispatchBB->addSuccessor(DispContBB);
6311
6312   // Insert and MBBs.
6313   MF->insert(MF->end(), DispatchBB);
6314   MF->insert(MF->end(), DispContBB);
6315   MF->insert(MF->end(), TrapBB);
6316
6317   // Insert code into the entry block that creates and registers the function
6318   // context.
6319   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6320
6321   MachineMemOperand *FIMMOLd =
6322     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6323                              MachineMemOperand::MOLoad |
6324                              MachineMemOperand::MOVolatile, 4, 4);
6325
6326   MachineInstrBuilder MIB;
6327   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6328
6329   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6330   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6331
6332   // Add a register mask with no preserved registers.  This results in all
6333   // registers being marked as clobbered.
6334   MIB.addRegMask(RI.getNoPreservedMask());
6335
6336   unsigned NumLPads = LPadList.size();
6337   if (Subtarget->isThumb2()) {
6338     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6339     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6340                    .addFrameIndex(FI)
6341                    .addImm(4)
6342                    .addMemOperand(FIMMOLd));
6343
6344     if (NumLPads < 256) {
6345       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6346                      .addReg(NewVReg1)
6347                      .addImm(LPadList.size()));
6348     } else {
6349       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6350       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6351                      .addImm(NumLPads & 0xFFFF));
6352
6353       unsigned VReg2 = VReg1;
6354       if ((NumLPads & 0xFFFF0000) != 0) {
6355         VReg2 = MRI->createVirtualRegister(TRC);
6356         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6357                        .addReg(VReg1)
6358                        .addImm(NumLPads >> 16));
6359       }
6360
6361       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6362                      .addReg(NewVReg1)
6363                      .addReg(VReg2));
6364     }
6365
6366     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6367       .addMBB(TrapBB)
6368       .addImm(ARMCC::HI)
6369       .addReg(ARM::CPSR);
6370
6371     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6372     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6373                    .addJumpTableIndex(MJTI)
6374                    .addImm(UId));
6375
6376     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6377     AddDefaultCC(
6378       AddDefaultPred(
6379         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6380         .addReg(NewVReg3, RegState::Kill)
6381         .addReg(NewVReg1)
6382         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6383
6384     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6385       .addReg(NewVReg4, RegState::Kill)
6386       .addReg(NewVReg1)
6387       .addJumpTableIndex(MJTI)
6388       .addImm(UId);
6389   } else if (Subtarget->isThumb()) {
6390     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6391     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6392                    .addFrameIndex(FI)
6393                    .addImm(1)
6394                    .addMemOperand(FIMMOLd));
6395
6396     if (NumLPads < 256) {
6397       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6398                      .addReg(NewVReg1)
6399                      .addImm(NumLPads));
6400     } else {
6401       MachineConstantPool *ConstantPool = MF->getConstantPool();
6402       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6403       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6404
6405       // MachineConstantPool wants an explicit alignment.
6406       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6407       if (Align == 0)
6408         Align = getDataLayout()->getTypeAllocSize(C->getType());
6409       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6410
6411       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6412       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6413                      .addReg(VReg1, RegState::Define)
6414                      .addConstantPoolIndex(Idx));
6415       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6416                      .addReg(NewVReg1)
6417                      .addReg(VReg1));
6418     }
6419
6420     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6421       .addMBB(TrapBB)
6422       .addImm(ARMCC::HI)
6423       .addReg(ARM::CPSR);
6424
6425     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6426     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6427                    .addReg(ARM::CPSR, RegState::Define)
6428                    .addReg(NewVReg1)
6429                    .addImm(2));
6430
6431     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6432     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6433                    .addJumpTableIndex(MJTI)
6434                    .addImm(UId));
6435
6436     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6437     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6438                    .addReg(ARM::CPSR, RegState::Define)
6439                    .addReg(NewVReg2, RegState::Kill)
6440                    .addReg(NewVReg3));
6441
6442     MachineMemOperand *JTMMOLd =
6443       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6444                                MachineMemOperand::MOLoad, 4, 4);
6445
6446     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6447     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6448                    .addReg(NewVReg4, RegState::Kill)
6449                    .addImm(0)
6450                    .addMemOperand(JTMMOLd));
6451
6452     unsigned NewVReg6 = MRI->createVirtualRegister(TRC);
6453     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6454                    .addReg(ARM::CPSR, RegState::Define)
6455                    .addReg(NewVReg5, RegState::Kill)
6456                    .addReg(NewVReg3));
6457
6458     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6459       .addReg(NewVReg6, RegState::Kill)
6460       .addJumpTableIndex(MJTI)
6461       .addImm(UId);
6462   } else {
6463     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6464     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6465                    .addFrameIndex(FI)
6466                    .addImm(4)
6467                    .addMemOperand(FIMMOLd));
6468
6469     if (NumLPads < 256) {
6470       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6471                      .addReg(NewVReg1)
6472                      .addImm(NumLPads));
6473     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6474       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6475       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6476                      .addImm(NumLPads & 0xFFFF));
6477
6478       unsigned VReg2 = VReg1;
6479       if ((NumLPads & 0xFFFF0000) != 0) {
6480         VReg2 = MRI->createVirtualRegister(TRC);
6481         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6482                        .addReg(VReg1)
6483                        .addImm(NumLPads >> 16));
6484       }
6485
6486       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6487                      .addReg(NewVReg1)
6488                      .addReg(VReg2));
6489     } else {
6490       MachineConstantPool *ConstantPool = MF->getConstantPool();
6491       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6492       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6493
6494       // MachineConstantPool wants an explicit alignment.
6495       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6496       if (Align == 0)
6497         Align = getDataLayout()->getTypeAllocSize(C->getType());
6498       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6499
6500       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6501       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6502                      .addReg(VReg1, RegState::Define)
6503                      .addConstantPoolIndex(Idx)
6504                      .addImm(0));
6505       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6506                      .addReg(NewVReg1)
6507                      .addReg(VReg1, RegState::Kill));
6508     }
6509
6510     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6511       .addMBB(TrapBB)
6512       .addImm(ARMCC::HI)
6513       .addReg(ARM::CPSR);
6514
6515     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6516     AddDefaultCC(
6517       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6518                      .addReg(NewVReg1)
6519                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6520     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6521     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6522                    .addJumpTableIndex(MJTI)
6523                    .addImm(UId));
6524
6525     MachineMemOperand *JTMMOLd =
6526       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6527                                MachineMemOperand::MOLoad, 4, 4);
6528     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6529     AddDefaultPred(
6530       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6531       .addReg(NewVReg3, RegState::Kill)
6532       .addReg(NewVReg4)
6533       .addImm(0)
6534       .addMemOperand(JTMMOLd));
6535
6536     BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6537       .addReg(NewVReg5, RegState::Kill)
6538       .addReg(NewVReg4)
6539       .addJumpTableIndex(MJTI)
6540       .addImm(UId);
6541   }
6542
6543   // Add the jump table entries as successors to the MBB.
6544   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6545   for (std::vector<MachineBasicBlock*>::iterator
6546          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6547     MachineBasicBlock *CurMBB = *I;
6548     if (SeenMBBs.insert(CurMBB))
6549       DispContBB->addSuccessor(CurMBB);
6550   }
6551
6552   // N.B. the order the invoke BBs are processed in doesn't matter here.
6553   const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6554   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6555   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6556          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6557     MachineBasicBlock *BB = *I;
6558
6559     // Remove the landing pad successor from the invoke block and replace it
6560     // with the new dispatch block.
6561     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6562                                                   BB->succ_end());
6563     while (!Successors.empty()) {
6564       MachineBasicBlock *SMBB = Successors.pop_back_val();
6565       if (SMBB->isLandingPad()) {
6566         BB->removeSuccessor(SMBB);
6567         MBBLPads.push_back(SMBB);
6568       }
6569     }
6570
6571     BB->addSuccessor(DispatchBB);
6572
6573     // Find the invoke call and mark all of the callee-saved registers as
6574     // 'implicit defined' so that they're spilled. This prevents code from
6575     // moving instructions to before the EH block, where they will never be
6576     // executed.
6577     for (MachineBasicBlock::reverse_iterator
6578            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6579       if (!II->isCall()) continue;
6580
6581       DenseMap<unsigned, bool> DefRegs;
6582       for (MachineInstr::mop_iterator
6583              OI = II->operands_begin(), OE = II->operands_end();
6584            OI != OE; ++OI) {
6585         if (!OI->isReg()) continue;
6586         DefRegs[OI->getReg()] = true;
6587       }
6588
6589       MachineInstrBuilder MIB(*MF, &*II);
6590
6591       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6592         unsigned Reg = SavedRegs[i];
6593         if (Subtarget->isThumb2() &&
6594             !ARM::tGPRRegClass.contains(Reg) &&
6595             !ARM::hGPRRegClass.contains(Reg))
6596           continue;
6597         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6598           continue;
6599         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6600           continue;
6601         if (!DefRegs[Reg])
6602           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6603       }
6604
6605       break;
6606     }
6607   }
6608
6609   // Mark all former landing pads as non-landing pads. The dispatch is the only
6610   // landing pad now.
6611   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6612          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6613     (*I)->setIsLandingPad(false);
6614
6615   // The instruction is gone now.
6616   MI->eraseFromParent();
6617
6618   return MBB;
6619 }
6620
6621 static
6622 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6623   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6624        E = MBB->succ_end(); I != E; ++I)
6625     if (*I != Succ)
6626       return *I;
6627   llvm_unreachable("Expecting a BB with two successors!");
6628 }
6629
6630 MachineBasicBlock *ARMTargetLowering::
6631 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
6632   // This pseudo instruction has 3 operands: dst, src, size
6633   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6634   // Otherwise, we will generate unrolled scalar copies.
6635   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6636   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6637   MachineFunction::iterator It = BB;
6638   ++It;
6639
6640   unsigned dest = MI->getOperand(0).getReg();
6641   unsigned src = MI->getOperand(1).getReg();
6642   unsigned SizeVal = MI->getOperand(2).getImm();
6643   unsigned Align = MI->getOperand(3).getImm();
6644   DebugLoc dl = MI->getDebugLoc();
6645
6646   bool isThumb2 = Subtarget->isThumb2();
6647   MachineFunction *MF = BB->getParent();
6648   MachineRegisterInfo &MRI = MF->getRegInfo();
6649   unsigned ldrOpc, strOpc, UnitSize = 0;
6650
6651   const TargetRegisterClass *TRC = isThumb2 ?
6652     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6653     (const TargetRegisterClass*)&ARM::GPRRegClass;
6654   const TargetRegisterClass *TRC_Vec = 0;
6655
6656   if (Align & 1) {
6657     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6658     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6659     UnitSize = 1;
6660   } else if (Align & 2) {
6661     ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
6662     strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
6663     UnitSize = 2;
6664   } else {
6665     // Check whether we can use NEON instructions.
6666     if (!MF->getFunction()->getAttributes().
6667           hasAttribute(AttributeSet::FunctionIndex,
6668                        Attribute::NoImplicitFloat) &&
6669         Subtarget->hasNEON()) {
6670       if ((Align % 16 == 0) && SizeVal >= 16) {
6671         ldrOpc = ARM::VLD1q32wb_fixed;
6672         strOpc = ARM::VST1q32wb_fixed;
6673         UnitSize = 16;
6674         TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
6675       }
6676       else if ((Align % 8 == 0) && SizeVal >= 8) {
6677         ldrOpc = ARM::VLD1d32wb_fixed;
6678         strOpc = ARM::VST1d32wb_fixed;
6679         UnitSize = 8;
6680         TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
6681       }
6682     }
6683     // Can't use NEON instructions.
6684     if (UnitSize == 0) {
6685       ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
6686       strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
6687       UnitSize = 4;
6688     }
6689   }
6690
6691   unsigned BytesLeft = SizeVal % UnitSize;
6692   unsigned LoopSize = SizeVal - BytesLeft;
6693
6694   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6695     // Use LDR and STR to copy.
6696     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6697     // [destOut] = STR_POST(scratch, destIn, UnitSize)
6698     unsigned srcIn = src;
6699     unsigned destIn = dest;
6700     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6701       unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6702       unsigned srcOut = MRI.createVirtualRegister(TRC);
6703       unsigned destOut = MRI.createVirtualRegister(TRC);
6704       if (UnitSize >= 8) {
6705         AddDefaultPred(BuildMI(*BB, MI, dl,
6706           TII->get(ldrOpc), scratch)
6707           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
6708
6709         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6710           .addReg(destIn).addImm(0).addReg(scratch));
6711       } else if (isThumb2) {
6712         AddDefaultPred(BuildMI(*BB, MI, dl,
6713           TII->get(ldrOpc), scratch)
6714           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
6715
6716         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6717           .addReg(scratch).addReg(destIn)
6718           .addImm(UnitSize));
6719       } else {
6720         AddDefaultPred(BuildMI(*BB, MI, dl,
6721           TII->get(ldrOpc), scratch)
6722           .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
6723           .addImm(UnitSize));
6724
6725         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6726           .addReg(scratch).addReg(destIn)
6727           .addReg(0).addImm(UnitSize));
6728       }
6729       srcIn = srcOut;
6730       destIn = destOut;
6731     }
6732
6733     // Handle the leftover bytes with LDRB and STRB.
6734     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6735     // [destOut] = STRB_POST(scratch, destIn, 1)
6736     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6737     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6738     for (unsigned i = 0; i < BytesLeft; i++) {
6739       unsigned scratch = MRI.createVirtualRegister(TRC);
6740       unsigned srcOut = MRI.createVirtualRegister(TRC);
6741       unsigned destOut = MRI.createVirtualRegister(TRC);
6742       if (isThumb2) {
6743         AddDefaultPred(BuildMI(*BB, MI, dl,
6744           TII->get(ldrOpc),scratch)
6745           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6746
6747         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6748           .addReg(scratch).addReg(destIn)
6749           .addReg(0).addImm(1));
6750       } else {
6751         AddDefaultPred(BuildMI(*BB, MI, dl,
6752           TII->get(ldrOpc),scratch)
6753           .addReg(srcOut, RegState::Define).addReg(srcIn)
6754           .addReg(0).addImm(1));
6755
6756         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
6757           .addReg(scratch).addReg(destIn)
6758           .addReg(0).addImm(1));
6759       }
6760       srcIn = srcOut;
6761       destIn = destOut;
6762     }
6763     MI->eraseFromParent();   // The instruction is gone now.
6764     return BB;
6765   }
6766
6767   // Expand the pseudo op to a loop.
6768   // thisMBB:
6769   //   ...
6770   //   movw varEnd, # --> with thumb2
6771   //   movt varEnd, #
6772   //   ldrcp varEnd, idx --> without thumb2
6773   //   fallthrough --> loopMBB
6774   // loopMBB:
6775   //   PHI varPhi, varEnd, varLoop
6776   //   PHI srcPhi, src, srcLoop
6777   //   PHI destPhi, dst, destLoop
6778   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6779   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
6780   //   subs varLoop, varPhi, #UnitSize
6781   //   bne loopMBB
6782   //   fallthrough --> exitMBB
6783   // exitMBB:
6784   //   epilogue to handle left-over bytes
6785   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6786   //   [destOut] = STRB_POST(scratch, destLoop, 1)
6787   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6788   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6789   MF->insert(It, loopMBB);
6790   MF->insert(It, exitMBB);
6791
6792   // Transfer the remainder of BB and its successor edges to exitMBB.
6793   exitMBB->splice(exitMBB->begin(), BB,
6794                   llvm::next(MachineBasicBlock::iterator(MI)),
6795                   BB->end());
6796   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6797
6798   // Load an immediate to varEnd.
6799   unsigned varEnd = MRI.createVirtualRegister(TRC);
6800   if (isThumb2) {
6801     unsigned VReg1 = varEnd;
6802     if ((LoopSize & 0xFFFF0000) != 0)
6803       VReg1 = MRI.createVirtualRegister(TRC);
6804     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
6805                    .addImm(LoopSize & 0xFFFF));
6806
6807     if ((LoopSize & 0xFFFF0000) != 0)
6808       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
6809                      .addReg(VReg1)
6810                      .addImm(LoopSize >> 16));
6811   } else {
6812     MachineConstantPool *ConstantPool = MF->getConstantPool();
6813     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6814     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
6815
6816     // MachineConstantPool wants an explicit alignment.
6817     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6818     if (Align == 0)
6819       Align = getDataLayout()->getTypeAllocSize(C->getType());
6820     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6821
6822     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
6823                    .addReg(varEnd, RegState::Define)
6824                    .addConstantPoolIndex(Idx)
6825                    .addImm(0));
6826   }
6827   BB->addSuccessor(loopMBB);
6828
6829   // Generate the loop body:
6830   //   varPhi = PHI(varLoop, varEnd)
6831   //   srcPhi = PHI(srcLoop, src)
6832   //   destPhi = PHI(destLoop, dst)
6833   MachineBasicBlock *entryBB = BB;
6834   BB = loopMBB;
6835   unsigned varLoop = MRI.createVirtualRegister(TRC);
6836   unsigned varPhi = MRI.createVirtualRegister(TRC);
6837   unsigned srcLoop = MRI.createVirtualRegister(TRC);
6838   unsigned srcPhi = MRI.createVirtualRegister(TRC);
6839   unsigned destLoop = MRI.createVirtualRegister(TRC);
6840   unsigned destPhi = MRI.createVirtualRegister(TRC);
6841
6842   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
6843     .addReg(varLoop).addMBB(loopMBB)
6844     .addReg(varEnd).addMBB(entryBB);
6845   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
6846     .addReg(srcLoop).addMBB(loopMBB)
6847     .addReg(src).addMBB(entryBB);
6848   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
6849     .addReg(destLoop).addMBB(loopMBB)
6850     .addReg(dest).addMBB(entryBB);
6851
6852   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6853   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
6854   unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
6855   if (UnitSize >= 8) {
6856     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6857       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
6858
6859     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6860       .addReg(destPhi).addImm(0).addReg(scratch));
6861   } else if (isThumb2) {
6862     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6863       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
6864
6865     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6866       .addReg(scratch).addReg(destPhi)
6867       .addImm(UnitSize));
6868   } else {
6869     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
6870       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
6871       .addImm(UnitSize));
6872
6873     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
6874       .addReg(scratch).addReg(destPhi)
6875       .addReg(0).addImm(UnitSize));
6876   }
6877
6878   // Decrement loop variable by UnitSize.
6879   MachineInstrBuilder MIB = BuildMI(BB, dl,
6880     TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
6881   AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
6882   MIB->getOperand(5).setReg(ARM::CPSR);
6883   MIB->getOperand(5).setIsDef(true);
6884
6885   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6886     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6887
6888   // loopMBB can loop back to loopMBB or fall through to exitMBB.
6889   BB->addSuccessor(loopMBB);
6890   BB->addSuccessor(exitMBB);
6891
6892   // Add epilogue to handle BytesLeft.
6893   BB = exitMBB;
6894   MachineInstr *StartOfExit = exitMBB->begin();
6895   ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6896   strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6897
6898   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6899   //   [destOut] = STRB_POST(scratch, destLoop, 1)
6900   unsigned srcIn = srcLoop;
6901   unsigned destIn = destLoop;
6902   for (unsigned i = 0; i < BytesLeft; i++) {
6903     unsigned scratch = MRI.createVirtualRegister(TRC);
6904     unsigned srcOut = MRI.createVirtualRegister(TRC);
6905     unsigned destOut = MRI.createVirtualRegister(TRC);
6906     if (isThumb2) {
6907       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6908         TII->get(ldrOpc),scratch)
6909         .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
6910
6911       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6912         .addReg(scratch).addReg(destIn)
6913         .addImm(1));
6914     } else {
6915       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
6916         TII->get(ldrOpc),scratch)
6917         .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
6918
6919       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
6920         .addReg(scratch).addReg(destIn)
6921         .addReg(0).addImm(1));
6922     }
6923     srcIn = srcOut;
6924     destIn = destOut;
6925   }
6926
6927   MI->eraseFromParent();   // The instruction is gone now.
6928   return BB;
6929 }
6930
6931 MachineBasicBlock *
6932 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6933                                                MachineBasicBlock *BB) const {
6934   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6935   DebugLoc dl = MI->getDebugLoc();
6936   bool isThumb2 = Subtarget->isThumb2();
6937   switch (MI->getOpcode()) {
6938   default: {
6939     MI->dump();
6940     llvm_unreachable("Unexpected instr type to insert");
6941   }
6942   // The Thumb2 pre-indexed stores have the same MI operands, they just
6943   // define them differently in the .td files from the isel patterns, so
6944   // they need pseudos.
6945   case ARM::t2STR_preidx:
6946     MI->setDesc(TII->get(ARM::t2STR_PRE));
6947     return BB;
6948   case ARM::t2STRB_preidx:
6949     MI->setDesc(TII->get(ARM::t2STRB_PRE));
6950     return BB;
6951   case ARM::t2STRH_preidx:
6952     MI->setDesc(TII->get(ARM::t2STRH_PRE));
6953     return BB;
6954
6955   case ARM::STRi_preidx:
6956   case ARM::STRBi_preidx: {
6957     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
6958       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
6959     // Decode the offset.
6960     unsigned Offset = MI->getOperand(4).getImm();
6961     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
6962     Offset = ARM_AM::getAM2Offset(Offset);
6963     if (isSub)
6964       Offset = -Offset;
6965
6966     MachineMemOperand *MMO = *MI->memoperands_begin();
6967     BuildMI(*BB, MI, dl, TII->get(NewOpc))
6968       .addOperand(MI->getOperand(0))  // Rn_wb
6969       .addOperand(MI->getOperand(1))  // Rt
6970       .addOperand(MI->getOperand(2))  // Rn
6971       .addImm(Offset)                 // offset (skip GPR==zero_reg)
6972       .addOperand(MI->getOperand(5))  // pred
6973       .addOperand(MI->getOperand(6))
6974       .addMemOperand(MMO);
6975     MI->eraseFromParent();
6976     return BB;
6977   }
6978   case ARM::STRr_preidx:
6979   case ARM::STRBr_preidx:
6980   case ARM::STRH_preidx: {
6981     unsigned NewOpc;
6982     switch (MI->getOpcode()) {
6983     default: llvm_unreachable("unexpected opcode!");
6984     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
6985     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
6986     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
6987     }
6988     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
6989     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
6990       MIB.addOperand(MI->getOperand(i));
6991     MI->eraseFromParent();
6992     return BB;
6993   }
6994   case ARM::ATOMIC_LOAD_ADD_I8:
6995      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6996   case ARM::ATOMIC_LOAD_ADD_I16:
6997      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6998   case ARM::ATOMIC_LOAD_ADD_I32:
6999      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7000
7001   case ARM::ATOMIC_LOAD_AND_I8:
7002      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7003   case ARM::ATOMIC_LOAD_AND_I16:
7004      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7005   case ARM::ATOMIC_LOAD_AND_I32:
7006      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7007
7008   case ARM::ATOMIC_LOAD_OR_I8:
7009      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7010   case ARM::ATOMIC_LOAD_OR_I16:
7011      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7012   case ARM::ATOMIC_LOAD_OR_I32:
7013      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7014
7015   case ARM::ATOMIC_LOAD_XOR_I8:
7016      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7017   case ARM::ATOMIC_LOAD_XOR_I16:
7018      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7019   case ARM::ATOMIC_LOAD_XOR_I32:
7020      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7021
7022   case ARM::ATOMIC_LOAD_NAND_I8:
7023      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7024   case ARM::ATOMIC_LOAD_NAND_I16:
7025      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7026   case ARM::ATOMIC_LOAD_NAND_I32:
7027      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7028
7029   case ARM::ATOMIC_LOAD_SUB_I8:
7030      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7031   case ARM::ATOMIC_LOAD_SUB_I16:
7032      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7033   case ARM::ATOMIC_LOAD_SUB_I32:
7034      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7035
7036   case ARM::ATOMIC_LOAD_MIN_I8:
7037      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7038   case ARM::ATOMIC_LOAD_MIN_I16:
7039      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7040   case ARM::ATOMIC_LOAD_MIN_I32:
7041      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7042
7043   case ARM::ATOMIC_LOAD_MAX_I8:
7044      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7045   case ARM::ATOMIC_LOAD_MAX_I16:
7046      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7047   case ARM::ATOMIC_LOAD_MAX_I32:
7048      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7049
7050   case ARM::ATOMIC_LOAD_UMIN_I8:
7051      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7052   case ARM::ATOMIC_LOAD_UMIN_I16:
7053      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7054   case ARM::ATOMIC_LOAD_UMIN_I32:
7055      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7056
7057   case ARM::ATOMIC_LOAD_UMAX_I8:
7058      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7059   case ARM::ATOMIC_LOAD_UMAX_I16:
7060      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7061   case ARM::ATOMIC_LOAD_UMAX_I32:
7062      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7063
7064   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
7065   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7066   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7067
7068   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
7069   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7070   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7071
7072
7073   case ARM::ATOMADD6432:
7074     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7075                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7076                               /*NeedsCarry*/ true);
7077   case ARM::ATOMSUB6432:
7078     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7079                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7080                               /*NeedsCarry*/ true);
7081   case ARM::ATOMOR6432:
7082     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7083                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7084   case ARM::ATOMXOR6432:
7085     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7086                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7087   case ARM::ATOMAND6432:
7088     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7089                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7090   case ARM::ATOMSWAP6432:
7091     return EmitAtomicBinary64(MI, BB, 0, 0, false);
7092   case ARM::ATOMCMPXCHG6432:
7093     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7094                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7095                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7096   case ARM::ATOMMIN6432:
7097     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7098                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7099                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7100                               /*IsMinMax*/ true, ARMCC::LT);
7101   case ARM::ATOMMAX6432:
7102     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7103                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7104                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7105                               /*IsMinMax*/ true, ARMCC::GE);
7106   case ARM::ATOMUMIN6432:
7107     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7108                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7109                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7110                               /*IsMinMax*/ true, ARMCC::LO);
7111   case ARM::ATOMUMAX6432:
7112     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7113                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7114                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7115                               /*IsMinMax*/ true, ARMCC::HS);
7116
7117   case ARM::tMOVCCr_pseudo: {
7118     // To "insert" a SELECT_CC instruction, we actually have to insert the
7119     // diamond control-flow pattern.  The incoming instruction knows the
7120     // destination vreg to set, the condition code register to branch on, the
7121     // true/false values to select between, and a branch opcode to use.
7122     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7123     MachineFunction::iterator It = BB;
7124     ++It;
7125
7126     //  thisMBB:
7127     //  ...
7128     //   TrueVal = ...
7129     //   cmpTY ccX, r1, r2
7130     //   bCC copy1MBB
7131     //   fallthrough --> copy0MBB
7132     MachineBasicBlock *thisMBB  = BB;
7133     MachineFunction *F = BB->getParent();
7134     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7135     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7136     F->insert(It, copy0MBB);
7137     F->insert(It, sinkMBB);
7138
7139     // Transfer the remainder of BB and its successor edges to sinkMBB.
7140     sinkMBB->splice(sinkMBB->begin(), BB,
7141                     llvm::next(MachineBasicBlock::iterator(MI)),
7142                     BB->end());
7143     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7144
7145     BB->addSuccessor(copy0MBB);
7146     BB->addSuccessor(sinkMBB);
7147
7148     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7149       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7150
7151     //  copy0MBB:
7152     //   %FalseValue = ...
7153     //   # fallthrough to sinkMBB
7154     BB = copy0MBB;
7155
7156     // Update machine-CFG edges
7157     BB->addSuccessor(sinkMBB);
7158
7159     //  sinkMBB:
7160     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7161     //  ...
7162     BB = sinkMBB;
7163     BuildMI(*BB, BB->begin(), dl,
7164             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7165       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7166       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7167
7168     MI->eraseFromParent();   // The pseudo instruction is gone now.
7169     return BB;
7170   }
7171
7172   case ARM::BCCi64:
7173   case ARM::BCCZi64: {
7174     // If there is an unconditional branch to the other successor, remove it.
7175     BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
7176
7177     // Compare both parts that make up the double comparison separately for
7178     // equality.
7179     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7180
7181     unsigned LHS1 = MI->getOperand(1).getReg();
7182     unsigned LHS2 = MI->getOperand(2).getReg();
7183     if (RHSisZero) {
7184       AddDefaultPred(BuildMI(BB, dl,
7185                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7186                      .addReg(LHS1).addImm(0));
7187       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7188         .addReg(LHS2).addImm(0)
7189         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7190     } else {
7191       unsigned RHS1 = MI->getOperand(3).getReg();
7192       unsigned RHS2 = MI->getOperand(4).getReg();
7193       AddDefaultPred(BuildMI(BB, dl,
7194                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7195                      .addReg(LHS1).addReg(RHS1));
7196       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7197         .addReg(LHS2).addReg(RHS2)
7198         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7199     }
7200
7201     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7202     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7203     if (MI->getOperand(0).getImm() == ARMCC::NE)
7204       std::swap(destMBB, exitMBB);
7205
7206     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7207       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7208     if (isThumb2)
7209       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7210     else
7211       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7212
7213     MI->eraseFromParent();   // The pseudo instruction is gone now.
7214     return BB;
7215   }
7216
7217   case ARM::Int_eh_sjlj_setjmp:
7218   case ARM::Int_eh_sjlj_setjmp_nofp:
7219   case ARM::tInt_eh_sjlj_setjmp:
7220   case ARM::t2Int_eh_sjlj_setjmp:
7221   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7222     EmitSjLjDispatchBlock(MI, BB);
7223     return BB;
7224
7225   case ARM::ABS:
7226   case ARM::t2ABS: {
7227     // To insert an ABS instruction, we have to insert the
7228     // diamond control-flow pattern.  The incoming instruction knows the
7229     // source vreg to test against 0, the destination vreg to set,
7230     // the condition code register to branch on, the
7231     // true/false values to select between, and a branch opcode to use.
7232     // It transforms
7233     //     V1 = ABS V0
7234     // into
7235     //     V2 = MOVS V0
7236     //     BCC                      (branch to SinkBB if V0 >= 0)
7237     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7238     //     SinkBB: V1 = PHI(V2, V3)
7239     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7240     MachineFunction::iterator BBI = BB;
7241     ++BBI;
7242     MachineFunction *Fn = BB->getParent();
7243     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7244     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7245     Fn->insert(BBI, RSBBB);
7246     Fn->insert(BBI, SinkBB);
7247
7248     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7249     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7250     bool isThumb2 = Subtarget->isThumb2();
7251     MachineRegisterInfo &MRI = Fn->getRegInfo();
7252     // In Thumb mode S must not be specified if source register is the SP or
7253     // PC and if destination register is the SP, so restrict register class
7254     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7255       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7256       (const TargetRegisterClass*)&ARM::GPRRegClass);
7257
7258     // Transfer the remainder of BB and its successor edges to sinkMBB.
7259     SinkBB->splice(SinkBB->begin(), BB,
7260       llvm::next(MachineBasicBlock::iterator(MI)),
7261       BB->end());
7262     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7263
7264     BB->addSuccessor(RSBBB);
7265     BB->addSuccessor(SinkBB);
7266
7267     // fall through to SinkMBB
7268     RSBBB->addSuccessor(SinkBB);
7269
7270     // insert a cmp at the end of BB
7271     AddDefaultPred(BuildMI(BB, dl,
7272                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7273                    .addReg(ABSSrcReg).addImm(0));
7274
7275     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7276     BuildMI(BB, dl,
7277       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7278       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7279
7280     // insert rsbri in RSBBB
7281     // Note: BCC and rsbri will be converted into predicated rsbmi
7282     // by if-conversion pass
7283     BuildMI(*RSBBB, RSBBB->begin(), dl,
7284       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7285       .addReg(ABSSrcReg, RegState::Kill)
7286       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7287
7288     // insert PHI in SinkBB,
7289     // reuse ABSDstReg to not change uses of ABS instruction
7290     BuildMI(*SinkBB, SinkBB->begin(), dl,
7291       TII->get(ARM::PHI), ABSDstReg)
7292       .addReg(NewRsbDstReg).addMBB(RSBBB)
7293       .addReg(ABSSrcReg).addMBB(BB);
7294
7295     // remove ABS instruction
7296     MI->eraseFromParent();
7297
7298     // return last added BB
7299     return SinkBB;
7300   }
7301   case ARM::COPY_STRUCT_BYVAL_I32:
7302     ++NumLoopByVals;
7303     return EmitStructByval(MI, BB);
7304   }
7305 }
7306
7307 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7308                                                       SDNode *Node) const {
7309   if (!MI->hasPostISelHook()) {
7310     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7311            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7312     return;
7313   }
7314
7315   const MCInstrDesc *MCID = &MI->getDesc();
7316   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7317   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7318   // operand is still set to noreg. If needed, set the optional operand's
7319   // register to CPSR, and remove the redundant implicit def.
7320   //
7321   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7322
7323   // Rename pseudo opcodes.
7324   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7325   if (NewOpc) {
7326     const ARMBaseInstrInfo *TII =
7327       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7328     MCID = &TII->get(NewOpc);
7329
7330     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7331            "converted opcode should be the same except for cc_out");
7332
7333     MI->setDesc(*MCID);
7334
7335     // Add the optional cc_out operand
7336     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7337   }
7338   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7339
7340   // Any ARM instruction that sets the 's' bit should specify an optional
7341   // "cc_out" operand in the last operand position.
7342   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7343     assert(!NewOpc && "Optional cc_out operand required");
7344     return;
7345   }
7346   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7347   // since we already have an optional CPSR def.
7348   bool definesCPSR = false;
7349   bool deadCPSR = false;
7350   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7351        i != e; ++i) {
7352     const MachineOperand &MO = MI->getOperand(i);
7353     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7354       definesCPSR = true;
7355       if (MO.isDead())
7356         deadCPSR = true;
7357       MI->RemoveOperand(i);
7358       break;
7359     }
7360   }
7361   if (!definesCPSR) {
7362     assert(!NewOpc && "Optional cc_out operand required");
7363     return;
7364   }
7365   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7366   if (deadCPSR) {
7367     assert(!MI->getOperand(ccOutIdx).getReg() &&
7368            "expect uninitialized optional cc_out operand");
7369     return;
7370   }
7371
7372   // If this instruction was defined with an optional CPSR def and its dag node
7373   // had a live implicit CPSR def, then activate the optional CPSR def.
7374   MachineOperand &MO = MI->getOperand(ccOutIdx);
7375   MO.setReg(ARM::CPSR);
7376   MO.setIsDef(true);
7377 }
7378
7379 //===----------------------------------------------------------------------===//
7380 //                           ARM Optimization Hooks
7381 //===----------------------------------------------------------------------===//
7382
7383 // Helper function that checks if N is a null or all ones constant.
7384 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7385   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7386   if (!C)
7387     return false;
7388   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7389 }
7390
7391 // Return true if N is conditionally 0 or all ones.
7392 // Detects these expressions where cc is an i1 value:
7393 //
7394 //   (select cc 0, y)   [AllOnes=0]
7395 //   (select cc y, 0)   [AllOnes=0]
7396 //   (zext cc)          [AllOnes=0]
7397 //   (sext cc)          [AllOnes=0/1]
7398 //   (select cc -1, y)  [AllOnes=1]
7399 //   (select cc y, -1)  [AllOnes=1]
7400 //
7401 // Invert is set when N is the null/all ones constant when CC is false.
7402 // OtherOp is set to the alternative value of N.
7403 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7404                                        SDValue &CC, bool &Invert,
7405                                        SDValue &OtherOp,
7406                                        SelectionDAG &DAG) {
7407   switch (N->getOpcode()) {
7408   default: return false;
7409   case ISD::SELECT: {
7410     CC = N->getOperand(0);
7411     SDValue N1 = N->getOperand(1);
7412     SDValue N2 = N->getOperand(2);
7413     if (isZeroOrAllOnes(N1, AllOnes)) {
7414       Invert = false;
7415       OtherOp = N2;
7416       return true;
7417     }
7418     if (isZeroOrAllOnes(N2, AllOnes)) {
7419       Invert = true;
7420       OtherOp = N1;
7421       return true;
7422     }
7423     return false;
7424   }
7425   case ISD::ZERO_EXTEND:
7426     // (zext cc) can never be the all ones value.
7427     if (AllOnes)
7428       return false;
7429     // Fall through.
7430   case ISD::SIGN_EXTEND: {
7431     EVT VT = N->getValueType(0);
7432     CC = N->getOperand(0);
7433     if (CC.getValueType() != MVT::i1)
7434       return false;
7435     Invert = !AllOnes;
7436     if (AllOnes)
7437       // When looking for an AllOnes constant, N is an sext, and the 'other'
7438       // value is 0.
7439       OtherOp = DAG.getConstant(0, VT);
7440     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7441       // When looking for a 0 constant, N can be zext or sext.
7442       OtherOp = DAG.getConstant(1, VT);
7443     else
7444       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7445     return true;
7446   }
7447   }
7448 }
7449
7450 // Combine a constant select operand into its use:
7451 //
7452 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7453 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7454 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7455 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7456 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7457 //
7458 // The transform is rejected if the select doesn't have a constant operand that
7459 // is null, or all ones when AllOnes is set.
7460 //
7461 // Also recognize sext/zext from i1:
7462 //
7463 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7464 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7465 //
7466 // These transformations eventually create predicated instructions.
7467 //
7468 // @param N       The node to transform.
7469 // @param Slct    The N operand that is a select.
7470 // @param OtherOp The other N operand (x above).
7471 // @param DCI     Context.
7472 // @param AllOnes Require the select constant to be all ones instead of null.
7473 // @returns The new node, or SDValue() on failure.
7474 static
7475 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7476                             TargetLowering::DAGCombinerInfo &DCI,
7477                             bool AllOnes = false) {
7478   SelectionDAG &DAG = DCI.DAG;
7479   EVT VT = N->getValueType(0);
7480   SDValue NonConstantVal;
7481   SDValue CCOp;
7482   bool SwapSelectOps;
7483   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7484                                   NonConstantVal, DAG))
7485     return SDValue();
7486
7487   // Slct is now know to be the desired identity constant when CC is true.
7488   SDValue TrueVal = OtherOp;
7489   SDValue FalseVal = DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT,
7490                                  OtherOp, NonConstantVal);
7491   // Unless SwapSelectOps says CC should be false.
7492   if (SwapSelectOps)
7493     std::swap(TrueVal, FalseVal);
7494
7495   return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
7496                      CCOp, TrueVal, FalseVal);
7497 }
7498
7499 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7500 static
7501 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7502                                        TargetLowering::DAGCombinerInfo &DCI) {
7503   SDValue N0 = N->getOperand(0);
7504   SDValue N1 = N->getOperand(1);
7505   if (N0.getNode()->hasOneUse()) {
7506     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7507     if (Result.getNode())
7508       return Result;
7509   }
7510   if (N1.getNode()->hasOneUse()) {
7511     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7512     if (Result.getNode())
7513       return Result;
7514   }
7515   return SDValue();
7516 }
7517
7518 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7519 // (only after legalization).
7520 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7521                                  TargetLowering::DAGCombinerInfo &DCI,
7522                                  const ARMSubtarget *Subtarget) {
7523
7524   // Only perform optimization if after legalize, and if NEON is available. We
7525   // also expected both operands to be BUILD_VECTORs.
7526   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7527       || N0.getOpcode() != ISD::BUILD_VECTOR
7528       || N1.getOpcode() != ISD::BUILD_VECTOR)
7529     return SDValue();
7530
7531   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7532   EVT VT = N->getValueType(0);
7533   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7534     return SDValue();
7535
7536   // Check that the vector operands are of the right form.
7537   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7538   // operands, where N is the size of the formed vector.
7539   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7540   // index such that we have a pair wise add pattern.
7541
7542   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7543   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7544     return SDValue();
7545   SDValue Vec = N0->getOperand(0)->getOperand(0);
7546   SDNode *V = Vec.getNode();
7547   unsigned nextIndex = 0;
7548
7549   // For each operands to the ADD which are BUILD_VECTORs,
7550   // check to see if each of their operands are an EXTRACT_VECTOR with
7551   // the same vector and appropriate index.
7552   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7553     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7554         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7555
7556       SDValue ExtVec0 = N0->getOperand(i);
7557       SDValue ExtVec1 = N1->getOperand(i);
7558
7559       // First operand is the vector, verify its the same.
7560       if (V != ExtVec0->getOperand(0).getNode() ||
7561           V != ExtVec1->getOperand(0).getNode())
7562         return SDValue();
7563
7564       // Second is the constant, verify its correct.
7565       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7566       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7567
7568       // For the constant, we want to see all the even or all the odd.
7569       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7570           || C1->getZExtValue() != nextIndex+1)
7571         return SDValue();
7572
7573       // Increment index.
7574       nextIndex+=2;
7575     } else
7576       return SDValue();
7577   }
7578
7579   // Create VPADDL node.
7580   SelectionDAG &DAG = DCI.DAG;
7581   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7582
7583   // Build operand list.
7584   SmallVector<SDValue, 8> Ops;
7585   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7586                                 TLI.getPointerTy()));
7587
7588   // Input is the vector.
7589   Ops.push_back(Vec);
7590
7591   // Get widened type and narrowed type.
7592   MVT widenType;
7593   unsigned numElem = VT.getVectorNumElements();
7594   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
7595     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7596     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7597     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7598     default:
7599       llvm_unreachable("Invalid vector element type for padd optimization.");
7600   }
7601
7602   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7603                             widenType, &Ops[0], Ops.size());
7604   return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
7605 }
7606
7607 static SDValue findMUL_LOHI(SDValue V) {
7608   if (V->getOpcode() == ISD::UMUL_LOHI ||
7609       V->getOpcode() == ISD::SMUL_LOHI)
7610     return V;
7611   return SDValue();
7612 }
7613
7614 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7615                                      TargetLowering::DAGCombinerInfo &DCI,
7616                                      const ARMSubtarget *Subtarget) {
7617
7618   if (Subtarget->isThumb1Only()) return SDValue();
7619
7620   // Only perform the checks after legalize when the pattern is available.
7621   if (DCI.isBeforeLegalize()) return SDValue();
7622
7623   // Look for multiply add opportunities.
7624   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7625   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7626   // a glue link from the first add to the second add.
7627   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7628   // a S/UMLAL instruction.
7629   //          loAdd   UMUL_LOHI
7630   //            \    / :lo    \ :hi
7631   //             \  /          \          [no multiline comment]
7632   //              ADDC         |  hiAdd
7633   //                 \ :glue  /  /
7634   //                  \      /  /
7635   //                    ADDE
7636   //
7637   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7638   SDValue AddcOp0 = AddcNode->getOperand(0);
7639   SDValue AddcOp1 = AddcNode->getOperand(1);
7640
7641   // Check if the two operands are from the same mul_lohi node.
7642   if (AddcOp0.getNode() == AddcOp1.getNode())
7643     return SDValue();
7644
7645   assert(AddcNode->getNumValues() == 2 &&
7646          AddcNode->getValueType(0) == MVT::i32 &&
7647          AddcNode->getValueType(1) == MVT::Glue &&
7648          "Expect ADDC with two result values: i32, glue");
7649
7650   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7651   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7652       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7653       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7654       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7655     return SDValue();
7656
7657   // Look for the glued ADDE.
7658   SDNode* AddeNode = AddcNode->getGluedUser();
7659   if (AddeNode == NULL)
7660     return SDValue();
7661
7662   // Make sure it is really an ADDE.
7663   if (AddeNode->getOpcode() != ISD::ADDE)
7664     return SDValue();
7665
7666   assert(AddeNode->getNumOperands() == 3 &&
7667          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7668          "ADDE node has the wrong inputs");
7669
7670   // Check for the triangle shape.
7671   SDValue AddeOp0 = AddeNode->getOperand(0);
7672   SDValue AddeOp1 = AddeNode->getOperand(1);
7673
7674   // Make sure that the ADDE operands are not coming from the same node.
7675   if (AddeOp0.getNode() == AddeOp1.getNode())
7676     return SDValue();
7677
7678   // Find the MUL_LOHI node walking up ADDE's operands.
7679   bool IsLeftOperandMUL = false;
7680   SDValue MULOp = findMUL_LOHI(AddeOp0);
7681   if (MULOp == SDValue())
7682    MULOp = findMUL_LOHI(AddeOp1);
7683   else
7684     IsLeftOperandMUL = true;
7685   if (MULOp == SDValue())
7686      return SDValue();
7687
7688   // Figure out the right opcode.
7689   unsigned Opc = MULOp->getOpcode();
7690   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7691
7692   // Figure out the high and low input values to the MLAL node.
7693   SDValue* HiMul = &MULOp;
7694   SDValue* HiAdd = NULL;
7695   SDValue* LoMul = NULL;
7696   SDValue* LowAdd = NULL;
7697
7698   if (IsLeftOperandMUL)
7699     HiAdd = &AddeOp1;
7700   else
7701     HiAdd = &AddeOp0;
7702
7703
7704   if (AddcOp0->getOpcode() == Opc) {
7705     LoMul = &AddcOp0;
7706     LowAdd = &AddcOp1;
7707   }
7708   if (AddcOp1->getOpcode() == Opc) {
7709     LoMul = &AddcOp1;
7710     LowAdd = &AddcOp0;
7711   }
7712
7713   if (LoMul == NULL)
7714     return SDValue();
7715
7716   if (LoMul->getNode() != HiMul->getNode())
7717     return SDValue();
7718
7719   // Create the merged node.
7720   SelectionDAG &DAG = DCI.DAG;
7721
7722   // Build operand list.
7723   SmallVector<SDValue, 8> Ops;
7724   Ops.push_back(LoMul->getOperand(0));
7725   Ops.push_back(LoMul->getOperand(1));
7726   Ops.push_back(*LowAdd);
7727   Ops.push_back(*HiAdd);
7728
7729   SDValue MLALNode =  DAG.getNode(FinalOpc, AddcNode->getDebugLoc(),
7730                                  DAG.getVTList(MVT::i32, MVT::i32),
7731                                  &Ops[0], Ops.size());
7732
7733   // Replace the ADDs' nodes uses by the MLA node's values.
7734   SDValue HiMLALResult(MLALNode.getNode(), 1);
7735   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7736
7737   SDValue LoMLALResult(MLALNode.getNode(), 0);
7738   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7739
7740   // Return original node to notify the driver to stop replacing.
7741   SDValue resNode(AddcNode, 0);
7742   return resNode;
7743 }
7744
7745 /// PerformADDCCombine - Target-specific dag combine transform from
7746 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7747 static SDValue PerformADDCCombine(SDNode *N,
7748                                  TargetLowering::DAGCombinerInfo &DCI,
7749                                  const ARMSubtarget *Subtarget) {
7750
7751   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7752
7753 }
7754
7755 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7756 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
7757 /// called with the default operands, and if that fails, with commuted
7758 /// operands.
7759 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7760                                           TargetLowering::DAGCombinerInfo &DCI,
7761                                           const ARMSubtarget *Subtarget){
7762
7763   // Attempt to create vpaddl for this add.
7764   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7765   if (Result.getNode())
7766     return Result;
7767
7768   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7769   if (N0.getNode()->hasOneUse()) {
7770     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7771     if (Result.getNode()) return Result;
7772   }
7773   return SDValue();
7774 }
7775
7776 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7777 ///
7778 static SDValue PerformADDCombine(SDNode *N,
7779                                  TargetLowering::DAGCombinerInfo &DCI,
7780                                  const ARMSubtarget *Subtarget) {
7781   SDValue N0 = N->getOperand(0);
7782   SDValue N1 = N->getOperand(1);
7783
7784   // First try with the default operand order.
7785   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7786   if (Result.getNode())
7787     return Result;
7788
7789   // If that didn't work, try again with the operands commuted.
7790   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7791 }
7792
7793 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7794 ///
7795 static SDValue PerformSUBCombine(SDNode *N,
7796                                  TargetLowering::DAGCombinerInfo &DCI) {
7797   SDValue N0 = N->getOperand(0);
7798   SDValue N1 = N->getOperand(1);
7799
7800   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7801   if (N1.getNode()->hasOneUse()) {
7802     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7803     if (Result.getNode()) return Result;
7804   }
7805
7806   return SDValue();
7807 }
7808
7809 /// PerformVMULCombine
7810 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7811 /// special multiplier accumulator forwarding.
7812 ///   vmul d3, d0, d2
7813 ///   vmla d3, d1, d2
7814 /// is faster than
7815 ///   vadd d3, d0, d1
7816 ///   vmul d3, d3, d2
7817 static SDValue PerformVMULCombine(SDNode *N,
7818                                   TargetLowering::DAGCombinerInfo &DCI,
7819                                   const ARMSubtarget *Subtarget) {
7820   if (!Subtarget->hasVMLxForwarding())
7821     return SDValue();
7822
7823   SelectionDAG &DAG = DCI.DAG;
7824   SDValue N0 = N->getOperand(0);
7825   SDValue N1 = N->getOperand(1);
7826   unsigned Opcode = N0.getOpcode();
7827   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7828       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7829     Opcode = N1.getOpcode();
7830     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7831         Opcode != ISD::FADD && Opcode != ISD::FSUB)
7832       return SDValue();
7833     std::swap(N0, N1);
7834   }
7835
7836   EVT VT = N->getValueType(0);
7837   DebugLoc DL = N->getDebugLoc();
7838   SDValue N00 = N0->getOperand(0);
7839   SDValue N01 = N0->getOperand(1);
7840   return DAG.getNode(Opcode, DL, VT,
7841                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7842                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7843 }
7844
7845 static SDValue PerformMULCombine(SDNode *N,
7846                                  TargetLowering::DAGCombinerInfo &DCI,
7847                                  const ARMSubtarget *Subtarget) {
7848   SelectionDAG &DAG = DCI.DAG;
7849
7850   if (Subtarget->isThumb1Only())
7851     return SDValue();
7852
7853   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7854     return SDValue();
7855
7856   EVT VT = N->getValueType(0);
7857   if (VT.is64BitVector() || VT.is128BitVector())
7858     return PerformVMULCombine(N, DCI, Subtarget);
7859   if (VT != MVT::i32)
7860     return SDValue();
7861
7862   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7863   if (!C)
7864     return SDValue();
7865
7866   int64_t MulAmt = C->getSExtValue();
7867   unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
7868
7869   ShiftAmt = ShiftAmt & (32 - 1);
7870   SDValue V = N->getOperand(0);
7871   DebugLoc DL = N->getDebugLoc();
7872
7873   SDValue Res;
7874   MulAmt >>= ShiftAmt;
7875
7876   if (MulAmt >= 0) {
7877     if (isPowerOf2_32(MulAmt - 1)) {
7878       // (mul x, 2^N + 1) => (add (shl x, N), x)
7879       Res = DAG.getNode(ISD::ADD, DL, VT,
7880                         V,
7881                         DAG.getNode(ISD::SHL, DL, VT,
7882                                     V,
7883                                     DAG.getConstant(Log2_32(MulAmt - 1),
7884                                                     MVT::i32)));
7885     } else if (isPowerOf2_32(MulAmt + 1)) {
7886       // (mul x, 2^N - 1) => (sub (shl x, N), x)
7887       Res = DAG.getNode(ISD::SUB, DL, VT,
7888                         DAG.getNode(ISD::SHL, DL, VT,
7889                                     V,
7890                                     DAG.getConstant(Log2_32(MulAmt + 1),
7891                                                     MVT::i32)),
7892                         V);
7893     } else
7894       return SDValue();
7895   } else {
7896     uint64_t MulAmtAbs = -MulAmt;
7897     if (isPowerOf2_32(MulAmtAbs + 1)) {
7898       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7899       Res = DAG.getNode(ISD::SUB, DL, VT,
7900                         V,
7901                         DAG.getNode(ISD::SHL, DL, VT,
7902                                     V,
7903                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
7904                                                     MVT::i32)));
7905     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
7906       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7907       Res = DAG.getNode(ISD::ADD, DL, VT,
7908                         V,
7909                         DAG.getNode(ISD::SHL, DL, VT,
7910                                     V,
7911                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
7912                                                     MVT::i32)));
7913       Res = DAG.getNode(ISD::SUB, DL, VT,
7914                         DAG.getConstant(0, MVT::i32),Res);
7915
7916     } else
7917       return SDValue();
7918   }
7919
7920   if (ShiftAmt != 0)
7921     Res = DAG.getNode(ISD::SHL, DL, VT,
7922                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
7923
7924   // Do not add new nodes to DAG combiner worklist.
7925   DCI.CombineTo(N, Res, false);
7926   return SDValue();
7927 }
7928
7929 static SDValue PerformANDCombine(SDNode *N,
7930                                  TargetLowering::DAGCombinerInfo &DCI,
7931                                  const ARMSubtarget *Subtarget) {
7932
7933   // Attempt to use immediate-form VBIC
7934   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7935   DebugLoc dl = N->getDebugLoc();
7936   EVT VT = N->getValueType(0);
7937   SelectionDAG &DAG = DCI.DAG;
7938
7939   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7940     return SDValue();
7941
7942   APInt SplatBits, SplatUndef;
7943   unsigned SplatBitSize;
7944   bool HasAnyUndefs;
7945   if (BVN &&
7946       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7947     if (SplatBitSize <= 64) {
7948       EVT VbicVT;
7949       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
7950                                       SplatUndef.getZExtValue(), SplatBitSize,
7951                                       DAG, VbicVT, VT.is128BitVector(),
7952                                       OtherModImm);
7953       if (Val.getNode()) {
7954         SDValue Input =
7955           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
7956         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
7957         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
7958       }
7959     }
7960   }
7961
7962   if (!Subtarget->isThumb1Only()) {
7963     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
7964     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
7965     if (Result.getNode())
7966       return Result;
7967   }
7968
7969   return SDValue();
7970 }
7971
7972 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
7973 static SDValue PerformORCombine(SDNode *N,
7974                                 TargetLowering::DAGCombinerInfo &DCI,
7975                                 const ARMSubtarget *Subtarget) {
7976   // Attempt to use immediate-form VORR
7977   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7978   DebugLoc dl = N->getDebugLoc();
7979   EVT VT = N->getValueType(0);
7980   SelectionDAG &DAG = DCI.DAG;
7981
7982   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7983     return SDValue();
7984
7985   APInt SplatBits, SplatUndef;
7986   unsigned SplatBitSize;
7987   bool HasAnyUndefs;
7988   if (BVN && Subtarget->hasNEON() &&
7989       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7990     if (SplatBitSize <= 64) {
7991       EVT VorrVT;
7992       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
7993                                       SplatUndef.getZExtValue(), SplatBitSize,
7994                                       DAG, VorrVT, VT.is128BitVector(),
7995                                       OtherModImm);
7996       if (Val.getNode()) {
7997         SDValue Input =
7998           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
7999         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8000         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8001       }
8002     }
8003   }
8004
8005   if (!Subtarget->isThumb1Only()) {
8006     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8007     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8008     if (Result.getNode())
8009       return Result;
8010   }
8011
8012   // The code below optimizes (or (and X, Y), Z).
8013   // The AND operand needs to have a single user to make these optimizations
8014   // profitable.
8015   SDValue N0 = N->getOperand(0);
8016   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8017     return SDValue();
8018   SDValue N1 = N->getOperand(1);
8019
8020   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8021   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8022       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8023     APInt SplatUndef;
8024     unsigned SplatBitSize;
8025     bool HasAnyUndefs;
8026
8027     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8028     APInt SplatBits0;
8029     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8030                                   HasAnyUndefs) && !HasAnyUndefs) {
8031       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8032       APInt SplatBits1;
8033       if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8034                                     HasAnyUndefs) && !HasAnyUndefs &&
8035           SplatBits0 == ~SplatBits1) {
8036         // Canonicalize the vector type to make instruction selection simpler.
8037         EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8038         SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8039                                      N0->getOperand(1), N0->getOperand(0),
8040                                      N1->getOperand(0));
8041         return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8042       }
8043     }
8044   }
8045
8046   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8047   // reasonable.
8048
8049   // BFI is only available on V6T2+
8050   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8051     return SDValue();
8052
8053   DebugLoc DL = N->getDebugLoc();
8054   // 1) or (and A, mask), val => ARMbfi A, val, mask
8055   //      iff (val & mask) == val
8056   //
8057   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8058   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8059   //          && mask == ~mask2
8060   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8061   //          && ~mask == mask2
8062   //  (i.e., copy a bitfield value into another bitfield of the same width)
8063
8064   if (VT != MVT::i32)
8065     return SDValue();
8066
8067   SDValue N00 = N0.getOperand(0);
8068
8069   // The value and the mask need to be constants so we can verify this is
8070   // actually a bitfield set. If the mask is 0xffff, we can do better
8071   // via a movt instruction, so don't use BFI in that case.
8072   SDValue MaskOp = N0.getOperand(1);
8073   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8074   if (!MaskC)
8075     return SDValue();
8076   unsigned Mask = MaskC->getZExtValue();
8077   if (Mask == 0xffff)
8078     return SDValue();
8079   SDValue Res;
8080   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8081   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8082   if (N1C) {
8083     unsigned Val = N1C->getZExtValue();
8084     if ((Val & ~Mask) != Val)
8085       return SDValue();
8086
8087     if (ARM::isBitFieldInvertedMask(Mask)) {
8088       Val >>= CountTrailingZeros_32(~Mask);
8089
8090       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8091                         DAG.getConstant(Val, MVT::i32),
8092                         DAG.getConstant(Mask, MVT::i32));
8093
8094       // Do not add new nodes to DAG combiner worklist.
8095       DCI.CombineTo(N, Res, false);
8096       return SDValue();
8097     }
8098   } else if (N1.getOpcode() == ISD::AND) {
8099     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8100     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8101     if (!N11C)
8102       return SDValue();
8103     unsigned Mask2 = N11C->getZExtValue();
8104
8105     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8106     // as is to match.
8107     if (ARM::isBitFieldInvertedMask(Mask) &&
8108         (Mask == ~Mask2)) {
8109       // The pack halfword instruction works better for masks that fit it,
8110       // so use that when it's available.
8111       if (Subtarget->hasT2ExtractPack() &&
8112           (Mask == 0xffff || Mask == 0xffff0000))
8113         return SDValue();
8114       // 2a
8115       unsigned amt = CountTrailingZeros_32(Mask2);
8116       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8117                         DAG.getConstant(amt, MVT::i32));
8118       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8119                         DAG.getConstant(Mask, MVT::i32));
8120       // Do not add new nodes to DAG combiner worklist.
8121       DCI.CombineTo(N, Res, false);
8122       return SDValue();
8123     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8124                (~Mask == Mask2)) {
8125       // The pack halfword instruction works better for masks that fit it,
8126       // so use that when it's available.
8127       if (Subtarget->hasT2ExtractPack() &&
8128           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8129         return SDValue();
8130       // 2b
8131       unsigned lsb = CountTrailingZeros_32(Mask);
8132       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8133                         DAG.getConstant(lsb, MVT::i32));
8134       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8135                         DAG.getConstant(Mask2, MVT::i32));
8136       // Do not add new nodes to DAG combiner worklist.
8137       DCI.CombineTo(N, Res, false);
8138       return SDValue();
8139     }
8140   }
8141
8142   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8143       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8144       ARM::isBitFieldInvertedMask(~Mask)) {
8145     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8146     // where lsb(mask) == #shamt and masked bits of B are known zero.
8147     SDValue ShAmt = N00.getOperand(1);
8148     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8149     unsigned LSB = CountTrailingZeros_32(Mask);
8150     if (ShAmtC != LSB)
8151       return SDValue();
8152
8153     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8154                       DAG.getConstant(~Mask, MVT::i32));
8155
8156     // Do not add new nodes to DAG combiner worklist.
8157     DCI.CombineTo(N, Res, false);
8158   }
8159
8160   return SDValue();
8161 }
8162
8163 static SDValue PerformXORCombine(SDNode *N,
8164                                  TargetLowering::DAGCombinerInfo &DCI,
8165                                  const ARMSubtarget *Subtarget) {
8166   EVT VT = N->getValueType(0);
8167   SelectionDAG &DAG = DCI.DAG;
8168
8169   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8170     return SDValue();
8171
8172   if (!Subtarget->isThumb1Only()) {
8173     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8174     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8175     if (Result.getNode())
8176       return Result;
8177   }
8178
8179   return SDValue();
8180 }
8181
8182 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8183 /// the bits being cleared by the AND are not demanded by the BFI.
8184 static SDValue PerformBFICombine(SDNode *N,
8185                                  TargetLowering::DAGCombinerInfo &DCI) {
8186   SDValue N1 = N->getOperand(1);
8187   if (N1.getOpcode() == ISD::AND) {
8188     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8189     if (!N11C)
8190       return SDValue();
8191     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8192     unsigned LSB = CountTrailingZeros_32(~InvMask);
8193     unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
8194     unsigned Mask = (1 << Width)-1;
8195     unsigned Mask2 = N11C->getZExtValue();
8196     if ((Mask & (~Mask2)) == 0)
8197       return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
8198                              N->getOperand(0), N1.getOperand(0),
8199                              N->getOperand(2));
8200   }
8201   return SDValue();
8202 }
8203
8204 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8205 /// ARMISD::VMOVRRD.
8206 static SDValue PerformVMOVRRDCombine(SDNode *N,
8207                                      TargetLowering::DAGCombinerInfo &DCI) {
8208   // vmovrrd(vmovdrr x, y) -> x,y
8209   SDValue InDouble = N->getOperand(0);
8210   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8211     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8212
8213   // vmovrrd(load f64) -> (load i32), (load i32)
8214   SDNode *InNode = InDouble.getNode();
8215   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8216       InNode->getValueType(0) == MVT::f64 &&
8217       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8218       !cast<LoadSDNode>(InNode)->isVolatile()) {
8219     // TODO: Should this be done for non-FrameIndex operands?
8220     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8221
8222     SelectionDAG &DAG = DCI.DAG;
8223     DebugLoc DL = LD->getDebugLoc();
8224     SDValue BasePtr = LD->getBasePtr();
8225     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8226                                  LD->getPointerInfo(), LD->isVolatile(),
8227                                  LD->isNonTemporal(), LD->isInvariant(),
8228                                  LD->getAlignment());
8229
8230     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8231                                     DAG.getConstant(4, MVT::i32));
8232     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8233                                  LD->getPointerInfo(), LD->isVolatile(),
8234                                  LD->isNonTemporal(), LD->isInvariant(),
8235                                  std::min(4U, LD->getAlignment() / 2));
8236
8237     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8238     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8239     DCI.RemoveFromWorklist(LD);
8240     DAG.DeleteNode(LD);
8241     return Result;
8242   }
8243
8244   return SDValue();
8245 }
8246
8247 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8248 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8249 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8250   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8251   SDValue Op0 = N->getOperand(0);
8252   SDValue Op1 = N->getOperand(1);
8253   if (Op0.getOpcode() == ISD::BITCAST)
8254     Op0 = Op0.getOperand(0);
8255   if (Op1.getOpcode() == ISD::BITCAST)
8256     Op1 = Op1.getOperand(0);
8257   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8258       Op0.getNode() == Op1.getNode() &&
8259       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8260     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
8261                        N->getValueType(0), Op0.getOperand(0));
8262   return SDValue();
8263 }
8264
8265 /// PerformSTORECombine - Target-specific dag combine xforms for
8266 /// ISD::STORE.
8267 static SDValue PerformSTORECombine(SDNode *N,
8268                                    TargetLowering::DAGCombinerInfo &DCI) {
8269   StoreSDNode *St = cast<StoreSDNode>(N);
8270   if (St->isVolatile())
8271     return SDValue();
8272
8273   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8274   // pack all of the elements in one place.  Next, store to memory in fewer
8275   // chunks.
8276   SDValue StVal = St->getValue();
8277   EVT VT = StVal.getValueType();
8278   if (St->isTruncatingStore() && VT.isVector()) {
8279     SelectionDAG &DAG = DCI.DAG;
8280     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8281     EVT StVT = St->getMemoryVT();
8282     unsigned NumElems = VT.getVectorNumElements();
8283     assert(StVT != VT && "Cannot truncate to the same type");
8284     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8285     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8286
8287     // From, To sizes and ElemCount must be pow of two
8288     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8289
8290     // We are going to use the original vector elt for storing.
8291     // Accumulated smaller vector elements must be a multiple of the store size.
8292     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8293
8294     unsigned SizeRatio  = FromEltSz / ToEltSz;
8295     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8296
8297     // Create a type on which we perform the shuffle.
8298     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8299                                      NumElems*SizeRatio);
8300     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8301
8302     DebugLoc DL = St->getDebugLoc();
8303     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8304     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8305     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8306
8307     // Can't shuffle using an illegal type.
8308     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8309
8310     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8311                                 DAG.getUNDEF(WideVec.getValueType()),
8312                                 ShuffleVec.data());
8313     // At this point all of the data is stored at the bottom of the
8314     // register. We now need to save it to mem.
8315
8316     // Find the largest store unit
8317     MVT StoreType = MVT::i8;
8318     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8319          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8320       MVT Tp = (MVT::SimpleValueType)tp;
8321       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8322         StoreType = Tp;
8323     }
8324     // Didn't find a legal store type.
8325     if (!TLI.isTypeLegal(StoreType))
8326       return SDValue();
8327
8328     // Bitcast the original vector into a vector of store-size units
8329     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8330             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8331     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8332     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8333     SmallVector<SDValue, 8> Chains;
8334     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8335                                         TLI.getPointerTy());
8336     SDValue BasePtr = St->getBasePtr();
8337
8338     // Perform one or more big stores into memory.
8339     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8340     for (unsigned I = 0; I < E; I++) {
8341       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8342                                    StoreType, ShuffWide,
8343                                    DAG.getIntPtrConstant(I));
8344       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8345                                 St->getPointerInfo(), St->isVolatile(),
8346                                 St->isNonTemporal(), St->getAlignment());
8347       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8348                             Increment);
8349       Chains.push_back(Ch);
8350     }
8351     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
8352                        Chains.size());
8353   }
8354
8355   if (!ISD::isNormalStore(St))
8356     return SDValue();
8357
8358   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8359   // ARM stores of arguments in the same cache line.
8360   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8361       StVal.getNode()->hasOneUse()) {
8362     SelectionDAG  &DAG = DCI.DAG;
8363     DebugLoc DL = St->getDebugLoc();
8364     SDValue BasePtr = St->getBasePtr();
8365     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8366                                   StVal.getNode()->getOperand(0), BasePtr,
8367                                   St->getPointerInfo(), St->isVolatile(),
8368                                   St->isNonTemporal(), St->getAlignment());
8369
8370     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8371                                     DAG.getConstant(4, MVT::i32));
8372     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
8373                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8374                         St->isNonTemporal(),
8375                         std::min(4U, St->getAlignment() / 2));
8376   }
8377
8378   if (StVal.getValueType() != MVT::i64 ||
8379       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8380     return SDValue();
8381
8382   // Bitcast an i64 store extracted from a vector to f64.
8383   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8384   SelectionDAG &DAG = DCI.DAG;
8385   DebugLoc dl = StVal.getDebugLoc();
8386   SDValue IntVec = StVal.getOperand(0);
8387   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8388                                  IntVec.getValueType().getVectorNumElements());
8389   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8390   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8391                                Vec, StVal.getOperand(1));
8392   dl = N->getDebugLoc();
8393   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8394   // Make the DAGCombiner fold the bitcasts.
8395   DCI.AddToWorklist(Vec.getNode());
8396   DCI.AddToWorklist(ExtElt.getNode());
8397   DCI.AddToWorklist(V.getNode());
8398   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8399                       St->getPointerInfo(), St->isVolatile(),
8400                       St->isNonTemporal(), St->getAlignment(),
8401                       St->getTBAAInfo());
8402 }
8403
8404 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8405 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8406 /// i64 vector to have f64 elements, since the value can then be loaded
8407 /// directly into a VFP register.
8408 static bool hasNormalLoadOperand(SDNode *N) {
8409   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8410   for (unsigned i = 0; i < NumElts; ++i) {
8411     SDNode *Elt = N->getOperand(i).getNode();
8412     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8413       return true;
8414   }
8415   return false;
8416 }
8417
8418 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8419 /// ISD::BUILD_VECTOR.
8420 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8421                                           TargetLowering::DAGCombinerInfo &DCI){
8422   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8423   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8424   // into a pair of GPRs, which is fine when the value is used as a scalar,
8425   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8426   SelectionDAG &DAG = DCI.DAG;
8427   if (N->getNumOperands() == 2) {
8428     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8429     if (RV.getNode())
8430       return RV;
8431   }
8432
8433   // Load i64 elements as f64 values so that type legalization does not split
8434   // them up into i32 values.
8435   EVT VT = N->getValueType(0);
8436   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8437     return SDValue();
8438   DebugLoc dl = N->getDebugLoc();
8439   SmallVector<SDValue, 8> Ops;
8440   unsigned NumElts = VT.getVectorNumElements();
8441   for (unsigned i = 0; i < NumElts; ++i) {
8442     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8443     Ops.push_back(V);
8444     // Make the DAGCombiner fold the bitcast.
8445     DCI.AddToWorklist(V.getNode());
8446   }
8447   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8448   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
8449   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8450 }
8451
8452 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8453 /// ISD::INSERT_VECTOR_ELT.
8454 static SDValue PerformInsertEltCombine(SDNode *N,
8455                                        TargetLowering::DAGCombinerInfo &DCI) {
8456   // Bitcast an i64 load inserted into a vector to f64.
8457   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8458   EVT VT = N->getValueType(0);
8459   SDNode *Elt = N->getOperand(1).getNode();
8460   if (VT.getVectorElementType() != MVT::i64 ||
8461       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8462     return SDValue();
8463
8464   SelectionDAG &DAG = DCI.DAG;
8465   DebugLoc dl = N->getDebugLoc();
8466   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8467                                  VT.getVectorNumElements());
8468   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8469   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8470   // Make the DAGCombiner fold the bitcasts.
8471   DCI.AddToWorklist(Vec.getNode());
8472   DCI.AddToWorklist(V.getNode());
8473   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8474                                Vec, V, N->getOperand(2));
8475   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8476 }
8477
8478 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8479 /// ISD::VECTOR_SHUFFLE.
8480 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8481   // The LLVM shufflevector instruction does not require the shuffle mask
8482   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8483   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8484   // operands do not match the mask length, they are extended by concatenating
8485   // them with undef vectors.  That is probably the right thing for other
8486   // targets, but for NEON it is better to concatenate two double-register
8487   // size vector operands into a single quad-register size vector.  Do that
8488   // transformation here:
8489   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8490   //   shuffle(concat(v1, v2), undef)
8491   SDValue Op0 = N->getOperand(0);
8492   SDValue Op1 = N->getOperand(1);
8493   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8494       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8495       Op0.getNumOperands() != 2 ||
8496       Op1.getNumOperands() != 2)
8497     return SDValue();
8498   SDValue Concat0Op1 = Op0.getOperand(1);
8499   SDValue Concat1Op1 = Op1.getOperand(1);
8500   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8501       Concat1Op1.getOpcode() != ISD::UNDEF)
8502     return SDValue();
8503   // Skip the transformation if any of the types are illegal.
8504   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8505   EVT VT = N->getValueType(0);
8506   if (!TLI.isTypeLegal(VT) ||
8507       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8508       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8509     return SDValue();
8510
8511   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
8512                                   Op0.getOperand(0), Op1.getOperand(0));
8513   // Translate the shuffle mask.
8514   SmallVector<int, 16> NewMask;
8515   unsigned NumElts = VT.getVectorNumElements();
8516   unsigned HalfElts = NumElts/2;
8517   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8518   for (unsigned n = 0; n < NumElts; ++n) {
8519     int MaskElt = SVN->getMaskElt(n);
8520     int NewElt = -1;
8521     if (MaskElt < (int)HalfElts)
8522       NewElt = MaskElt;
8523     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8524       NewElt = HalfElts + MaskElt - NumElts;
8525     NewMask.push_back(NewElt);
8526   }
8527   return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
8528                               DAG.getUNDEF(VT), NewMask.data());
8529 }
8530
8531 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8532 /// NEON load/store intrinsics to merge base address updates.
8533 static SDValue CombineBaseUpdate(SDNode *N,
8534                                  TargetLowering::DAGCombinerInfo &DCI) {
8535   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8536     return SDValue();
8537
8538   SelectionDAG &DAG = DCI.DAG;
8539   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8540                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8541   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8542   SDValue Addr = N->getOperand(AddrOpIdx);
8543
8544   // Search for a use of the address operand that is an increment.
8545   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8546          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8547     SDNode *User = *UI;
8548     if (User->getOpcode() != ISD::ADD ||
8549         UI.getUse().getResNo() != Addr.getResNo())
8550       continue;
8551
8552     // Check that the add is independent of the load/store.  Otherwise, folding
8553     // it would create a cycle.
8554     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8555       continue;
8556
8557     // Find the new opcode for the updating load/store.
8558     bool isLoad = true;
8559     bool isLaneOp = false;
8560     unsigned NewOpc = 0;
8561     unsigned NumVecs = 0;
8562     if (isIntrinsic) {
8563       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8564       switch (IntNo) {
8565       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8566       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8567         NumVecs = 1; break;
8568       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8569         NumVecs = 2; break;
8570       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8571         NumVecs = 3; break;
8572       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8573         NumVecs = 4; break;
8574       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8575         NumVecs = 2; isLaneOp = true; break;
8576       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8577         NumVecs = 3; isLaneOp = true; break;
8578       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8579         NumVecs = 4; isLaneOp = true; break;
8580       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8581         NumVecs = 1; isLoad = false; break;
8582       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8583         NumVecs = 2; isLoad = false; break;
8584       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8585         NumVecs = 3; isLoad = false; break;
8586       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8587         NumVecs = 4; isLoad = false; break;
8588       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8589         NumVecs = 2; isLoad = false; isLaneOp = true; break;
8590       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8591         NumVecs = 3; isLoad = false; isLaneOp = true; break;
8592       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8593         NumVecs = 4; isLoad = false; isLaneOp = true; break;
8594       }
8595     } else {
8596       isLaneOp = true;
8597       switch (N->getOpcode()) {
8598       default: llvm_unreachable("unexpected opcode for Neon base update");
8599       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8600       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8601       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8602       }
8603     }
8604
8605     // Find the size of memory referenced by the load/store.
8606     EVT VecTy;
8607     if (isLoad)
8608       VecTy = N->getValueType(0);
8609     else
8610       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8611     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8612     if (isLaneOp)
8613       NumBytes /= VecTy.getVectorNumElements();
8614
8615     // If the increment is a constant, it must match the memory ref size.
8616     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8617     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8618       uint64_t IncVal = CInc->getZExtValue();
8619       if (IncVal != NumBytes)
8620         continue;
8621     } else if (NumBytes >= 3 * 16) {
8622       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8623       // separate instructions that make it harder to use a non-constant update.
8624       continue;
8625     }
8626
8627     // Create the new updating load/store node.
8628     EVT Tys[6];
8629     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8630     unsigned n;
8631     for (n = 0; n < NumResultVecs; ++n)
8632       Tys[n] = VecTy;
8633     Tys[n++] = MVT::i32;
8634     Tys[n] = MVT::Other;
8635     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
8636     SmallVector<SDValue, 8> Ops;
8637     Ops.push_back(N->getOperand(0)); // incoming chain
8638     Ops.push_back(N->getOperand(AddrOpIdx));
8639     Ops.push_back(Inc);
8640     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8641       Ops.push_back(N->getOperand(i));
8642     }
8643     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8644     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
8645                                            Ops.data(), Ops.size(),
8646                                            MemInt->getMemoryVT(),
8647                                            MemInt->getMemOperand());
8648
8649     // Update the uses.
8650     std::vector<SDValue> NewResults;
8651     for (unsigned i = 0; i < NumResultVecs; ++i) {
8652       NewResults.push_back(SDValue(UpdN.getNode(), i));
8653     }
8654     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8655     DCI.CombineTo(N, NewResults);
8656     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8657
8658     break;
8659   }
8660   return SDValue();
8661 }
8662
8663 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8664 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8665 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
8666 /// return true.
8667 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8668   SelectionDAG &DAG = DCI.DAG;
8669   EVT VT = N->getValueType(0);
8670   // vldN-dup instructions only support 64-bit vectors for N > 1.
8671   if (!VT.is64BitVector())
8672     return false;
8673
8674   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8675   SDNode *VLD = N->getOperand(0).getNode();
8676   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8677     return false;
8678   unsigned NumVecs = 0;
8679   unsigned NewOpc = 0;
8680   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8681   if (IntNo == Intrinsic::arm_neon_vld2lane) {
8682     NumVecs = 2;
8683     NewOpc = ARMISD::VLD2DUP;
8684   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8685     NumVecs = 3;
8686     NewOpc = ARMISD::VLD3DUP;
8687   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8688     NumVecs = 4;
8689     NewOpc = ARMISD::VLD4DUP;
8690   } else {
8691     return false;
8692   }
8693
8694   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8695   // numbers match the load.
8696   unsigned VLDLaneNo =
8697     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8698   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8699        UI != UE; ++UI) {
8700     // Ignore uses of the chain result.
8701     if (UI.getUse().getResNo() == NumVecs)
8702       continue;
8703     SDNode *User = *UI;
8704     if (User->getOpcode() != ARMISD::VDUPLANE ||
8705         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8706       return false;
8707   }
8708
8709   // Create the vldN-dup node.
8710   EVT Tys[5];
8711   unsigned n;
8712   for (n = 0; n < NumVecs; ++n)
8713     Tys[n] = VT;
8714   Tys[n] = MVT::Other;
8715   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
8716   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8717   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8718   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
8719                                            Ops, 2, VLDMemInt->getMemoryVT(),
8720                                            VLDMemInt->getMemOperand());
8721
8722   // Update the uses.
8723   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8724        UI != UE; ++UI) {
8725     unsigned ResNo = UI.getUse().getResNo();
8726     // Ignore uses of the chain result.
8727     if (ResNo == NumVecs)
8728       continue;
8729     SDNode *User = *UI;
8730     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8731   }
8732
8733   // Now the vldN-lane intrinsic is dead except for its chain result.
8734   // Update uses of the chain.
8735   std::vector<SDValue> VLDDupResults;
8736   for (unsigned n = 0; n < NumVecs; ++n)
8737     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8738   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8739   DCI.CombineTo(VLD, VLDDupResults);
8740
8741   return true;
8742 }
8743
8744 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8745 /// ARMISD::VDUPLANE.
8746 static SDValue PerformVDUPLANECombine(SDNode *N,
8747                                       TargetLowering::DAGCombinerInfo &DCI) {
8748   SDValue Op = N->getOperand(0);
8749
8750   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8751   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8752   if (CombineVLDDUP(N, DCI))
8753     return SDValue(N, 0);
8754
8755   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8756   // redundant.  Ignore bit_converts for now; element sizes are checked below.
8757   while (Op.getOpcode() == ISD::BITCAST)
8758     Op = Op.getOperand(0);
8759   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8760     return SDValue();
8761
8762   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8763   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8764   // The canonical VMOV for a zero vector uses a 32-bit element size.
8765   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8766   unsigned EltBits;
8767   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8768     EltSize = 8;
8769   EVT VT = N->getValueType(0);
8770   if (EltSize > VT.getVectorElementType().getSizeInBits())
8771     return SDValue();
8772
8773   return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
8774 }
8775
8776 // isConstVecPow2 - Return true if each vector element is a power of 2, all
8777 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
8778 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
8779 {
8780   integerPart cN;
8781   integerPart c0 = 0;
8782   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
8783        I != E; I++) {
8784     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
8785     if (!C)
8786       return false;
8787
8788     bool isExact;
8789     APFloat APF = C->getValueAPF();
8790     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
8791         != APFloat::opOK || !isExact)
8792       return false;
8793
8794     c0 = (I == 0) ? cN : c0;
8795     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
8796       return false;
8797   }
8798   C = c0;
8799   return true;
8800 }
8801
8802 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
8803 /// can replace combinations of VMUL and VCVT (floating-point to integer)
8804 /// when the VMUL has a constant operand that is a power of 2.
8805 ///
8806 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8807 ///  vmul.f32        d16, d17, d16
8808 ///  vcvt.s32.f32    d16, d16
8809 /// becomes:
8810 ///  vcvt.s32.f32    d16, d16, #3
8811 static SDValue PerformVCVTCombine(SDNode *N,
8812                                   TargetLowering::DAGCombinerInfo &DCI,
8813                                   const ARMSubtarget *Subtarget) {
8814   SelectionDAG &DAG = DCI.DAG;
8815   SDValue Op = N->getOperand(0);
8816
8817   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
8818       Op.getOpcode() != ISD::FMUL)
8819     return SDValue();
8820
8821   uint64_t C;
8822   SDValue N0 = Op->getOperand(0);
8823   SDValue ConstVec = Op->getOperand(1);
8824   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
8825
8826   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8827       !isConstVecPow2(ConstVec, isSigned, C))
8828     return SDValue();
8829
8830   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
8831     Intrinsic::arm_neon_vcvtfp2fxu;
8832   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8833                      N->getValueType(0),
8834                      DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
8835                      DAG.getConstant(Log2_64(C), MVT::i32));
8836 }
8837
8838 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
8839 /// can replace combinations of VCVT (integer to floating-point) and VDIV
8840 /// when the VDIV has a constant operand that is a power of 2.
8841 ///
8842 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8843 ///  vcvt.f32.s32    d16, d16
8844 ///  vdiv.f32        d16, d17, d16
8845 /// becomes:
8846 ///  vcvt.f32.s32    d16, d16, #3
8847 static SDValue PerformVDIVCombine(SDNode *N,
8848                                   TargetLowering::DAGCombinerInfo &DCI,
8849                                   const ARMSubtarget *Subtarget) {
8850   SelectionDAG &DAG = DCI.DAG;
8851   SDValue Op = N->getOperand(0);
8852   unsigned OpOpcode = Op.getNode()->getOpcode();
8853
8854   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
8855       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
8856     return SDValue();
8857
8858   uint64_t C;
8859   SDValue ConstVec = N->getOperand(1);
8860   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
8861
8862   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8863       !isConstVecPow2(ConstVec, isSigned, C))
8864     return SDValue();
8865
8866   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
8867     Intrinsic::arm_neon_vcvtfxu2fp;
8868   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
8869                      Op.getValueType(),
8870                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
8871                      Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
8872 }
8873
8874 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
8875 /// operand of a vector shift operation, where all the elements of the
8876 /// build_vector must have the same constant integer value.
8877 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8878   // Ignore bit_converts.
8879   while (Op.getOpcode() == ISD::BITCAST)
8880     Op = Op.getOperand(0);
8881   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8882   APInt SplatBits, SplatUndef;
8883   unsigned SplatBitSize;
8884   bool HasAnyUndefs;
8885   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
8886                                       HasAnyUndefs, ElementBits) ||
8887       SplatBitSize > ElementBits)
8888     return false;
8889   Cnt = SplatBits.getSExtValue();
8890   return true;
8891 }
8892
8893 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
8894 /// operand of a vector shift left operation.  That value must be in the range:
8895 ///   0 <= Value < ElementBits for a left shift; or
8896 ///   0 <= Value <= ElementBits for a long left shift.
8897 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8898   assert(VT.isVector() && "vector shift count is not a vector type");
8899   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8900   if (! getVShiftImm(Op, ElementBits, Cnt))
8901     return false;
8902   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
8903 }
8904
8905 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
8906 /// operand of a vector shift right operation.  For a shift opcode, the value
8907 /// is positive, but for an intrinsic the value count must be negative. The
8908 /// absolute value must be in the range:
8909 ///   1 <= |Value| <= ElementBits for a right shift; or
8910 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
8911 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
8912                          int64_t &Cnt) {
8913   assert(VT.isVector() && "vector shift count is not a vector type");
8914   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8915   if (! getVShiftImm(Op, ElementBits, Cnt))
8916     return false;
8917   if (isIntrinsic)
8918     Cnt = -Cnt;
8919   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
8920 }
8921
8922 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
8923 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
8924   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8925   switch (IntNo) {
8926   default:
8927     // Don't do anything for most intrinsics.
8928     break;
8929
8930   // Vector shifts: check for immediate versions and lower them.
8931   // Note: This is done during DAG combining instead of DAG legalizing because
8932   // the build_vectors for 64-bit vector element shift counts are generally
8933   // not legal, and it is hard to see their values after they get legalized to
8934   // loads from a constant pool.
8935   case Intrinsic::arm_neon_vshifts:
8936   case Intrinsic::arm_neon_vshiftu:
8937   case Intrinsic::arm_neon_vshiftls:
8938   case Intrinsic::arm_neon_vshiftlu:
8939   case Intrinsic::arm_neon_vshiftn:
8940   case Intrinsic::arm_neon_vrshifts:
8941   case Intrinsic::arm_neon_vrshiftu:
8942   case Intrinsic::arm_neon_vrshiftn:
8943   case Intrinsic::arm_neon_vqshifts:
8944   case Intrinsic::arm_neon_vqshiftu:
8945   case Intrinsic::arm_neon_vqshiftsu:
8946   case Intrinsic::arm_neon_vqshiftns:
8947   case Intrinsic::arm_neon_vqshiftnu:
8948   case Intrinsic::arm_neon_vqshiftnsu:
8949   case Intrinsic::arm_neon_vqrshiftns:
8950   case Intrinsic::arm_neon_vqrshiftnu:
8951   case Intrinsic::arm_neon_vqrshiftnsu: {
8952     EVT VT = N->getOperand(1).getValueType();
8953     int64_t Cnt;
8954     unsigned VShiftOpc = 0;
8955
8956     switch (IntNo) {
8957     case Intrinsic::arm_neon_vshifts:
8958     case Intrinsic::arm_neon_vshiftu:
8959       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
8960         VShiftOpc = ARMISD::VSHL;
8961         break;
8962       }
8963       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
8964         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
8965                      ARMISD::VSHRs : ARMISD::VSHRu);
8966         break;
8967       }
8968       return SDValue();
8969
8970     case Intrinsic::arm_neon_vshiftls:
8971     case Intrinsic::arm_neon_vshiftlu:
8972       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
8973         break;
8974       llvm_unreachable("invalid shift count for vshll intrinsic");
8975
8976     case Intrinsic::arm_neon_vrshifts:
8977     case Intrinsic::arm_neon_vrshiftu:
8978       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
8979         break;
8980       return SDValue();
8981
8982     case Intrinsic::arm_neon_vqshifts:
8983     case Intrinsic::arm_neon_vqshiftu:
8984       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8985         break;
8986       return SDValue();
8987
8988     case Intrinsic::arm_neon_vqshiftsu:
8989       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
8990         break;
8991       llvm_unreachable("invalid shift count for vqshlu intrinsic");
8992
8993     case Intrinsic::arm_neon_vshiftn:
8994     case Intrinsic::arm_neon_vrshiftn:
8995     case Intrinsic::arm_neon_vqshiftns:
8996     case Intrinsic::arm_neon_vqshiftnu:
8997     case Intrinsic::arm_neon_vqshiftnsu:
8998     case Intrinsic::arm_neon_vqrshiftns:
8999     case Intrinsic::arm_neon_vqrshiftnu:
9000     case Intrinsic::arm_neon_vqrshiftnsu:
9001       // Narrowing shifts require an immediate right shift.
9002       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9003         break;
9004       llvm_unreachable("invalid shift count for narrowing vector shift "
9005                        "intrinsic");
9006
9007     default:
9008       llvm_unreachable("unhandled vector shift");
9009     }
9010
9011     switch (IntNo) {
9012     case Intrinsic::arm_neon_vshifts:
9013     case Intrinsic::arm_neon_vshiftu:
9014       // Opcode already set above.
9015       break;
9016     case Intrinsic::arm_neon_vshiftls:
9017     case Intrinsic::arm_neon_vshiftlu:
9018       if (Cnt == VT.getVectorElementType().getSizeInBits())
9019         VShiftOpc = ARMISD::VSHLLi;
9020       else
9021         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
9022                      ARMISD::VSHLLs : ARMISD::VSHLLu);
9023       break;
9024     case Intrinsic::arm_neon_vshiftn:
9025       VShiftOpc = ARMISD::VSHRN; break;
9026     case Intrinsic::arm_neon_vrshifts:
9027       VShiftOpc = ARMISD::VRSHRs; break;
9028     case Intrinsic::arm_neon_vrshiftu:
9029       VShiftOpc = ARMISD::VRSHRu; break;
9030     case Intrinsic::arm_neon_vrshiftn:
9031       VShiftOpc = ARMISD::VRSHRN; break;
9032     case Intrinsic::arm_neon_vqshifts:
9033       VShiftOpc = ARMISD::VQSHLs; break;
9034     case Intrinsic::arm_neon_vqshiftu:
9035       VShiftOpc = ARMISD::VQSHLu; break;
9036     case Intrinsic::arm_neon_vqshiftsu:
9037       VShiftOpc = ARMISD::VQSHLsu; break;
9038     case Intrinsic::arm_neon_vqshiftns:
9039       VShiftOpc = ARMISD::VQSHRNs; break;
9040     case Intrinsic::arm_neon_vqshiftnu:
9041       VShiftOpc = ARMISD::VQSHRNu; break;
9042     case Intrinsic::arm_neon_vqshiftnsu:
9043       VShiftOpc = ARMISD::VQSHRNsu; break;
9044     case Intrinsic::arm_neon_vqrshiftns:
9045       VShiftOpc = ARMISD::VQRSHRNs; break;
9046     case Intrinsic::arm_neon_vqrshiftnu:
9047       VShiftOpc = ARMISD::VQRSHRNu; break;
9048     case Intrinsic::arm_neon_vqrshiftnsu:
9049       VShiftOpc = ARMISD::VQRSHRNsu; break;
9050     }
9051
9052     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
9053                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9054   }
9055
9056   case Intrinsic::arm_neon_vshiftins: {
9057     EVT VT = N->getOperand(1).getValueType();
9058     int64_t Cnt;
9059     unsigned VShiftOpc = 0;
9060
9061     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9062       VShiftOpc = ARMISD::VSLI;
9063     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9064       VShiftOpc = ARMISD::VSRI;
9065     else {
9066       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9067     }
9068
9069     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
9070                        N->getOperand(1), N->getOperand(2),
9071                        DAG.getConstant(Cnt, MVT::i32));
9072   }
9073
9074   case Intrinsic::arm_neon_vqrshifts:
9075   case Intrinsic::arm_neon_vqrshiftu:
9076     // No immediate versions of these to check for.
9077     break;
9078   }
9079
9080   return SDValue();
9081 }
9082
9083 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9084 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9085 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9086 /// vector element shift counts are generally not legal, and it is hard to see
9087 /// their values after they get legalized to loads from a constant pool.
9088 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9089                                    const ARMSubtarget *ST) {
9090   EVT VT = N->getValueType(0);
9091   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9092     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9093     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9094     SDValue N1 = N->getOperand(1);
9095     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9096       SDValue N0 = N->getOperand(0);
9097       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9098           DAG.MaskedValueIsZero(N0.getOperand(0),
9099                                 APInt::getHighBitsSet(32, 16)))
9100         return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, N0, N1);
9101     }
9102   }
9103
9104   // Nothing to be done for scalar shifts.
9105   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9106   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9107     return SDValue();
9108
9109   assert(ST->hasNEON() && "unexpected vector shift");
9110   int64_t Cnt;
9111
9112   switch (N->getOpcode()) {
9113   default: llvm_unreachable("unexpected shift opcode");
9114
9115   case ISD::SHL:
9116     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9117       return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
9118                          DAG.getConstant(Cnt, MVT::i32));
9119     break;
9120
9121   case ISD::SRA:
9122   case ISD::SRL:
9123     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9124       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9125                             ARMISD::VSHRs : ARMISD::VSHRu);
9126       return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
9127                          DAG.getConstant(Cnt, MVT::i32));
9128     }
9129   }
9130   return SDValue();
9131 }
9132
9133 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9134 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9135 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9136                                     const ARMSubtarget *ST) {
9137   SDValue N0 = N->getOperand(0);
9138
9139   // Check for sign- and zero-extensions of vector extract operations of 8-
9140   // and 16-bit vector elements.  NEON supports these directly.  They are
9141   // handled during DAG combining because type legalization will promote them
9142   // to 32-bit types and it is messy to recognize the operations after that.
9143   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9144     SDValue Vec = N0.getOperand(0);
9145     SDValue Lane = N0.getOperand(1);
9146     EVT VT = N->getValueType(0);
9147     EVT EltVT = N0.getValueType();
9148     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9149
9150     if (VT == MVT::i32 &&
9151         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9152         TLI.isTypeLegal(Vec.getValueType()) &&
9153         isa<ConstantSDNode>(Lane)) {
9154
9155       unsigned Opc = 0;
9156       switch (N->getOpcode()) {
9157       default: llvm_unreachable("unexpected opcode");
9158       case ISD::SIGN_EXTEND:
9159         Opc = ARMISD::VGETLANEs;
9160         break;
9161       case ISD::ZERO_EXTEND:
9162       case ISD::ANY_EXTEND:
9163         Opc = ARMISD::VGETLANEu;
9164         break;
9165       }
9166       return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
9167     }
9168   }
9169
9170   return SDValue();
9171 }
9172
9173 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9174 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9175 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9176                                        const ARMSubtarget *ST) {
9177   // If the target supports NEON, try to use vmax/vmin instructions for f32
9178   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9179   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9180   // a NaN; only do the transformation when it matches that behavior.
9181
9182   // For now only do this when using NEON for FP operations; if using VFP, it
9183   // is not obvious that the benefit outweighs the cost of switching to the
9184   // NEON pipeline.
9185   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9186       N->getValueType(0) != MVT::f32)
9187     return SDValue();
9188
9189   SDValue CondLHS = N->getOperand(0);
9190   SDValue CondRHS = N->getOperand(1);
9191   SDValue LHS = N->getOperand(2);
9192   SDValue RHS = N->getOperand(3);
9193   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9194
9195   unsigned Opcode = 0;
9196   bool IsReversed;
9197   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9198     IsReversed = false; // x CC y ? x : y
9199   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9200     IsReversed = true ; // x CC y ? y : x
9201   } else {
9202     return SDValue();
9203   }
9204
9205   bool IsUnordered;
9206   switch (CC) {
9207   default: break;
9208   case ISD::SETOLT:
9209   case ISD::SETOLE:
9210   case ISD::SETLT:
9211   case ISD::SETLE:
9212   case ISD::SETULT:
9213   case ISD::SETULE:
9214     // If LHS is NaN, an ordered comparison will be false and the result will
9215     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9216     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9217     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9218     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9219       break;
9220     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9221     // will return -0, so vmin can only be used for unsafe math or if one of
9222     // the operands is known to be nonzero.
9223     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9224         !DAG.getTarget().Options.UnsafeFPMath &&
9225         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9226       break;
9227     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9228     break;
9229
9230   case ISD::SETOGT:
9231   case ISD::SETOGE:
9232   case ISD::SETGT:
9233   case ISD::SETGE:
9234   case ISD::SETUGT:
9235   case ISD::SETUGE:
9236     // If LHS is NaN, an ordered comparison will be false and the result will
9237     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9238     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9239     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9240     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9241       break;
9242     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9243     // will return +0, so vmax can only be used for unsafe math or if one of
9244     // the operands is known to be nonzero.
9245     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9246         !DAG.getTarget().Options.UnsafeFPMath &&
9247         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9248       break;
9249     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9250     break;
9251   }
9252
9253   if (!Opcode)
9254     return SDValue();
9255   return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
9256 }
9257
9258 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9259 SDValue
9260 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9261   SDValue Cmp = N->getOperand(4);
9262   if (Cmp.getOpcode() != ARMISD::CMPZ)
9263     // Only looking at EQ and NE cases.
9264     return SDValue();
9265
9266   EVT VT = N->getValueType(0);
9267   DebugLoc dl = N->getDebugLoc();
9268   SDValue LHS = Cmp.getOperand(0);
9269   SDValue RHS = Cmp.getOperand(1);
9270   SDValue FalseVal = N->getOperand(0);
9271   SDValue TrueVal = N->getOperand(1);
9272   SDValue ARMcc = N->getOperand(2);
9273   ARMCC::CondCodes CC =
9274     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9275
9276   // Simplify
9277   //   mov     r1, r0
9278   //   cmp     r1, x
9279   //   mov     r0, y
9280   //   moveq   r0, x
9281   // to
9282   //   cmp     r0, x
9283   //   movne   r0, y
9284   //
9285   //   mov     r1, r0
9286   //   cmp     r1, x
9287   //   mov     r0, x
9288   //   movne   r0, y
9289   // to
9290   //   cmp     r0, x
9291   //   movne   r0, y
9292   /// FIXME: Turn this into a target neutral optimization?
9293   SDValue Res;
9294   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9295     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9296                       N->getOperand(3), Cmp);
9297   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9298     SDValue ARMcc;
9299     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9300     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9301                       N->getOperand(3), NewCmp);
9302   }
9303
9304   if (Res.getNode()) {
9305     APInt KnownZero, KnownOne;
9306     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
9307     // Capture demanded bits information that would be otherwise lost.
9308     if (KnownZero == 0xfffffffe)
9309       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9310                         DAG.getValueType(MVT::i1));
9311     else if (KnownZero == 0xffffff00)
9312       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9313                         DAG.getValueType(MVT::i8));
9314     else if (KnownZero == 0xffff0000)
9315       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9316                         DAG.getValueType(MVT::i16));
9317   }
9318
9319   return Res;
9320 }
9321
9322 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9323                                              DAGCombinerInfo &DCI) const {
9324   switch (N->getOpcode()) {
9325   default: break;
9326   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9327   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9328   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9329   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9330   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9331   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9332   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9333   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9334   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9335   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9336   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9337   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9338   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9339   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9340   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9341   case ISD::FP_TO_SINT:
9342   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9343   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9344   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9345   case ISD::SHL:
9346   case ISD::SRA:
9347   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9348   case ISD::SIGN_EXTEND:
9349   case ISD::ZERO_EXTEND:
9350   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9351   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9352   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9353   case ARMISD::VLD2DUP:
9354   case ARMISD::VLD3DUP:
9355   case ARMISD::VLD4DUP:
9356     return CombineBaseUpdate(N, DCI);
9357   case ISD::INTRINSIC_VOID:
9358   case ISD::INTRINSIC_W_CHAIN:
9359     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9360     case Intrinsic::arm_neon_vld1:
9361     case Intrinsic::arm_neon_vld2:
9362     case Intrinsic::arm_neon_vld3:
9363     case Intrinsic::arm_neon_vld4:
9364     case Intrinsic::arm_neon_vld2lane:
9365     case Intrinsic::arm_neon_vld3lane:
9366     case Intrinsic::arm_neon_vld4lane:
9367     case Intrinsic::arm_neon_vst1:
9368     case Intrinsic::arm_neon_vst2:
9369     case Intrinsic::arm_neon_vst3:
9370     case Intrinsic::arm_neon_vst4:
9371     case Intrinsic::arm_neon_vst2lane:
9372     case Intrinsic::arm_neon_vst3lane:
9373     case Intrinsic::arm_neon_vst4lane:
9374       return CombineBaseUpdate(N, DCI);
9375     default: break;
9376     }
9377     break;
9378   }
9379   return SDValue();
9380 }
9381
9382 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9383                                                           EVT VT) const {
9384   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9385 }
9386
9387 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
9388   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9389   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9390
9391   switch (VT.getSimpleVT().SimpleTy) {
9392   default:
9393     return false;
9394   case MVT::i8:
9395   case MVT::i16:
9396   case MVT::i32: {
9397     // Unaligned access can use (for example) LRDB, LRDH, LDR
9398     if (AllowsUnaligned) {
9399       if (Fast)
9400         *Fast = Subtarget->hasV7Ops();
9401       return true;
9402     }
9403     return false;
9404   }
9405   case MVT::f64:
9406   case MVT::v2f64: {
9407     // For any little-endian targets with neon, we can support unaligned ld/st
9408     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9409     // A big-endian target may also explictly support unaligned accesses
9410     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9411       if (Fast)
9412         *Fast = true;
9413       return true;
9414     }
9415     return false;
9416   }
9417   }
9418 }
9419
9420 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9421                        unsigned AlignCheck) {
9422   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9423           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9424 }
9425
9426 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9427                                            unsigned DstAlign, unsigned SrcAlign,
9428                                            bool IsMemset, bool ZeroMemset,
9429                                            bool MemcpyStrSrc,
9430                                            MachineFunction &MF) const {
9431   const Function *F = MF.getFunction();
9432
9433   // See if we can use NEON instructions for this...
9434   if ((!IsMemset || ZeroMemset) &&
9435       Subtarget->hasNEON() &&
9436       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9437                                        Attribute::NoImplicitFloat)) {
9438     bool Fast;
9439     if (Size >= 16 &&
9440         (memOpAlign(SrcAlign, DstAlign, 16) ||
9441          (allowsUnalignedMemoryAccesses(MVT::v2f64, &Fast) && Fast))) {
9442       return MVT::v2f64;
9443     } else if (Size >= 8 &&
9444                (memOpAlign(SrcAlign, DstAlign, 8) ||
9445                 (allowsUnalignedMemoryAccesses(MVT::f64, &Fast) && Fast))) {
9446       return MVT::f64;
9447     }
9448   }
9449
9450   // Lowering to i32/i16 if the size permits.
9451   if (Size >= 4)
9452     return MVT::i32;
9453   else if (Size >= 2)
9454     return MVT::i16;
9455
9456   // Let the target-independent logic figure it out.
9457   return MVT::Other;
9458 }
9459
9460 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9461   if (Val.getOpcode() != ISD::LOAD)
9462     return false;
9463
9464   EVT VT1 = Val.getValueType();
9465   if (!VT1.isSimple() || !VT1.isInteger() ||
9466       !VT2.isSimple() || !VT2.isInteger())
9467     return false;
9468
9469   switch (VT1.getSimpleVT().SimpleTy) {
9470   default: break;
9471   case MVT::i1:
9472   case MVT::i8:
9473   case MVT::i16:
9474     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9475     return true;
9476   }
9477
9478   return false;
9479 }
9480
9481 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9482   if (V < 0)
9483     return false;
9484
9485   unsigned Scale = 1;
9486   switch (VT.getSimpleVT().SimpleTy) {
9487   default: return false;
9488   case MVT::i1:
9489   case MVT::i8:
9490     // Scale == 1;
9491     break;
9492   case MVT::i16:
9493     // Scale == 2;
9494     Scale = 2;
9495     break;
9496   case MVT::i32:
9497     // Scale == 4;
9498     Scale = 4;
9499     break;
9500   }
9501
9502   if ((V & (Scale - 1)) != 0)
9503     return false;
9504   V /= Scale;
9505   return V == (V & ((1LL << 5) - 1));
9506 }
9507
9508 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9509                                       const ARMSubtarget *Subtarget) {
9510   bool isNeg = false;
9511   if (V < 0) {
9512     isNeg = true;
9513     V = - V;
9514   }
9515
9516   switch (VT.getSimpleVT().SimpleTy) {
9517   default: return false;
9518   case MVT::i1:
9519   case MVT::i8:
9520   case MVT::i16:
9521   case MVT::i32:
9522     // + imm12 or - imm8
9523     if (isNeg)
9524       return V == (V & ((1LL << 8) - 1));
9525     return V == (V & ((1LL << 12) - 1));
9526   case MVT::f32:
9527   case MVT::f64:
9528     // Same as ARM mode. FIXME: NEON?
9529     if (!Subtarget->hasVFP2())
9530       return false;
9531     if ((V & 3) != 0)
9532       return false;
9533     V >>= 2;
9534     return V == (V & ((1LL << 8) - 1));
9535   }
9536 }
9537
9538 /// isLegalAddressImmediate - Return true if the integer value can be used
9539 /// as the offset of the target addressing mode for load / store of the
9540 /// given type.
9541 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9542                                     const ARMSubtarget *Subtarget) {
9543   if (V == 0)
9544     return true;
9545
9546   if (!VT.isSimple())
9547     return false;
9548
9549   if (Subtarget->isThumb1Only())
9550     return isLegalT1AddressImmediate(V, VT);
9551   else if (Subtarget->isThumb2())
9552     return isLegalT2AddressImmediate(V, VT, Subtarget);
9553
9554   // ARM mode.
9555   if (V < 0)
9556     V = - V;
9557   switch (VT.getSimpleVT().SimpleTy) {
9558   default: return false;
9559   case MVT::i1:
9560   case MVT::i8:
9561   case MVT::i32:
9562     // +- imm12
9563     return V == (V & ((1LL << 12) - 1));
9564   case MVT::i16:
9565     // +- imm8
9566     return V == (V & ((1LL << 8) - 1));
9567   case MVT::f32:
9568   case MVT::f64:
9569     if (!Subtarget->hasVFP2()) // FIXME: NEON?
9570       return false;
9571     if ((V & 3) != 0)
9572       return false;
9573     V >>= 2;
9574     return V == (V & ((1LL << 8) - 1));
9575   }
9576 }
9577
9578 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9579                                                       EVT VT) const {
9580   int Scale = AM.Scale;
9581   if (Scale < 0)
9582     return false;
9583
9584   switch (VT.getSimpleVT().SimpleTy) {
9585   default: return false;
9586   case MVT::i1:
9587   case MVT::i8:
9588   case MVT::i16:
9589   case MVT::i32:
9590     if (Scale == 1)
9591       return true;
9592     // r + r << imm
9593     Scale = Scale & ~1;
9594     return Scale == 2 || Scale == 4 || Scale == 8;
9595   case MVT::i64:
9596     // r + r
9597     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9598       return true;
9599     return false;
9600   case MVT::isVoid:
9601     // Note, we allow "void" uses (basically, uses that aren't loads or
9602     // stores), because arm allows folding a scale into many arithmetic
9603     // operations.  This should be made more precise and revisited later.
9604
9605     // Allow r << imm, but the imm has to be a multiple of two.
9606     if (Scale & 1) return false;
9607     return isPowerOf2_32(Scale);
9608   }
9609 }
9610
9611 /// isLegalAddressingMode - Return true if the addressing mode represented
9612 /// by AM is legal for this target, for a load/store of the specified type.
9613 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9614                                               Type *Ty) const {
9615   EVT VT = getValueType(Ty, true);
9616   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9617     return false;
9618
9619   // Can never fold addr of global into load/store.
9620   if (AM.BaseGV)
9621     return false;
9622
9623   switch (AM.Scale) {
9624   case 0:  // no scale reg, must be "r+i" or "r", or "i".
9625     break;
9626   case 1:
9627     if (Subtarget->isThumb1Only())
9628       return false;
9629     // FALL THROUGH.
9630   default:
9631     // ARM doesn't support any R+R*scale+imm addr modes.
9632     if (AM.BaseOffs)
9633       return false;
9634
9635     if (!VT.isSimple())
9636       return false;
9637
9638     if (Subtarget->isThumb2())
9639       return isLegalT2ScaledAddressingMode(AM, VT);
9640
9641     int Scale = AM.Scale;
9642     switch (VT.getSimpleVT().SimpleTy) {
9643     default: return false;
9644     case MVT::i1:
9645     case MVT::i8:
9646     case MVT::i32:
9647       if (Scale < 0) Scale = -Scale;
9648       if (Scale == 1)
9649         return true;
9650       // r + r << imm
9651       return isPowerOf2_32(Scale & ~1);
9652     case MVT::i16:
9653     case MVT::i64:
9654       // r + r
9655       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9656         return true;
9657       return false;
9658
9659     case MVT::isVoid:
9660       // Note, we allow "void" uses (basically, uses that aren't loads or
9661       // stores), because arm allows folding a scale into many arithmetic
9662       // operations.  This should be made more precise and revisited later.
9663
9664       // Allow r << imm, but the imm has to be a multiple of two.
9665       if (Scale & 1) return false;
9666       return isPowerOf2_32(Scale);
9667     }
9668   }
9669   return true;
9670 }
9671
9672 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9673 /// icmp immediate, that is the target has icmp instructions which can compare
9674 /// a register against the immediate without having to materialize the
9675 /// immediate into a register.
9676 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9677   // Thumb2 and ARM modes can use cmn for negative immediates.
9678   if (!Subtarget->isThumb())
9679     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9680   if (Subtarget->isThumb2())
9681     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9682   // Thumb1 doesn't have cmn, and only 8-bit immediates.
9683   return Imm >= 0 && Imm <= 255;
9684 }
9685
9686 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9687 /// *or sub* immediate, that is the target has add or sub instructions which can
9688 /// add a register with the immediate without having to materialize the
9689 /// immediate into a register.
9690 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9691   // Same encoding for add/sub, just flip the sign.
9692   int64_t AbsImm = llvm::abs64(Imm);
9693   if (!Subtarget->isThumb())
9694     return ARM_AM::getSOImmVal(AbsImm) != -1;
9695   if (Subtarget->isThumb2())
9696     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9697   // Thumb1 only has 8-bit unsigned immediate.
9698   return AbsImm >= 0 && AbsImm <= 255;
9699 }
9700
9701 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9702                                       bool isSEXTLoad, SDValue &Base,
9703                                       SDValue &Offset, bool &isInc,
9704                                       SelectionDAG &DAG) {
9705   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9706     return false;
9707
9708   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9709     // AddressingMode 3
9710     Base = Ptr->getOperand(0);
9711     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9712       int RHSC = (int)RHS->getZExtValue();
9713       if (RHSC < 0 && RHSC > -256) {
9714         assert(Ptr->getOpcode() == ISD::ADD);
9715         isInc = false;
9716         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9717         return true;
9718       }
9719     }
9720     isInc = (Ptr->getOpcode() == ISD::ADD);
9721     Offset = Ptr->getOperand(1);
9722     return true;
9723   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9724     // AddressingMode 2
9725     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9726       int RHSC = (int)RHS->getZExtValue();
9727       if (RHSC < 0 && RHSC > -0x1000) {
9728         assert(Ptr->getOpcode() == ISD::ADD);
9729         isInc = false;
9730         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9731         Base = Ptr->getOperand(0);
9732         return true;
9733       }
9734     }
9735
9736     if (Ptr->getOpcode() == ISD::ADD) {
9737       isInc = true;
9738       ARM_AM::ShiftOpc ShOpcVal=
9739         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9740       if (ShOpcVal != ARM_AM::no_shift) {
9741         Base = Ptr->getOperand(1);
9742         Offset = Ptr->getOperand(0);
9743       } else {
9744         Base = Ptr->getOperand(0);
9745         Offset = Ptr->getOperand(1);
9746       }
9747       return true;
9748     }
9749
9750     isInc = (Ptr->getOpcode() == ISD::ADD);
9751     Base = Ptr->getOperand(0);
9752     Offset = Ptr->getOperand(1);
9753     return true;
9754   }
9755
9756   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
9757   return false;
9758 }
9759
9760 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
9761                                      bool isSEXTLoad, SDValue &Base,
9762                                      SDValue &Offset, bool &isInc,
9763                                      SelectionDAG &DAG) {
9764   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9765     return false;
9766
9767   Base = Ptr->getOperand(0);
9768   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9769     int RHSC = (int)RHS->getZExtValue();
9770     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
9771       assert(Ptr->getOpcode() == ISD::ADD);
9772       isInc = false;
9773       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9774       return true;
9775     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
9776       isInc = Ptr->getOpcode() == ISD::ADD;
9777       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
9778       return true;
9779     }
9780   }
9781
9782   return false;
9783 }
9784
9785 /// getPreIndexedAddressParts - returns true by value, base pointer and
9786 /// offset pointer and addressing mode by reference if the node's address
9787 /// can be legally represented as pre-indexed load / store address.
9788 bool
9789 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9790                                              SDValue &Offset,
9791                                              ISD::MemIndexedMode &AM,
9792                                              SelectionDAG &DAG) const {
9793   if (Subtarget->isThumb1Only())
9794     return false;
9795
9796   EVT VT;
9797   SDValue Ptr;
9798   bool isSEXTLoad = false;
9799   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9800     Ptr = LD->getBasePtr();
9801     VT  = LD->getMemoryVT();
9802     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9803   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9804     Ptr = ST->getBasePtr();
9805     VT  = ST->getMemoryVT();
9806   } else
9807     return false;
9808
9809   bool isInc;
9810   bool isLegal = false;
9811   if (Subtarget->isThumb2())
9812     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9813                                        Offset, isInc, DAG);
9814   else
9815     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9816                                         Offset, isInc, DAG);
9817   if (!isLegal)
9818     return false;
9819
9820   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
9821   return true;
9822 }
9823
9824 /// getPostIndexedAddressParts - returns true by value, base pointer and
9825 /// offset pointer and addressing mode by reference if this node can be
9826 /// combined with a load / store to form a post-indexed load / store.
9827 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
9828                                                    SDValue &Base,
9829                                                    SDValue &Offset,
9830                                                    ISD::MemIndexedMode &AM,
9831                                                    SelectionDAG &DAG) const {
9832   if (Subtarget->isThumb1Only())
9833     return false;
9834
9835   EVT VT;
9836   SDValue Ptr;
9837   bool isSEXTLoad = false;
9838   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9839     VT  = LD->getMemoryVT();
9840     Ptr = LD->getBasePtr();
9841     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9842   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9843     VT  = ST->getMemoryVT();
9844     Ptr = ST->getBasePtr();
9845   } else
9846     return false;
9847
9848   bool isInc;
9849   bool isLegal = false;
9850   if (Subtarget->isThumb2())
9851     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9852                                        isInc, DAG);
9853   else
9854     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9855                                         isInc, DAG);
9856   if (!isLegal)
9857     return false;
9858
9859   if (Ptr != Base) {
9860     // Swap base ptr and offset to catch more post-index load / store when
9861     // it's legal. In Thumb2 mode, offset must be an immediate.
9862     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
9863         !Subtarget->isThumb2())
9864       std::swap(Base, Offset);
9865
9866     // Post-indexed load / store update the base pointer.
9867     if (Ptr != Base)
9868       return false;
9869   }
9870
9871   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
9872   return true;
9873 }
9874
9875 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9876                                                        APInt &KnownZero,
9877                                                        APInt &KnownOne,
9878                                                        const SelectionDAG &DAG,
9879                                                        unsigned Depth) const {
9880   KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
9881   switch (Op.getOpcode()) {
9882   default: break;
9883   case ARMISD::CMOV: {
9884     // Bits are known zero/one if known on the LHS and RHS.
9885     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
9886     if (KnownZero == 0 && KnownOne == 0) return;
9887
9888     APInt KnownZeroRHS, KnownOneRHS;
9889     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
9890     KnownZero &= KnownZeroRHS;
9891     KnownOne  &= KnownOneRHS;
9892     return;
9893   }
9894   }
9895 }
9896
9897 //===----------------------------------------------------------------------===//
9898 //                           ARM Inline Assembly Support
9899 //===----------------------------------------------------------------------===//
9900
9901 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
9902   // Looking for "rev" which is V6+.
9903   if (!Subtarget->hasV6Ops())
9904     return false;
9905
9906   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9907   std::string AsmStr = IA->getAsmString();
9908   SmallVector<StringRef, 4> AsmPieces;
9909   SplitString(AsmStr, AsmPieces, ";\n");
9910
9911   switch (AsmPieces.size()) {
9912   default: return false;
9913   case 1:
9914     AsmStr = AsmPieces[0];
9915     AsmPieces.clear();
9916     SplitString(AsmStr, AsmPieces, " \t,");
9917
9918     // rev $0, $1
9919     if (AsmPieces.size() == 3 &&
9920         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
9921         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
9922       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9923       if (Ty && Ty->getBitWidth() == 32)
9924         return IntrinsicLowering::LowerToByteSwap(CI);
9925     }
9926     break;
9927   }
9928
9929   return false;
9930 }
9931
9932 /// getConstraintType - Given a constraint letter, return the type of
9933 /// constraint it is for this target.
9934 ARMTargetLowering::ConstraintType
9935 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
9936   if (Constraint.size() == 1) {
9937     switch (Constraint[0]) {
9938     default:  break;
9939     case 'l': return C_RegisterClass;
9940     case 'w': return C_RegisterClass;
9941     case 'h': return C_RegisterClass;
9942     case 'x': return C_RegisterClass;
9943     case 't': return C_RegisterClass;
9944     case 'j': return C_Other; // Constant for movw.
9945       // An address with a single base register. Due to the way we
9946       // currently handle addresses it is the same as an 'r' memory constraint.
9947     case 'Q': return C_Memory;
9948     }
9949   } else if (Constraint.size() == 2) {
9950     switch (Constraint[0]) {
9951     default: break;
9952     // All 'U+' constraints are addresses.
9953     case 'U': return C_Memory;
9954     }
9955   }
9956   return TargetLowering::getConstraintType(Constraint);
9957 }
9958
9959 /// Examine constraint type and operand type and determine a weight value.
9960 /// This object must already have been set up with the operand type
9961 /// and the current alternative constraint selected.
9962 TargetLowering::ConstraintWeight
9963 ARMTargetLowering::getSingleConstraintMatchWeight(
9964     AsmOperandInfo &info, const char *constraint) const {
9965   ConstraintWeight weight = CW_Invalid;
9966   Value *CallOperandVal = info.CallOperandVal;
9967     // If we don't have a value, we can't do a match,
9968     // but allow it at the lowest weight.
9969   if (CallOperandVal == NULL)
9970     return CW_Default;
9971   Type *type = CallOperandVal->getType();
9972   // Look at the constraint type.
9973   switch (*constraint) {
9974   default:
9975     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
9976     break;
9977   case 'l':
9978     if (type->isIntegerTy()) {
9979       if (Subtarget->isThumb())
9980         weight = CW_SpecificReg;
9981       else
9982         weight = CW_Register;
9983     }
9984     break;
9985   case 'w':
9986     if (type->isFloatingPointTy())
9987       weight = CW_Register;
9988     break;
9989   }
9990   return weight;
9991 }
9992
9993 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
9994 RCPair
9995 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9996                                                 EVT VT) const {
9997   if (Constraint.size() == 1) {
9998     // GCC ARM Constraint Letters
9999     switch (Constraint[0]) {
10000     case 'l': // Low regs or general regs.
10001       if (Subtarget->isThumb())
10002         return RCPair(0U, &ARM::tGPRRegClass);
10003       return RCPair(0U, &ARM::GPRRegClass);
10004     case 'h': // High regs or no regs.
10005       if (Subtarget->isThumb())
10006         return RCPair(0U, &ARM::hGPRRegClass);
10007       break;
10008     case 'r':
10009       return RCPair(0U, &ARM::GPRRegClass);
10010     case 'w':
10011       if (VT == MVT::f32)
10012         return RCPair(0U, &ARM::SPRRegClass);
10013       if (VT.getSizeInBits() == 64)
10014         return RCPair(0U, &ARM::DPRRegClass);
10015       if (VT.getSizeInBits() == 128)
10016         return RCPair(0U, &ARM::QPRRegClass);
10017       break;
10018     case 'x':
10019       if (VT == MVT::f32)
10020         return RCPair(0U, &ARM::SPR_8RegClass);
10021       if (VT.getSizeInBits() == 64)
10022         return RCPair(0U, &ARM::DPR_8RegClass);
10023       if (VT.getSizeInBits() == 128)
10024         return RCPair(0U, &ARM::QPR_8RegClass);
10025       break;
10026     case 't':
10027       if (VT == MVT::f32)
10028         return RCPair(0U, &ARM::SPRRegClass);
10029       break;
10030     }
10031   }
10032   if (StringRef("{cc}").equals_lower(Constraint))
10033     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10034
10035   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10036 }
10037
10038 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10039 /// vector.  If it is invalid, don't add anything to Ops.
10040 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10041                                                      std::string &Constraint,
10042                                                      std::vector<SDValue>&Ops,
10043                                                      SelectionDAG &DAG) const {
10044   SDValue Result(0, 0);
10045
10046   // Currently only support length 1 constraints.
10047   if (Constraint.length() != 1) return;
10048
10049   char ConstraintLetter = Constraint[0];
10050   switch (ConstraintLetter) {
10051   default: break;
10052   case 'j':
10053   case 'I': case 'J': case 'K': case 'L':
10054   case 'M': case 'N': case 'O':
10055     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10056     if (!C)
10057       return;
10058
10059     int64_t CVal64 = C->getSExtValue();
10060     int CVal = (int) CVal64;
10061     // None of these constraints allow values larger than 32 bits.  Check
10062     // that the value fits in an int.
10063     if (CVal != CVal64)
10064       return;
10065
10066     switch (ConstraintLetter) {
10067       case 'j':
10068         // Constant suitable for movw, must be between 0 and
10069         // 65535.
10070         if (Subtarget->hasV6T2Ops())
10071           if (CVal >= 0 && CVal <= 65535)
10072             break;
10073         return;
10074       case 'I':
10075         if (Subtarget->isThumb1Only()) {
10076           // This must be a constant between 0 and 255, for ADD
10077           // immediates.
10078           if (CVal >= 0 && CVal <= 255)
10079             break;
10080         } else if (Subtarget->isThumb2()) {
10081           // A constant that can be used as an immediate value in a
10082           // data-processing instruction.
10083           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10084             break;
10085         } else {
10086           // A constant that can be used as an immediate value in a
10087           // data-processing instruction.
10088           if (ARM_AM::getSOImmVal(CVal) != -1)
10089             break;
10090         }
10091         return;
10092
10093       case 'J':
10094         if (Subtarget->isThumb()) {  // FIXME thumb2
10095           // This must be a constant between -255 and -1, for negated ADD
10096           // immediates. This can be used in GCC with an "n" modifier that
10097           // prints the negated value, for use with SUB instructions. It is
10098           // not useful otherwise but is implemented for compatibility.
10099           if (CVal >= -255 && CVal <= -1)
10100             break;
10101         } else {
10102           // This must be a constant between -4095 and 4095. It is not clear
10103           // what this constraint is intended for. Implemented for
10104           // compatibility with GCC.
10105           if (CVal >= -4095 && CVal <= 4095)
10106             break;
10107         }
10108         return;
10109
10110       case 'K':
10111         if (Subtarget->isThumb1Only()) {
10112           // A 32-bit value where only one byte has a nonzero value. Exclude
10113           // zero to match GCC. This constraint is used by GCC internally for
10114           // constants that can be loaded with a move/shift combination.
10115           // It is not useful otherwise but is implemented for compatibility.
10116           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10117             break;
10118         } else if (Subtarget->isThumb2()) {
10119           // A constant whose bitwise inverse can be used as an immediate
10120           // value in a data-processing instruction. This can be used in GCC
10121           // with a "B" modifier that prints the inverted value, for use with
10122           // BIC and MVN instructions. It is not useful otherwise but is
10123           // implemented for compatibility.
10124           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10125             break;
10126         } else {
10127           // A constant whose bitwise inverse can be used as an immediate
10128           // value in a data-processing instruction. This can be used in GCC
10129           // with a "B" modifier that prints the inverted value, for use with
10130           // BIC and MVN instructions. It is not useful otherwise but is
10131           // implemented for compatibility.
10132           if (ARM_AM::getSOImmVal(~CVal) != -1)
10133             break;
10134         }
10135         return;
10136
10137       case 'L':
10138         if (Subtarget->isThumb1Only()) {
10139           // This must be a constant between -7 and 7,
10140           // for 3-operand ADD/SUB immediate instructions.
10141           if (CVal >= -7 && CVal < 7)
10142             break;
10143         } else if (Subtarget->isThumb2()) {
10144           // A constant whose negation can be used as an immediate value in a
10145           // data-processing instruction. This can be used in GCC with an "n"
10146           // modifier that prints the negated value, for use with SUB
10147           // instructions. It is not useful otherwise but is implemented for
10148           // compatibility.
10149           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10150             break;
10151         } else {
10152           // A constant whose negation can be used as an immediate value in a
10153           // data-processing instruction. This can be used in GCC with an "n"
10154           // modifier that prints the negated value, for use with SUB
10155           // instructions. It is not useful otherwise but is implemented for
10156           // compatibility.
10157           if (ARM_AM::getSOImmVal(-CVal) != -1)
10158             break;
10159         }
10160         return;
10161
10162       case 'M':
10163         if (Subtarget->isThumb()) { // FIXME thumb2
10164           // This must be a multiple of 4 between 0 and 1020, for
10165           // ADD sp + immediate.
10166           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10167             break;
10168         } else {
10169           // A power of two or a constant between 0 and 32.  This is used in
10170           // GCC for the shift amount on shifted register operands, but it is
10171           // useful in general for any shift amounts.
10172           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10173             break;
10174         }
10175         return;
10176
10177       case 'N':
10178         if (Subtarget->isThumb()) {  // FIXME thumb2
10179           // This must be a constant between 0 and 31, for shift amounts.
10180           if (CVal >= 0 && CVal <= 31)
10181             break;
10182         }
10183         return;
10184
10185       case 'O':
10186         if (Subtarget->isThumb()) {  // FIXME thumb2
10187           // This must be a multiple of 4 between -508 and 508, for
10188           // ADD/SUB sp = sp + immediate.
10189           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10190             break;
10191         }
10192         return;
10193     }
10194     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10195     break;
10196   }
10197
10198   if (Result.getNode()) {
10199     Ops.push_back(Result);
10200     return;
10201   }
10202   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10203 }
10204
10205 bool
10206 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10207   // The ARM target isn't yet aware of offsets.
10208   return false;
10209 }
10210
10211 bool ARM::isBitFieldInvertedMask(unsigned v) {
10212   if (v == 0xffffffff)
10213     return 0;
10214   // there can be 1's on either or both "outsides", all the "inside"
10215   // bits must be 0's
10216   unsigned int lsb = 0, msb = 31;
10217   while (v & (1 << msb)) --msb;
10218   while (v & (1 << lsb)) ++lsb;
10219   for (unsigned int i = lsb; i <= msb; ++i) {
10220     if (v & (1 << i))
10221       return 0;
10222   }
10223   return 1;
10224 }
10225
10226 /// isFPImmLegal - Returns true if the target can instruction select the
10227 /// specified FP immediate natively. If false, the legalizer will
10228 /// materialize the FP immediate as a load from a constant pool.
10229 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10230   if (!Subtarget->hasVFP3())
10231     return false;
10232   if (VT == MVT::f32)
10233     return ARM_AM::getFP32Imm(Imm) != -1;
10234   if (VT == MVT::f64)
10235     return ARM_AM::getFP64Imm(Imm) != -1;
10236   return false;
10237 }
10238
10239 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10240 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10241 /// specified in the intrinsic calls.
10242 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10243                                            const CallInst &I,
10244                                            unsigned Intrinsic) const {
10245   switch (Intrinsic) {
10246   case Intrinsic::arm_neon_vld1:
10247   case Intrinsic::arm_neon_vld2:
10248   case Intrinsic::arm_neon_vld3:
10249   case Intrinsic::arm_neon_vld4:
10250   case Intrinsic::arm_neon_vld2lane:
10251   case Intrinsic::arm_neon_vld3lane:
10252   case Intrinsic::arm_neon_vld4lane: {
10253     Info.opc = ISD::INTRINSIC_W_CHAIN;
10254     // Conservatively set memVT to the entire set of vectors loaded.
10255     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10256     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10257     Info.ptrVal = I.getArgOperand(0);
10258     Info.offset = 0;
10259     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10260     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10261     Info.vol = false; // volatile loads with NEON intrinsics not supported
10262     Info.readMem = true;
10263     Info.writeMem = false;
10264     return true;
10265   }
10266   case Intrinsic::arm_neon_vst1:
10267   case Intrinsic::arm_neon_vst2:
10268   case Intrinsic::arm_neon_vst3:
10269   case Intrinsic::arm_neon_vst4:
10270   case Intrinsic::arm_neon_vst2lane:
10271   case Intrinsic::arm_neon_vst3lane:
10272   case Intrinsic::arm_neon_vst4lane: {
10273     Info.opc = ISD::INTRINSIC_VOID;
10274     // Conservatively set memVT to the entire set of vectors stored.
10275     unsigned NumElts = 0;
10276     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10277       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10278       if (!ArgTy->isVectorTy())
10279         break;
10280       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10281     }
10282     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10283     Info.ptrVal = I.getArgOperand(0);
10284     Info.offset = 0;
10285     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10286     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10287     Info.vol = false; // volatile stores with NEON intrinsics not supported
10288     Info.readMem = false;
10289     Info.writeMem = true;
10290     return true;
10291   }
10292   case Intrinsic::arm_strexd: {
10293     Info.opc = ISD::INTRINSIC_W_CHAIN;
10294     Info.memVT = MVT::i64;
10295     Info.ptrVal = I.getArgOperand(2);
10296     Info.offset = 0;
10297     Info.align = 8;
10298     Info.vol = true;
10299     Info.readMem = false;
10300     Info.writeMem = true;
10301     return true;
10302   }
10303   case Intrinsic::arm_ldrexd: {
10304     Info.opc = ISD::INTRINSIC_W_CHAIN;
10305     Info.memVT = MVT::i64;
10306     Info.ptrVal = I.getArgOperand(0);
10307     Info.offset = 0;
10308     Info.align = 8;
10309     Info.vol = true;
10310     Info.readMem = true;
10311     Info.writeMem = false;
10312     return true;
10313   }
10314   default:
10315     break;
10316   }
10317
10318   return false;
10319 }
10320